Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
256e648
feat(groups): follow-up, continuation, and close for group conversations
ginccc Jul 8, 2026
89da643
fix(groups): address PR #595 review findings for follow-up/continue/c…
ginccc Jul 13, 2026
f477cb1
fix(groups): fix CI + address multi-agent review findings on PR #595
ginccc Jul 13, 2026
05b6d64
test(groups): cover continueDiscussionStreaming (403 rethrow, SSE err…
ginccc Jul 13, 2026
8341fed
Merge origin/main into feat/group-followups
ginccc Jul 14, 2026
ff90745
fix(groups): resolve cross-feature review findings from the main merge
ginccc Jul 14, 2026
cd2040a
fix(groups): MCP ownership, CLOSED-blindness, atomic CAS + review bac…
ginccc Jul 14, 2026
516be0c
fix(groups): MCP owner resolution + honest /continue attachment contract
ginccc Jul 14, 2026
1e0858f
fix(groups): address CodeQL, Copilot and CodeRabbit PR review findings
ginccc Jul 14, 2026
e387b3e
Merge remote-tracking branch 'origin/main' into feat/group-followups
ginccc Jul 14, 2026
b3f945f
fix(groups): terminal-state integrity + no exception text in client b…
ginccc Jul 14, 2026
5b1328c
test(groups): mutation-audited regression coverage for the merge fixes
ginccc Jul 14, 2026
d1338a3
feat(groups): split follow-up/continue HTTP status codes by failure c…
ginccc Jul 15, 2026
38dfc45
fix(groups): mid-round member timeout maps to 504, not 502
ginccc Jul 15, 2026
9875e46
fix(groups): address Copilot PR review — MCP error curation, TEXT_PLA…
ginccc Jul 15, 2026
5268a72
fix(tools): make ToolExecutionTrace recording thread-safe
ginccc Jul 15, 2026
796fc08
Merge origin/main into feat/group-followups — resolve PR #595 conflicts
ginccc Jul 20, 2026
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
98 changes: 98 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,104 @@
> **Purpose:** Living document tracking all changes, decisions, and reasoning during implementation. Updated as work progresses for easy reference and review.


---

## 🔒 Group Conversation Follow-Ups — review-response hardening (2026-07-13)

**Repo:** EDDI (`feat/group-followups`)

Addresses static-analysis and code-review findings on [PR #595](https://github.com/labsai/EDDI/pull/595) (CodeQL, Copilot, CodeRabbit, GitHub Code Quality).

### Security & correctness

- **Log injection (CWE-117)**: sanitized user-controlled `groupConversationId` in log statements via `LogSanitizer.sanitize()` (`GroupConversationService` follow-up recovery, close, delete-not-found, and timeout-resolution paths).
- **Group-path validation**: `followup` / `continue` / `continue/stream` / `close` now verify the conversation belongs to the `{groupId}` in the path — mismatches return `404` (SSE `group_error` for the stream) via a shared `loadInGroup()` helper. Closes a "wrong group path" access gap **and** resolves the unused-`groupId` findings.
- **403 on streaming continue**: `continueDiscussionStreaming` now rethrows `ForbiddenException` so ownership failures map to HTTP `403` instead of a `200` SSE error event.

### Concurrency

- **Per-conversation operation guard**: `followUpWithMember` / `continueDiscussion` / `closeGroupConversation` acquire a fail-fast in-process guard (`ConcurrentHashMap.newKeySet()`) keyed by conversation ID; a second concurrent operation on the same conversation is rejected (`409`) rather than racing the `compareAndSetState` read-check-update. **NOTE:** single-node only — cluster-wide atomicity would require a conditional update at the storage layer (documented as future hardening, not built here).

### Resource lifecycle

- **`@PreDestroy` on `RestGroupConversation`**: the virtual-thread executor is now shut down on bean destroy.
- **Ephemeral cleanup on delete**: `deleteGroupConversation` now reclaims dynamically-created agents. Deferred cleanup previously ran only on `close`, so deleting a `COMPLETED` conversation orphaned them — this regression is introduced-and-fixed within the same feature branch. Extracted `cleanupEphemeralAgentsForGroup()` shared by close + delete.
- **Known limitations** (ephemeral-agent reclamation): (a) a `COMPLETED` conversation that is never closed *or* deleted still retains its ephemeral agents; (b) if cleanup fails on `delete` (group config already gone, or a transient undeploy error), the record is still hard-deleted, so the `createdAgentIds` mapping is lost and a future reaper cannot reclaim those agents (they remain operator-recoverable via the agent store). A TTL reaper (built on `ScheduleFireExecutor`) is the planned mitigation for (a) — tracked as a separate item.

### API cleanup

- **Removed dead `userId` param** from `followUpWithMember` / `continueDiscussion` (service interface, impl, REST, MCP tools). Ownership is validated via the stored conversation owner; the param was never used downstream.
- **Configurable follow-up timeout**: the follow-up agent call now uses the group's `protocol.agentTimeoutSeconds()` (default 60, consistent with discussion turns) via `resolveAgentTimeoutSeconds()`, instead of a hardcoded 120s.
- **Model encapsulation**: `GroupConversation.getMemberDisplayNames()` returns an unmodifiable view; population goes through the new `addMemberDisplayName()` method (the getter can no longer be mutated); the setter defensively copies.
- **OpenAPI**: added `404` responses to `followup` / `continue`, and `200` / `404` + event listing (incl. `round_start`) to `continue/stream`.

### Round 2 — multi-agent adversarial review + CI (2026-07-13)

Second pass after an adversarial multi-dimension review (concurrency / security / REST / lifecycle / test-coverage) plus the CI test run.

- **CI green**: updated the `GroupConversationState` (6→7, `CLOSED`) and `TranscriptEntryType` (14→15, `FOLLOW_UP`) enum-count guard tests. Added the three follow-up MCP tools (`followup_with_member`, `continue_group_discussion`, `close_group_conversation`) to `McpToolFilter` — they were **filtered out entirely** (never exposed to MCP clients) because the whitelist was never updated, so this is a functional fix, not just a test tweak.
- **Delete race** (flagged by two review dimensions): `deleteGroupConversation` now participates in the per-conversation guard. Because deferred cleanup made delete a *terminal* operation, an unguarded delete could tear down member conversations / ephemeral agents while a `continue`/`follow-up` was mid-run and then be resurrected as a "zombie" document via the store's upsert-by-id `update()`.
- **`close` status codes**: business conflicts (in-progress / wrong-state) now throw `GroupDiscussionException` → `409`; a genuine `ResourceStoreException` (DB failure) falls through to `500` via the global mapper, instead of every store error mapping to `409`. Aligns `close` with `followup`/`continue`.
- **Consistent group-scoping**: `readGroupConversation` and `deleteGroupConversation` now also route through `loadInGroup()`, so *every* endpoint under `/groups/{groupId}/conversations/{id}` verifies the conversation belongs to the path group (404 on mismatch). Previously only the new endpoints did.
- **CWE-117 in MCP tools**: the three new MCP follow-up tools now sanitize `e.getMessage()` before logging (`targetAgentId` is user-controlled and flows into exception messages).
- **Test coverage**: added unit tests for `getAvailableActions()` (per state), `memberDisplayNames` encapsulation, the `round` default, `compareAndSetState()` (all branches), `followUpWithMember` / `continueDiscussion` / `closeGroupConversation` service logic (display-name resolution, wrong-state, concurrency guard, state restore, round increment), and the new REST endpoints including the `loadInGroup` 404 guard.

### Deliberately not done

- **SSE listener factory extraction** (CodeRabbit nitpick): skipped — a pure DRY refactor of working, integration-only streaming code with no behavior gain.

### What's next

- TTL reaper for abandoned `COMPLETED` conversations (ephemeral-agent reclamation).
- Optional cluster-wide atomic state transition at the storage layer if concurrent group operations become a real deployment concern.
- Optional: sweep the remaining pre-existing `McpGroupTools` catch blocks for the same `LogSanitizer` treatment (≈11 older tools still use the unsanitized `errorf(..., e.getMessage())` pattern — lower priority, outside this PR's scope).

---

## ✨ Group Conversation Follow-Ups — member follow-up, continuation rounds, explicit close (2026-07-08)

**Repo:** EDDI (`feat/group-followups`)

### Summary

Adds three new interaction patterns for completed group conversations:
1. **Follow up with any member** — ask a specific agent (including the moderator) a question; both the question and response are appended to the group transcript as `FOLLOW_UP` entries
2. **Continue the full group** — re-run all discussion phases with a new question; agents retain conversation memory from prior rounds via reused private conversations; round counter increments
3. **Explicit close** — end member conversations, run ephemeral agent cleanup, lock the conversation permanently (`CLOSED` state)

### Changes

**Model layer:**
- `GroupConversation.java`: Added `round` field (1-based counter), `CLOSED` to `GroupConversationState`, `FOLLOW_UP` to `TranscriptEntryType`
- `IGroupConversationStore.java`: Added `compareAndSetState()` for optimistic concurrency control
- `GroupConversationStore.java`: Implemented `compareAndSetState()` (read-check-update pattern)

**Service layer:**
- `IGroupConversationService.java`: Added `followUpWithMember()`, `continueDiscussion()`, `closeGroupConversation()` + `onRoundStart()` listener method
- `GroupConversationService.java`: Implemented all three methods; modified `executeDiscussion()` to emit `round_start` SSE event (instead of `group_start`) for continuation rounds; deferred ephemeral agent cleanup to `closeGroupConversation()` for successful rounds (only immediate cleanup on failure)
- `GroupConversationEventSink.java`: Added `EVENT_ROUND_START` constant and `RoundStartEvent` record

**REST + MCP layer:**
- `IRestGroupConversation.java`: Added 4 endpoints (`POST /{gcId}/followup`, `POST /{gcId}/continue`, `POST /{gcId}/continue/stream`, `POST /{gcId}/close`) + `FollowUpRequest` record
- `RestGroupConversation.java`: Implemented all 4 endpoints with ownership validation and SSE streaming support for continuation
- `McpGroupTools.java`: Added `followup_with_member`, `continue_group_discussion`, `close_group_conversation` tools

### Design decisions

- **Concurrency**: `compareAndSetState(COMPLETED → IN_PROGRESS)` is a best-effort guard against overlapping follow-ups; state restored to `COMPLETED` on error. (Hardened on 2026-07-13 with a per-conversation in-process guard — see that entry.)
- **Deferred cleanup**: Ephemeral agents survive until explicit close so follow-ups can use dynamically-created agents; immediate cleanup only on failure
- **No TranscriptEntry.round field**: Round boundaries are inferred from `QUESTION` entries in the transcript — avoids churn on the 13-field record with 4 constructors
- **Plain-text follow-up *input***: The follow-up **input** is the plain question; the full transcript is still provided via the `groupTranscript` **context** variable (not re-injected into the input text), and the agent's private conversation retains prior turns

### Client experience improvements (follow-up commit)

- **Consistent response shapes**: All endpoints (`followup`, `continue`, `close`) now return the full `GroupConversation` — same shape as the initial `discuss` endpoint
- **Display name resolution**: `followUpWithMember` accepts either an agent ID or a display name (case-insensitive). Error messages list available members if target not found
- **`memberDisplayNames` map**: New field on `GroupConversation` maps agentId → displayName, populated at discussion start from group config. Eliminates client-side transcript scanning
- **`availableActions` computed property**: JSON response includes `["followup", "continue", "close"]` when COMPLETED, `["close"]` when FAILED, `[]` otherwise. Clients can discover available operations without reading docs
- **Close returns body**: `/close` now returns the closed `GroupConversation` with `state: CLOSED` and `availableActions: []`
- **Lifecycle documented in OpenAPI**: Close endpoint description includes `discuss → COMPLETED → [followup|continue]* → close → CLOSED (terminal)`

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
---

## 🐛 Fix: PostgreSQL group conversations broken — JDBC `?|` operator escape (2026-07-02)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,13 @@ public interface IGroupConversationStore {
void delete(String id) throws IResourceStore.ResourceStoreException;

List<GroupConversation> listByGroupId(String groupId, int index, int limit) throws IResourceStore.ResourceStoreException;

/**
* Atomically transition a group conversation from expectedState to newState.
* Returns true if the transition succeeded (state matched), false if the state
* had already changed (concurrent modification).
*/
boolean compareAndSetState(String id, GroupConversation.GroupConversationState expectedState,
GroupConversation.GroupConversationState newState)
throws IResourceStore.ResourceStoreException, IResourceStore.ResourceNotFoundException;
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
package ai.labs.eddi.configs.groups.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand All @@ -28,10 +30,17 @@ public class GroupConversation {
private String originalQuestion;
private List<TranscriptEntry> transcript = Collections.synchronizedList(new ArrayList<>());
private Map<String, String> memberConversationIds = new ConcurrentHashMap<>();
/**
* Maps agentId → displayName for all group members. Populated at discussion
* start.
*/
private Map<String, String> memberDisplayNames = new LinkedHashMap<>();
private int currentPhaseIndex;
private String currentPhaseName;
private String synthesizedAnswer;
private int depth;
/** Current discussion round (1-based). Incremented by continueDiscussion(). */
private int round = 1;
private SharedTaskList taskList;
/** Agents dynamically added during the discussion (recruited or created). */
private List<AgentGroupConfiguration.GroupMember> dynamicMembers = Collections.synchronizedList(new ArrayList<>());
Expand Down Expand Up @@ -121,13 +130,20 @@ public enum TranscriptEntryType {
/** Task execution result from the EXECUTE phase. */
TASK_RESULT,
/** Verification assessment from the VERIFY phase. */
VERIFICATION
VERIFICATION,
/** User-to-member or member-to-user follow-up exchange between rounds. */
FOLLOW_UP
}

public enum GroupConversationState {
CREATED, IN_PROGRESS, SYNTHESIZING, COMPLETED, FAILED,
/** Paused for human approval — HITL foundation (Phase 9b). */
AWAITING_APPROVAL
AWAITING_APPROVAL,
/**
* Terminal — member conversations ended, ephemeral agents cleaned up, no
* further follow-ups.
*/
CLOSED
}

// --- Getters/Setters ---
Expand Down Expand Up @@ -224,6 +240,14 @@ public void setDepth(int depth) {
this.depth = depth;
}

public int getRound() {
return round;
}

public void setRound(int round) {
this.round = round;
}

public Instant getCreated() {
return created;
}
Expand Down Expand Up @@ -296,4 +320,40 @@ public AgentGroupConfiguration.DynamicAgentConfig getDynamicAgentConfig() {
public void setDynamicAgentConfig(AgentGroupConfiguration.DynamicAgentConfig dynamicAgentConfig) {
this.dynamicAgentConfig = dynamicAgentConfig;
}

public Map<String, String> getMemberDisplayNames() {
Comment thread
github-code-quality[bot] marked this conversation as resolved.
Fixed
return Collections.unmodifiableMap(memberDisplayNames);
}

public void setMemberDisplayNames(Map<String, String> memberDisplayNames) {
this.memberDisplayNames = memberDisplayNames != null
? new LinkedHashMap<>(memberDisplayNames)
: new LinkedHashMap<>();
}

/**
* Register a member's display name (agentId → displayName). Used at discussion
* start to populate the map. This is the supported mutation path —
* {@link #getMemberDisplayNames()} returns an unmodifiable view.
*/
public void addMemberDisplayName(String agentId, String displayName) {
this.memberDisplayNames.put(agentId, displayName);
}

/**
* Computed property — not persisted. Tells clients which operations are
* available based on the current conversation state.
*/
Comment thread
ginccc marked this conversation as resolved.
Resolved
@JsonProperty(value = "availableActions", access = JsonProperty.Access.READ_ONLY)
public List<String> getAvailableActions() {
if (state == null) {
return List.of();
}
return switch (state) {
case COMPLETED -> List.of("followup", "continue", "close");
case FAILED -> List.of("close");
case IN_PROGRESS, SYNTHESIZING, CREATED, AWAITING_APPROVAL -> List.of();
case CLOSED -> List.of();
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,18 @@ public List<GroupConversation> listByGroupId(String groupId, int index, int limi
}
return results;
}

@Override
public boolean compareAndSetState(String id, GroupConversation.GroupConversationState expectedState,
GroupConversation.GroupConversationState newState)
throws IResourceStore.ResourceStoreException, IResourceStore.ResourceNotFoundException {
GroupConversation gc = read(id);
if (gc.getState() != expectedState) {
return false;
}
gc.setState(newState);
gc.setLastModified(java.time.Instant.now());
update(gc);
return true;
Comment thread
ginccc marked this conversation as resolved.
Resolved
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,43 @@ GroupConversation readGroupConversation(String groupConversationId)
*/
List<GroupConversation> listGroupConversations(String groupId, int index, int limit) throws IResourceStore.ResourceStoreException;

/**
* Send a follow-up question to a specific member agent within a completed group
* conversation. The exchange (user question + agent response) is appended to
* the group transcript. The agent retains full context from its participation
* in prior rounds via its reused private conversation.
*
* <p>
* The {@code targetAgentId} can be either an agent ID or a display name.
* Display names are resolved against
* {@link GroupConversation#getMemberDisplayNames()}.
*
* @return the updated group conversation with the follow-up appended to the
* transcript
*/
GroupConversation followUpWithMember(String groupConversationId, String targetAgentId,
String question)
throws GroupDiscussionException, IResourceStore.ResourceStoreException, IResourceStore.ResourceNotFoundException;

/**
* Continue a completed group conversation with a new question. All phases
* re-execute with the new question; agents retain conversation memory from
* prior rounds via their reused private conversations. The round counter
* increments.
*/
GroupConversation continueDiscussion(String groupConversationId, String question,
GroupDiscussionEventListener listener)
throws GroupDiscussionException, IResourceStore.ResourceStoreException, IResourceStore.ResourceNotFoundException;

/**
* Explicitly close a group conversation. Ends all member conversations,
* triggers ephemeral agent cleanup, and sets state to CLOSED. Irreversible.
*
* @return the closed group conversation
*/
GroupConversation closeGroupConversation(String groupConversationId)
throws GroupDiscussionException, IResourceStore.ResourceStoreException, IResourceStore.ResourceNotFoundException;

// --- Event listener for SSE streaming ---

interface GroupDiscussionEventListener {
Expand All @@ -89,6 +126,8 @@ default void onTaskPlanCreated(GroupConversationEventSink.TaskPlanCreatedEvent e
}
default void onTaskVerified(GroupConversationEventSink.TaskVerifiedEvent event) {
}
default void onRoundStart(GroupConversationEventSink.RoundStartEvent event) {
}
}

// --- Exceptions ---
Expand Down
Loading
Loading