Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,36 @@
> **Purpose:** Living document tracking all changes, decisions, and reasoning during implementation. Updated as work progresses for easy reference and review.


---

## 🔐 fix(agents): dynamic-agent guardrails — permissive fallback on resume, per-member caps, duplicate recruits, V7 (2026-08-09)

**Repo:** EDDI (`fix/dynamic-agent-guardrails`)

Wave B of the Agent / Group Agent review. These are the guardrails on the highest-blast-radius capability in the product — an LLM deploying agents to production — and they were the weakest-enforced things in the system.

1. **CRITICAL — a group's `dynamicAgents` policy silently reverted to fully permissive on a resumed member turn.** `resolveDynamicAgentConfig` accepted only a *typed* `DynamicAgentConfig` out of the context value; every other consumer of context data in the codebase handles the deserialized shape. A `Context` whose value round-trips through the conversation store comes back as a raw `LinkedHashMap` (`ConversationMemoryStore` rebuilds it as `new Context(type, map.get("value"))`), so any turn running against a *reloaded* step missed the `instanceof` and fell through to `createDefaultDynamicConfig()` — creation, recruitment and delegation all **on**, for a group that may have disabled every one of them. The trigger is an ordinary group path: a member's gated tool call is auto-rejected by `MemberTurnExecutor#tryResolveMemberToolPause`, which resumes the member conversation, and `Conversation#resume` re-enters the same LlmTask at the same index against memory freshly loaded from the store. The orchestrator is still blocked in that call, so the discussion is also still live in `LiveDiscussionRegistry` and the group-gated tools are available too. Resolution is now three-state and **fails closed**: key absent → standalone → permissive default; key present and readable (typed *or* map) → the group's policy; key present but unreadable → every capability off. "The operator said something we cannot parse" must never resolve to "the operator said yes to everything".
2. **`maxCreatedAgentsPerDiscussion` was enforced per member conversation, not per discussion.** `seedCreatedAgentIds` has always read a `dynamicCreatedAgentIds` context variable for the discussion-wide total, but nothing wrote it — so the cap bounded each member independently and a 5-member group with the default cap of 5 could deploy **25** agents to production, while both the field name and `docs/group-conversations.md` promised 5. `MemberTurnExecutor` now injects `gc.getCreatedAgentIds()` alongside the policy it already injects per turn.
3. **`RecruitAgentTool` could re-recruit a configured member.** Its Javadoc claimed the configured roster counted, but `isAlreadyMember` checked only `recruitedAgentIds`, `dynamicMembers` and `memberConversationIds` — and the last holds an agent only once it has *spoken*. A member whose first turn had not come up yet could be "recruited" as a duplicate: the roster union de-duplicated so nobody spoke twice, but the recruitment cap was consumed, a misleading FACILITATION entry was written, and `addMemberDisplayName` **overwrote the operator-chosen display name with the raw agent id**. The tool now receives the configured roster (resolved the same way `ArtifactToolsProvider` resolves its artifact policy), and display-name recording became `putIfAbsent`.
4. **Teardown never freed a creation slot, and a failed delete orphaned the agent.** `createdAgentIds.remove` ran *before* the delete, so a failed delete left the agent untracked and ephemeral cleanup never retried it — config and deployment record orphaned. And the removal was from a per-turn list that `seedCreatedAgentIds` rebuilds from every earlier step, so the id came straight back and the cap counted an agent that no longer exists forever. Teardown now records into `dynamic:torn_down_agent_ids`, which the seed subtracts and `propagateDynamicAgentTracking` applies to the group's own tracking; the tracking removal moved after the successful delete.
5. **V7 resolved — an omitted `builtInToolsWhitelist` no longer skips the dynamic-agent tools.** `docs/langchain.md` states twice that omitting the whitelist enables all built-in tools, and `BuiltinToolsProvider` implements exactly that; this provider alone returned early. `collectAllBuiltInTools` now calls it unconditionally. **Deliberately narrower than "all" in one respect:** the omitted case is honoured only when a group policy governs the turn. `dynamicAgents` is a field on `AgentGroupConfiguration`, so a standalone conversation has no surface on which an operator could have declined — handing it unconfigurable, production-deploying capabilities because it omitted a list would be a worse defect than the asymmetry being fixed. Under a group policy the operator *has* that surface, which is what makes "all" safe to mean all.

The three dynamic-agent tracking keys moved to `MemoryKeys` (`DYNAMIC_CREATED_AGENT_IDS`, `DYNAMIC_RETAINED_AGENT_IDS`, `DYNAMIC_TORN_DOWN_AGENT_IDS`) — the group layer reads them positionally out of a serialized snapshot, so both sides now name one constant instead of two string literals.

**Behaviour changes, deliberate:** (a) a group whose policy cannot be read now gets no dynamic-agent capabilities instead of all of them; (b) an agent in a group with `enableBuiltInTools=true` and no whitelist now receives the dynamic-agent tools its group policy permits.

**Review round 1 (PR #649).** Seven findings from CodeRabbit; six fixed, one declined:
- **Major, security — `teardown_agent` was not gated on the policy.** Its assembly branch checked only that the stores were present, and the tool itself takes no `DynamicAgentConfig`, so a group whose policy is disabled — or unreadable, which now resolves fail-closed — could still undeploy and **permanently delete** a tracked agent. A hole the V7 change widened, since an omitted whitelist now reaches this branch. Gated on `dynamicConfig.isEnabled()`.
- **Major — an unreadable roster failed open.** `configuredMemberIds` returned an empty set for both "no members" and "could not read", so a store hiccup silently restored the duplicate-recruit defect the change exists to prevent. It now returns `Optional`, and an unavailable roster **withholds `recruit_agent`** for that turn — gate by absence, matching `ArtifactToolsProvider`.
- **Major — stale snapshots could resurrect a torn-down agent.** Each member's tracking snapshot is one member's view: member B's turn can still name an agent member A tore down in between, and the merge re-added it. `GroupConversation` now carries a `tornDownAgentIds` tombstone, written before the merge by `recordTeardown` and consulted by it, so a teardown is final regardless of arrival order.
- **Major — the created-agent merge was not atomic.** `CopyOnWriteArrayList` makes each `add` atomic but not `contains()`-then-`add()`, and merges run on one coordinator thread per member turn; two could both append the same id, after which the single `remove()` a teardown performs leaves a duplicate. The compound operation now runs under the list's monitor, the same pattern `RecruitAgentTool` uses for `recruitedAgentIds`.
- **Major — `setMemberDisplayNames` installed a `LinkedHashMap`.** Every reload therefore dropped the concurrency guarantee the field declares, on a map written from member-turn threads and iterated by serialization — and `addMemberDisplayNameIfAbsent` depends on `putIfAbsent` being atomic. Now `ConcurrentHashMap` on both branches.
- **Declined — atomic reservation of creation capacity before dispatch.** Correct that parallel member turns can each read a stale count and collectively overshoot the cap. That is the same accepted-overshoot shape this codebase already documents for the cost ceiling ("an in-flight turn may still push the total past the ceiling; that overshoot is accepted, not prevented" — `GroupCostLedger`), and closing it properly needs budget *reservation* at dispatch, which is a design change rather than a fix. The cap moves from unbounded-per-member to bounded-with-parallel-overshoot; the residue is recorded rather than silently fixed.

**Review round 2 (PR #649).** One further finding, and a correct one: ordering the writes inside `recordTeardown` did not by itself close the race. A merge could read the tombstone set, find the id absent, be descheduled while a concurrent teardown recorded it, and then complete its own `add` — putting back an agent that no longer exists. The retained branch had the same shape and sat outside the monitor entirely. Check-tombstone-then-add and record-teardown are now mutually exclusive on a shared `dynamicTrackingMutex` (transient + `@JsonIgnore`, the `artifactAnnounceMutex` pattern), covering both the created and retained merges. Pinned by two 200-round interleaving tests, mutation-verified.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Suites: 869 tests green across `GroupConversationService*`, `GroupLifecycleOps*`, `LlmTask*`, `ConversationHitl*`, `ConversationToolResume*`, plus 487 across the orchestrator/tool suites; 25 new tests in two classes.

---

## 🔎 fix(groups): pre-merge deep review — facilitator HITL bypass, CALL_VOTE guards, metric cardinality, template honesty (2026-08-08)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,19 @@ public void setAnonymousSummaryUpToIndex(int anonymousSummaryUpToIndex) {
private List<String> recruitedAgentIds = new CopyOnWriteArrayList<>();
/** Agent IDs explicitly retained by the creating agent (skip cleanup). */
private Set<String> retainedAgentIds = ConcurrentHashMap.newKeySet();
/**
* Agent IDs torn down during this discussion — a tombstone, not a log.
* <p>
* {@code propagateDynamicAgentTracking} folds each member turn's
* {@code dynamic:created_agent_ids} snapshot into {@link #createdAgentIds}, and
* those snapshots are per-member and can arrive stale: member B's turn can
* carry a created list that still names an agent member A tore down between the
* two. Without a tombstone the id is simply re-added, so it keeps occupying a
* {@code maxCreatedAgentsPerDiscussion} slot and terminal cleanup keeps
* retrying its deletion. This set is consulted on every merge, so a teardown is
* final regardless of which order the snapshots land in.
*/
private Set<String> tornDownAgentIds = ConcurrentHashMap.newKeySet();
private int pausedAtPhaseIndex = -1;
private int pausedTurnCount = 0;
/**
Expand Down Expand Up @@ -1173,6 +1186,69 @@ public void setRetainedAgentIds(Set<String> retainedAgentIds) {
this.retainedAgentIds = newSet;
}

public Set<String> getTornDownAgentIds() {
return tornDownAgentIds;
}

public void setTornDownAgentIds(Set<String> tornDownAgentIds) {
Set<String> newSet = ConcurrentHashMap.newKeySet();
if (tornDownAgentIds != null) {
newSet.addAll(tornDownAgentIds);
}
this.tornDownAgentIds = newSet;
}

/**
* The monitor that serializes dynamic-agent tracking changes — teardowns
* against merges.
* <p>
* Ordering the writes inside {@link #recordTeardown} is NOT sufficient on its
* own, and the gap is easy to miss: a merge can read the tombstone set, find
* the id absent, be descheduled, have a concurrent teardown record the
* tombstone and remove the id, and then complete its own {@code add} — putting
* back an agent that no longer exists. Check-tombstone-then-add and
* record-teardown must therefore be mutually exclusive, not merely internally
* ordered.
* <p>
* Transient and {@link JsonIgnore}d like {@link #artifactAnnounceMutex}: it is
* runtime coordination state, and the field initialiser runs on Jackson's
* no-arg constructor so a deserialized document has one too.
*/
@JsonIgnore
private final transient Object dynamicTrackingMutex = new Object();

/**
* The monitor {@code GroupLifecycleOps#propagateDynamicAgentTracking} holds
* while it merges a member turn's tracking snapshot.
*/
@JsonIgnore
public Object dynamicTrackingMutex() {
return dynamicTrackingMutex;
}

/**
* Records a teardown and drops the agent from every live tracking list, as one
* atomic operation.
* <p>
* The tombstone is written first AND under {@link #dynamicTrackingMutex}, so a
* concurrent merge cannot interleave between the check it makes and the add it
* performs. The merge consults the tombstone precisely to refuse a stale
* snapshot, and it can only do that reliably if the two never overlap.
*
* @return {@code true} if this call was the one that recorded the teardown
*/
public boolean recordTeardown(String agentId) {
if (agentId == null) {
return false;
}
synchronized (dynamicTrackingMutex) {
boolean first = tornDownAgentIds.add(agentId);
createdAgentIds.remove(agentId);
retainedAgentIds.remove(agentId);
return first;
}
}

@JsonIgnore
public AgentGroupConfiguration.DynamicAgentConfig getDynamicAgentConfig() {
return dynamicAgentConfig;
Expand All @@ -1186,10 +1262,20 @@ public Map<String, String> getMemberDisplayNames() {
return Collections.unmodifiableMap(memberDisplayNames);
}

/**
* ConcurrentHashMap on BOTH branches, matching the field initialiser.
* <p>
* The setter installed a {@link LinkedHashMap}, so a conversation loaded from
* the store — every resume, every read-repair — silently lost the concurrency
* guarantee the field declares. That map is written from member-turn threads
* ({@code RecruitAgentTool}) and iterated by serialization, and
* {@link #addMemberDisplayNameIfAbsent} depends on {@code putIfAbsent} being
* atomic, which on a LinkedHashMap it is not.
*/
public void setMemberDisplayNames(Map<String, String> memberDisplayNames) {
this.memberDisplayNames = memberDisplayNames != null
? new LinkedHashMap<>(memberDisplayNames)
: new LinkedHashMap<>();
? new ConcurrentHashMap<>(memberDisplayNames)
: new ConcurrentHashMap<>();
}

/**
Expand All @@ -1201,6 +1287,20 @@ public void addMemberDisplayName(String agentId, String displayName) {
this.memberDisplayNames.put(agentId, displayName);
}

/**
* Records a display name only if the agent has none yet.
* <p>
* The seeding pass at the top of {@code executeDiscussion} fills this map from
* the CONFIGURED roster, where the names are operator-chosen. A later writer
* that only knows an agent id — {@code RecruitAgentTool}, which passes the id
* as the name — must not overwrite one of those; doing so replaced a member's
* real name with a raw id everywhere it is rendered, including the "which
* member did you mean?" list {@code followUpWithMember} produces.
*/
public void addMemberDisplayNameIfAbsent(String agentId, String displayName) {
this.memberDisplayNames.putIfAbsent(agentId, displayName);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/**
* Computed property derived from {@link #state} — tells clients which
* operations are available. It is serialized (so REST/MCP clients see it, and
Expand Down
Loading
Loading