diff --git a/docs/changelog.md b/docs/changelog.md index ee8c2de20b..812b9ec848 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -3,6 +3,332 @@ > **Purpose:** Living document tracking all changes, decisions, and reasoning during implementation. Updated as work progresses for easy reference and review. +--- + +## πŸ”€ Merge `origin/main` into `feat/group-followups` β€” conflict resolution (2026-07-20) + +**Repo:** EDDI (`feat/group-followups`) + +Merged `origin/main` (multi-model cascade enterprise hardening + MCP/REST conversation-ownership security hardening) to resolve PR #595's merge conflicts against `main`. Two files conflicted, both non-substantive: + +- **`ToolExecutionTrace.java`:** both branches independently documented the same `synchronized` rationale on `addToolCall`/`addFailedToolCall` β€” ours as a Javadoc block above each method, `origin/main`'s as an inline comment restating it. Kept the existing Javadoc, dropped the redundant inline comment. +- **`docs/changelog.md`:** both branches appended new entries directly below the file header. Resolved as a union, newest-first per branch: this branch's own entries (group follow-ups work, 2026-07-08 to 2026-07-15) kept first, followed by `origin/main`'s entries (MCP/REST conversation-ownership hardening + multi-model cascade, 2026-07-03 to 2026-07-15). + +--- + +## 🧡 ToolExecutionTrace β€” thread-safe recording (fixes CI flake) (2026-07-15) + +**Repo:** EDDI (`feat/group-followups`) β€” a **pre-existing** bug on `main`, unrelated to the group work, that surfaced as an intermittent full-suite CI failure on this branch: `ToolExecutionServiceBranchTest.executeMultipleInParallel` β†’ `expected but was `. Committed here to unblock this branch's CI (per decision), clearly scoped as an independent fix. + +**Root cause (systematic-debugging, root-caused before any fix):** `ToolExecutionService.executeToolsParallel` shares **one** `ToolExecutionTrace` across every concurrent task by design (it's the accumulator). But the trace's `addToolCall` / `addFailedToolCall` mutated a plain `ArrayList`, a plain `HashMap` (`toolMetrics`), and non-atomic counters with no synchronization. Under real parallelism, `HashMap.computeIfAbsent` detects concurrent structural modification and throws `ConcurrentModificationException`; `executeTool` catches it and returns `"Error executing tool: " + e.getClass().getSimpleName()` (CME's message is null) β€” the exact observed string. This is a genuine production bug: `executeToolsParallelAndWait` is a live API. + +**Fix:** `synchronized` on both trace mutators, serializing concurrent recording (covers the collection adds, the `computeIfAbsent`, and the primitive accumulations). `updateMetrics` is private and only called under those locks. Reads happen after `CompletableFuture.allOf(...).join()` (a happens-before edge), so writer synchronization is sufficient. + +**Coverage:** new `concurrentToolsShareTraceWithoutCorruption` stress test β€” 50 rounds Γ— 32 parallel tasks sharing one trace, asserting no task returns an error string and every call is recorded exactly once (no lost `ArrayList` updates). It fails reliably on the unsynchronized version (reproduced the CME at round 41) and passes 5/5 with the fix. The original 2-task test had too small a race window to be a reliable regression guard. + +--- + +## πŸ” Group conversations β€” Copilot PR-review response (2026-07-15) + +**Repo:** EDDI (`feat/group-followups`) + +Copilot flagged 5 items on the pushed branch. Each was adversarially verified against the actual code (a 6-agent verification workflow plus independent reading) before implementing β€” external review is evaluated, not rubber-stamped. **All 5 confirmed**, all fixed: + +- **MCP raw-exception leak (Γ—3, Medium)** β€” `followup_with_member`, `continue_group_discussion`, `close_group_conversation` returned `errorJson(e.getMessage())`, forwarding raw internal exception text to MCP callers (information exposure). Now each logs the full throwable server-side (`LOGGER.error(msg, e)`) and returns a stable curated `errorJson("Failed to …", "INTERNAL", null)` β€” matching the hardened `McpHitlTools` convention. (Verified the 3-arg `errorJson` overload exists, so this compiles; Copilot's suggested form was correct despite its own hedge.) +- **REST 400 missing `TEXT_PLAIN` (Medium)** β€” `rejectAttachmentsOnContinue()` was the sole error response in `RestGroupConversation` not setting `.type(TEXT_PLAIN)`. Added, for content-type consistency with every sibling 400/404/409/504. +- **Stale concurrency comment (Low)** β€” the `operationsInProgress` field comment called `compareAndSetState` a "best-effort read-check-update". That is now false: `GroupConversationStore.compareAndSetState` does a fast-path read then an **atomic** storage-layer conditional write (`storeIfFieldEquals` β†’ single Mongo `updateOne` / Postgres `UPDATE` filtered on the current `state`). Corrected the comment: the in-memory `Set` is a single-node fast-fail optimization; the cluster-wide guard is the storage CAS. + +**Coverage (mutation-verified):** three new `McpGroupToolsTest` cases drive each tool's generic `catch` (service throws a recognizable `boom-internal-detail-42`) and assert the response does **not** contain the raw text and **does** contain the curated message + `"errorCode":"INTERNAL"`. Reverting all three curations fails exactly those three tests (and nothing else) β€” proving they pin the non-leak contract. 46 `McpGroupToolsTest` cases pass (was 43); full group/MCP suite green; Checkstyle clean. + +**Deliberately out of scope:** the same `errorJson(e.getMessage())` pattern exists in ~10 pre-existing catch blocks in `McpGroupTools` (and other MCP tool classes), and two existing tests *depend* on those messages (`start_group_discussion` β†’ "Group not found", `delete` β†’ "Not found"). A blanket sweep would break tested behaviour and expand well beyond this PR, so it is left as a separate follow-up rather than bundled here. + +--- + +## 🌐 Group follow-up/continue β€” status-split completion: mid-round timeout β†’ 504 (2026-07-15) + +**Repo:** EDDI (`feat/group-followups`) + +An adversarial re-review of the status-code split found one path the split had missed. `executeAgentTurn` (the per-member turn used by the *initial* discussion and re-run by every continuation) still threw a **base** `GroupDiscussionException` on an ABORT-policy member timeout β€” so a genuine member-agent timeout mid-round mapped to `502 Bad Gateway`, not the `504 Gateway Timeout` the split documents. Every other timeout site was already `GroupTimeoutException`; this was the last one. + +- **Fix:** `GroupConversationService.executeAgentTurn` now throws `GroupTimeoutException` on the `onAgentFailure=ABORT` timeout branch. `executeDiscussion`'s re-wrap preserves the subtype, so it surfaces as `504`. +- **REST body hedge:** `continueDiscussion`'s `502` (`GroupExecutionException`) body previously claimed only "a member agent could not be reached". That catch also covers unrunnable-config failures, so the body now reads "a member agent or a required dependency could not be reached, or the group is misconfigured" β€” no longer asserting a single cause it cannot verify. +- **Coverage (mutation-verified):** new `GroupConversationServiceExtendedTest.FailurePolicies#abortPolicy_agentTimesOut_throwsGroupTimeoutException` drives a real member timeout (a `doNothing()` say stub so the future never completes) under `ABORT` and asserts `GroupTimeoutException`. Reverting the fix to the parent `GroupExecutionException` flips exactly this one test to failing ("expected GroupTimeoutException but was GroupExecutionException") β€” proving it pins the 504-vs-502 distinction, not just "some 5xx". + +250 group/MCP unit tests pass (52 extended, 82 service, 39 REST, 3 routing, 31 HITL, 43 MCP); Checkstyle clean. + +--- + +## 🌐 Group follow-up/continue β€” HTTP status-code split (2026-07-14) + +**Repo:** EDDI (`feat/group-followups`) + +A final pre-review pass flagged that `followUpWithMember` / `continueDiscussion` mapped **every** `GroupDiscussionException` to `409 Conflict` β€” including an unknown target agent (a client error) and mid-round server/upstream failures (LLM/DB down, agent timeout). A `409` tells the client "retryable conflict", which is wrong for a typo'd agent or a provider outage. This was pre-existing feature behaviour, not a regression, but it is a real API-semantics issue a reviewer would raise, so it was fixed properly. + +- **Cause-differentiated exception subtypes** (all extend `GroupDiscussionException`, so existing `catch (GroupDiscussionException)` in the MCP tools and tests keeps working): `GroupMemberNotFoundException` (β†’ 404), `GroupExecutionException` (β†’ 502), `GroupTimeoutException extends GroupExecutionException` (β†’ 504). The base type now means **only** a state/concurrency conflict (β†’ 409). +- **Single interception point** for execution failures: `executeDiscussion` re-throws every failure caught in its phase loop as `GroupExecutionException` (preserving `GroupTimeoutException`), so the many deep agent/quota/config throw sites did not each need editing. `followUpWithMember`'s own agent-call/timeout throws are re-typed directly. +- **REST mapping** (most-specific catch first): unknown member β†’ `404`, agent timeout β†’ `504`, agent/model failure β†’ `502` (Bad Gateway β€” an upstream dependency failed, logged with its stack trace), state/concurrency β†’ `409`. The `@APIResponse` annotations now list the full set. `close` is unchanged (only ever a state conflict β†’ 409). +- Nits swept: the new `400` bodies now set `.type(TEXT_PLAIN)` for consistency; the follow-up `InterruptedException` path restores the interrupt flag. + +Coverage: added REST tests (`followUp`/`continue` β†’ 404/502/504, and still-409 for a genuine conflict) and service tests asserting the specific subtypes are thrown (unknown member β†’ `GroupMemberNotFoundException`, agent failure β†’ `GroupExecutionException`, and the `executeDiscussion` failure-policy tests now assert `GroupExecutionException`). **Each new mapping was mutation-verified**: reverting the split makes the corresponding test fail (404/502/504 β†’ 409; specific subtype β†’ base). 654 group/MCP unit tests pass; Checkstyle clean. + +--- + +## 🧬 Group conversations β€” mutation-audited regression coverage (2026-07-14) + +**Repo:** EDDI (`feat/group-followups`) + +The question "do we have coverage for everything we fixed?" was answered with **mutation testing** rather than by reading test names: each fix was reverted in turn and the suite re-run. A fix whose mutant *survives* (suite still green) has no coverage and can silently regress. + +### Mutants that survived β€” i.e. bugs with ZERO coverage + +| Fix | Why the tests could not see it | +| --- | --- | +| **JAX-RS routing** β€” the `/{groupId}/conversations` prefix on the four post-discussion endpoints | The unit tests invoke resource methods **directly** and never exercise JAX-RS path binding. This was the single highest-severity bug of the whole effort (every follow-up/continue/close would have 404'd), and it could be reintroduced with the suite still green. | +| **SSE error curation** β€” the *service* pushing raw `e.getMessage()` into `GroupErrorEvent` | Nothing asserted what actually goes out over the wire to the browser. | +| **Malformed-id reflected value** β€” Mongo's `ObjectId` parser echoing the raw caller string | No test drove an unparseable id. | +| **Curated exception messages** (store + `loadInGroup`) | The existing test asserted the *response body*, which the REST layer curates anyway β€” so the message itself (which `read`/`delete` surface through the global mapper) was unguarded. | +| **Continuation `startPhaseIndex = 0`** | Nothing asserted that a continuation re-runs from the FIRST phase; a mutant that skipped phase 0 passed. | +| **`finally` cleanup condition** (defer `COMPLETED`, reclaim on `FAILED`/`CANCELLED`) | Nothing asserted that a COMPLETED round keeps its ephemeral agents for follow-ups. | +| **`resumeQuestion` read side** | Only the *write* was tested; nothing asserted that `resumeDiscussion` actually uses it. | +| **The three new metrics counters** | Never asserted. | + +### Coverage added (each verified to KILL its mutant) + +- **`IRestGroupConversationRoutingTest`** (new) β€” reflective assertions on the JAX-RS annotations: every `@PathParam` must have a matching `{template}` segment (a mismatch binds `null` β€” the exact production failure), every per-conversation route stays under `/groups/{groupId}/conversations/{groupConversationId}`, and the four endpoints resolve to their documented URLs. This is the invariant a direct-invocation test structurally cannot check. +- **`GroupConversationServiceExtendedTest.MergeRegressionGuards`** (new) β€” a failed discussion streams a *curated* error (never the raw exception text); a continuation re-runs from phase 0 and emits `round_start` (not `group_start`); a COMPLETED round keeps its ephemeral agents. +- **`GroupConversationServiceHitlTest`** β€” a paused *continuation* resumes with the follow-up question, not the stale round-1 one. +- **`GroupConversationStoreTest` / `RestGroupConversationTest`** β€” the not-found message never embeds the caller id; a malformed id is answered 404 without reflecting the payload; the group-mismatch exception *message* is curated. +- **`GroupConversationServiceTest`** β€” the three operation counters, and the failure counter incrementing even when the CAS is lost. + +Mutants **already killed** before this pass (genuinely covered): `failConversation`'s upsert, the MCP ownership gate, `CLOSED`-blindness in `persistedTerminalOverride`, `continueDiscussion`'s conditional write, the control-token pre-registration, `cancelDiscussion`'s `CLOSED` guard, `availableActions` for `CANCELLED`, and the MCP list owner-filter. + +647 group/MCP unit tests pass; Checkstyle clean. No production code changed in this commit. + +--- + +## πŸ›‘οΈ Group conversations β€” terminal-state integrity + error-body hardening (2026-07-14) + +**Repo:** EDDI (`feat/group-followups`). Found by an adversarial review of the previous PR-review-response commit β€” which had hardened the *success* write in `continueDiscussion` while leaving the *failure* write, and the rest of the reflected-value surface, wide open. + +### Terminal states are now irreversible + +- **`failConversation` was an unconditional whole-document write β€” i.e. an UPSERT.** It could **re-create a group conversation another pod had deleted**, and could overwrite a terminal `CANCELLED` (committed by a cross-pod cancel) with `FAILED`, clobbering that writer's transcript. It is now a conditional write. +- **The CAS expectation is taken from the PERSISTED state, not the in-memory one.** A first attempt CASed on `gc.getState()` and was itself a blocker: `executeDiscussion` flips the conversation to `SYNTHESIZING` **in memory** before the synthesis phase runs and only persists it afterwards, so a failure inside a synthesis phase would have CASed `SYNTHESIZING` against a persisted `IN_PROGRESS`, lost the race, skipped the write, and **stranded the conversation `IN_PROGRESS` forever** β€” worse than the bug being fixed. `failConversation` now re-reads the persisted state, skips the write when it is already terminal (aligning the in-memory state to it, so the `finally` makes the right ephemeral-agent decision), and counts the failure metric unconditionally so a lost race can never hide a failure from operators. + +### No exception text reaches the client (CodeQL: information exposure / reflected value) + +The previous commit curated one handler. This closes the class: + +- **Throw sites:** `GroupConversationStore` and `GroupConversationService` no longer embed caller-supplied ids in exception messages (`"Group conversation not found: {id}"`, `"Group not found: {groupId}"`, `"No phases defined for group: {groupId}"`). +- **Sinks:** `RestGroupConversation` returns **no raw exception text in any body** β€” every 400/404/409 is a curated, deliberately non-committal message (these exceptions cover several causes, so the body must not assert one), with the detail logged via `LogSanitizer`. +- **SSE:** the *service* was pushing raw `e.getMessage()` into `GroupErrorEvent`, which the streaming listener forwards to the browser β€” so LLM/DB/driver detail (and the caller's own input) reached the client even though the REST catch sites were curated. Those events are now curated too, and the raw cause is logged with its stack trace. +- **Malformed ids:** a non-hex id reaches Mongo's `ObjectId` parser, whose message embeds the **raw caller string** β€” the most exploitable sink. It is caught **inside `loadInGroup`, scoped to the id lookup only**, and answered with a curated 404. It is deliberately *not* a blanket `catch (IllegalArgumentException)` around the whole operation: that would mask a genuine internal bug as a false "not found" and hide its stack trace. + +Verified: 636 group/MCP unit tests pass (incl. new regression tests for the persisted-state CAS and the already-terminal skip); Checkstyle clean. Remaining full-suite failures are environmental only (Testcontainers/Docker + loopback-socket suites). + +--- + +## πŸ€– Group follow-ups β€” automated PR review response (CodeQL / Copilot / CodeRabbit) (2026-07-14) + +**Repo:** EDDI (`feat/group-followups`) β€” responses to the bot reviews on [PR #595](https://github.com/labsai/EDDI/pull/595). + +### Correctness + +- **Terminal-state resurrection in `continueDiscussion`** (Copilot, *High*): after the `COMPLETED β†’ IN_PROGRESS` CAS, the round/question mutation was persisted with an **unconditional** whole-document `update()`. A cancel/close/delete winning the window would be overwritten and the conversation resurrected as `IN_PROGRESS`. Now a conditional write (`updateIfState(gc, IN_PROGRESS)`) β†’ `409` on conflict. This is the same defect class already fixed in `followUpWithMember`; the continue path had been missed. + +### Security β€” reflected input & error exposure + +- **Reflected `groupId` in 404 bodies** (Copilot, *Medium*): `loadInGroup()` embedded the caller-supplied `groupId` in its exception message, which follow-up / continue / close echo verbatim into the `404` body (CodeQL reflected-value/XSS). Now a curated body; both ids are logged server-side via `LogSanitizer`. +- **Reflected `targetAgentId` in 409 bodies**: `followUpWithMember`'s "not a member" message echoed the caller-supplied agent id into the `409`. The id is no longer reflected (the available-member list β€” server data β€” is kept). +- **Information exposure through an error message** (CodeQL, *Medium*): the delete-conflict `409` returned the raw `e.getMessage()`. Now a curated "busy, please retry" body with the detail logged server-side. + +### Observability & docs + +- **Metrics for the new operations** (CodeRabbit): `followUpWithMember` / `continueDiscussion` / `closeGroupConversation` were uninstrumented, contrary to AGENTS.md. Added `eddi_group_followup_count`, `eddi_group_continue_count`, `eddi_group_close_count`. Instrumented in the **service** (not the MCP tools, as suggested) so the counters cover the REST *and* MCP surfaces. +- **Authorization denials now log at WARN** (CodeRabbit) β€” a security-relevant event should be alertable. +- **`getAvailableActions()` javadoc corrected** (Copilot, *Low*): it claimed "not persisted", but Jackson serializes it into stored documents. It is `READ_ONLY`, so the value is never read back and is always recomputed from `state` β€” the javadoc now says so rather than making a false claim. + +### Tests + +Post-CAS `IN_PROGRESS` read modelled so the `FAILED` recovery path is actually exercised; `close` now asserts a `CLOSED` result rather than `assertSame` on a stale instance; added the concurrent-terminal-transition conflict test, the SSE `cancelled` callback test, the admin-bypass tests (the other half of `requireOwnerOrAdmin` and the list-filter exemption), and assertions that neither the raw exception text nor the caller-supplied `groupId` reaches the client. + +### Not actioned (false positive) + +- CodeRabbit (*Major*) claimed `updateIfState` wrapping `ResourceNotFoundException` in the unchecked `GroupConversationGoneException` bypasses the REST layer's 404 handling and yields a 500. It does not: `RestGroupConversation` explicitly catches `GroupConversationGoneException` alongside `ResourceNotFoundException` in a multi-catch on every surface that exposes the operation (cancel / approve / approve-stream) and maps it to `404`. The unchecked type is a deliberate design from the HITL work (documented on the exception) so existing CAS call sites keep compiling; `compareAndSetState` converts it to `ResourceNotFoundException` for its own callers. No change made. + +--- + +## πŸ” Group merge β€” third-pass review: MCP authz, CLOSED-blindness, atomic CAS (2026-07-14) + +**Repo:** EDDI (`feat/group-followups`) + +A third critical review targeted what the earlier passes never looked at β€” the **auto-merged** files (git merged them without conflict, so nobody had reviewed them), the whole-branch PR surface, test coverage of the fixes, and security. 14 findings survived adversarial verification. All fixed: + +### Security β€” MCP was an authorization bypass (IDOR) +- `McpGroupTools` gated the conversation-scoped tools on a **role check only** (`eddi-viewer` for `followup_with_member` / `continue_group_discussion` / `read_group_conversation`, `eddi-editor` for `close`/`delete`) with **no ownership check**, while the equivalent REST endpoints all enforce `requireOwnerOrAdmin` (403). Any authenticated viewer could read another user's full transcript, append to it, re-run every phase against their conversation (burning their LLM budget), and an editor could close or delete it. Injected `OwnershipValidator` and added a `requireConversationOwner()` gate to all five tools, with a uniform non-leaking denial. Main's own HITL MCP tools already enforced this via `HitlAccessGuard` β€” MCP is now consistent with REST. +- **Owner resolution on creation** (found reviewing the gate above): MCP recorded the owner as the literal `"mcp-client"` (or any caller-supplied `userId`), so the new gate would have **locked the creator out of their own conversation** whenever auth was enabled β€” and let a caller create a conversation owned by someone else. `discuss_with_group` / `start_group_discussion` now resolve the owner via `validateAndResolveUserId` (the calling principal; impersonation rejected), falling back to `"mcp-client"` only when auth is off. +- **`list_group_conversations` is now owner-filtered** (mirroring REST). It returns full conversation documents, so without this the per-conversation gate was pointless β€” a non-owner could simply list the group and read everyone's transcripts. + +### Correctness β€” a systemic `CLOSED`-blindness +Ours introduced `CLOSED` as a new terminal state; theirs' HITL/cancel code predates it. A sweep of every terminal-state check found exactly two blind spots: +- **`persistedTerminalOverride`** treated only `{CANCELLED, FAILED, COMPLETED}` as terminal, so a running leg that found the conversation `CLOSED` did **not** stop β€” it fell through to an unconditional whole-document write and **resurrected the closed conversation** to `IN_PROGRESS`β†’`COMPLETED` after its member conversations were ended and its ephemeral agents deleted. (The previous round's fix F β€” close-of-`CANCELLED` β€” made this materially more reachable.) +- **`cancelDiscussion`** likewise ignored `CLOSED`, so a cancel could CAS `CLOSED β†’ CANCELLED` and un-terminalize an irreversible state. + +### Correctness β€” the cross-process guard wasn't atomic +- **`compareAndSetState` was a read-check-write**, not a CAS: it read, compared in Java, then wrote unconditionally, so two racing callers could both pass the check and both write. It is the *only* cross-process guard behind follow-up/continue/close (the original changelog admitted "single-node only… would require a conditional update at the storage layer"). The merge made the fix available β€” it now uses theirs' `storeIfFieldEquals`, returning `false` on a lost race. + +### Contract / robustness +- `followUpWithMember` with a null/blank `targetAgentId` NPE'd into a **500**; now validated β†’ **400** (service throws `IllegalArgumentException`, REST rejects up front). Same for a blank `question` on follow-up and continue. +- `POST /continue` advertised `attachments` on its body but **silently dropped them**. Now **rejected with 400** rather than silently ignored. (A first attempt to *honour* them was reverted after review: attachments are granted and injected to a member only on its first-ever turn, and on a continuation every member conversation already exists β€” so the "fix" was a no-op that stored an orphaned blob and still returned 200. Actually sharing new files mid-conversation needs the attachment fan-out reworked β€” see *What's next*.) +- `DELETE` during an in-flight follow-up/continue returned **500**; now a `GroupDiscussionException` β†’ **409**. +- OpenAPI updated for the new 400/409 responses and the `CANCELLED`-closeable state. + +### Tests +Backfilled the previously untested fixes (they could each have been reverted with the suite still green): `resumeQuestion` persistence, control-token pre-registration + removal, `persistedTerminalOverride` state alignment across all four terminal states, cancel-of-`CLOSED`, conditional-CAS + lost-race, MCP ownership denial/allow, blank-input 400s, continue-attachment forwarding, delete 409, and the streaming listener forwarding HITL + `round_start` events. + +Also fixed a **latent broken test the merge introduced**: `GroupConversationHitlTest` still asserted 7 enum states (the merge made it 8 with `CLOSED`) β€” it was never in the narrower test selections and had been failing since the merge commit. + +### What's next (deliberately not done here) + +- **Attachments on a continuation round.** `grantAndInjectAttachments` runs only on a member's *first-ever* turn (`privateConvId == null`), so a continuation cannot share new files. Supporting it means reworking the fan-out to grant/inject per *round* (e.g. tracking which member conversations have been granted the current attachment set) β€” a change to shared attachment code, out of scope for a merge-response fix. Until then `/continue` rejects attachments with 400. +- **Follow-up to a dynamically recruited agent.** `GroupConversation.dynamicMembers` has no production writer (sub-agent creation records only `createdAgentIds`), so recruited agents are not addressable as follow-up targets at all. A first attempt to resolve them by display name was reverted as dead code; the real fix is to register recruited agents as members (roster + `memberConversationIds`). + +Verified: `mvnw test` green β€” **758 group/MCP unit tests pass** (0 failures). The remaining full-suite failures are environmental only (Testcontainers/Docker and loopback-socket suites β€” Mongo/Postgres stores, HTTP tool tests); no group or MCP test fails. CI covers those. + +--- + +## 🩹 Group merge β€” cross-feature review-response fixes (2026-07-14) + +**Repo:** EDDI (`feat/group-followups`) + +A deep adversarial review of the merge (7 dimensions, 58 agents, each finding cross-examined by 3 skeptics) confirmed the conflict resolution was sound but surfaced **cross-feature interaction bugs** between *ours* (continue/follow-up/close) and *theirs* (HITL pause/cancel/resume) that neither branch could have had alone β€” none caught by the impl-level unit tests. Fixed: + +- **A β€” stale question on continuation resume:** a continuation round that paused at an HITL gate resumed with the round-1 question (`resumeDiscussion` read `originalQuestion`, which `continueDiscussion` never updated) β€” silent wrong multi-agent output. Added a dedicated `GroupConversation.resumeQuestion` field: `continueDiscussion` sets it, `resumeDiscussion` reads it (falling back to `originalQuestion` for round 1 / legacy docs). Kept separate from `originalQuestion` so the Manager conversation-list title (which renders `originalQuestion`) is not rewritten by continuations. +- **B β€” continue/stream dropped HITL events:** `continueDiscussionStreaming` used a hand-rolled inline SSE listener predating theirs' HITL callbacks, so a continuation that paused/cancelled emitted no event and hung the client + leaked the sink. Unified it on the shared `createStreamingListener` (added an `onRoundStart` override there); removed ~55 lines of duplication. +- **C β€” ephemeral-agent leak on cross-pod terminal race:** the merged `finally` cleans up only on `FAILED`/`CANCELLED` (to defer `COMPLETED` for follow-up reuse), but the cross-pod terminal-override and lost-completion-CAS exits left in-memory state stale (running/optimistic-`COMPLETED`), skipping cleanup. Both exits now align in-memory `state` to the actual persisted terminal value so the `finally` decides correctly. +- **D β€” follow-up clobbered a racing cancel:** `followUpWithMember`'s success path used an unconditional `update()` that could overwrite a concurrent `CANCELLED`. Switched to `updateIfState(gc, IN_PROGRESS)` (matching its own error path); a concurrent cancel/delete now yields a `409` instead of resurrecting the conversation. +- **E β€” cancel race + latency on continuation:** `continueDiscussion` didn't pre-register a `DiscussionControlToken`, so a cancel racing the CASβ†’`executeDiscussion` window took the DB branch and was overwritten, and cancel latency was a whole phase worse. Now pre-registers the token right after the CAS (mirrors `startAndDiscussAsync`/`resumeDiscussion`); removed on the pre-exec failure path. +- **F β€” `CANCELLED` had no reclaim path:** a cancel landing in the follow-up/continue pre-exec window could reach `CANCELLED` with orphaned ephemeral agents and no recovery. `closeGroupConversation` now accepts `CANCELLED β†’ CLOSED` and `getAvailableActions()` returns `["close"]` for `CANCELLED`, giving operators a reclaim path. + +Added regression tests (`CANCELLED` available-actions, close-of-`CANCELLED`); updated the follow-up success-write assertion. Verified: `mvnw test` green β€” 189 group-conversation unit tests pass (0 failures); each fix re-verified by an adversarial pass (5/6 clean first time; A refined from overloading `originalQuestion` to the dedicated field per that review). + +--- + +## πŸ”€ Merge `origin/main` into `feat/group-followups` β€” conflict resolution (2026-07-14) + +**Repo:** EDDI (`feat/group-followups`) + +Merged 170 commits of `origin/main` (HITL framework + multimodal-attachments group parity) into the group follow-up/continuation/close branch. Both sides evolved the group-conversation subsystem in parallel, so all 23 conflict hunks across 12 files were resolved as a **union** of the two feature sets. Key decisions: + +- **`GroupConversationService.executeDiscussion` setup (conflict):** interleaved ours' member-display-name population + round-aware start events (`onGroupStart` on round 1, `onRoundStart` on continuation rounds) with theirs' attachment re-hydration, resume-seeded turn counter (`pausedTurnCount`), HITL granularity, and control-token registration. The start-event now fires only on fresh execution (`startPhaseIndex == 0`), branching round-1 vs continuation. +- **`executeDiscussion` finally-block cleanup (conflict):** reconciled ours' "defer ephemeral cleanup for COMPLETED rounds so follow-ups can reuse dynamic agents" with theirs' "keep agents alive while `AWAITING_APPROVAL`". Result: always remove the control token; drop the verification cursor unless paused; clean up ephemeral agents only on terminal states with no follow-up/close path (`FAILED`, `CANCELLED`). `COMPLETED` cleanup stays deferred to `close`/`delete`. +- **`GroupConversationState` is now 8 values** (ours' `CLOSED` + theirs' `CANCELLED`). `getAvailableActions()` gained a `CANCELLED` arm (terminal, no actions β€” updated the exhaustive switch); the enum-count guard test was corrected 7 β†’ 8. +- **`executeDiscussion` signature:** theirs added `int startPhaseIndex`; ours' `continueDiscussion` call site now passes `0` (a continuation re-runs the full protocol from phase 0). +- **Group-path guard unified on `loadInGroup()`:** all six endpoints (read, delete, followup, continue, continue/stream, close) route through ours' `loadInGroup()`; theirs' parallel `requireGroupMembership()` helper was removed as dead code. HITL endpoints keep theirs' `validateGroupConversationOwnership`. +- **JAX-RS routing fix (would-be regression):** theirs flattened the class-level `@Path` from `/groups/{groupId}/conversations` to `/groups`, moving the `{groupId}/conversations` prefix onto each method. Ours' four methods (`followup`/`continue`/`continue/stream`/`close`) carried their old class-relative `@Path("/{groupConversationId}/…")`, so post-flatten they lost the `{groupId}` template segment while still declaring `@PathParam("groupId")` β€” `groupId` would bind `null` and every call would 404 (invisible to the unit tests, which call the impl directly). Each of the four method paths was prefixed with `/{groupId}/conversations`, restoring the original external URLs. Caught by an adversarial merge review. +- **Both feature APIs preserved:** ours' `followUpWithMember` / `continueDiscussion` / `closeGroupConversation` / `compareAndSetState` + theirs' `cancelDiscussion` / `resumeDiscussion` / `approveGroupPhase(/Streaming)` / `getGroupApprovalStatus` / `listGroup(All)PendingApprovals` / `updateIfState` / `findByState`; all SSE events and listener callbacks from both sides retained. +- **Review nitpick:** `RestGroupConversationExtendedTest` now has an `@AfterEach` that invokes the package-private `RestGroupConversation.shutdown()`, so a full suite run no longer accumulates un-terminated virtual-thread executors. + +Verified: `mvnw clean test-compile` green; ~187 group-conversation unit tests pass (GroupConversation 25, Store 19, Rest 25, RestExtended 21, Service 68, Hitl 29 β€” 0 failures/errors). + +--- + +## πŸ”’ 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)` + --- ## πŸ”­ Security β€” conversation-listing scan: enforce the budget per-descriptor + changelog accuracy (2026-07-15) diff --git a/src/main/java/ai/labs/eddi/configs/groups/IGroupConversationStore.java b/src/main/java/ai/labs/eddi/configs/groups/IGroupConversationStore.java index d37202cd93..8e162eb555 100644 --- a/src/main/java/ai/labs/eddi/configs/groups/IGroupConversationStore.java +++ b/src/main/java/ai/labs/eddi/configs/groups/IGroupConversationStore.java @@ -27,6 +27,15 @@ public interface IGroupConversationStore { List 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; + /** * Update the group conversation only if it is currently in the expected state. * Throws {@link IResourceStore.ResourceModifiedException} if the conversation diff --git a/src/main/java/ai/labs/eddi/configs/groups/model/GroupConversation.java b/src/main/java/ai/labs/eddi/configs/groups/model/GroupConversation.java index d8479d35ff..4f9a46abe0 100644 --- a/src/main/java/ai/labs/eddi/configs/groups/model/GroupConversation.java +++ b/src/main/java/ai/labs/eddi/configs/groups/model/GroupConversation.java @@ -7,10 +7,12 @@ import ai.labs.eddi.configs.hitl.HitlTimeoutPolicy; import ai.labs.eddi.engine.memory.model.Attachment; 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; @@ -28,12 +30,29 @@ public class GroupConversation { private String userId; private GroupConversationState state; private String originalQuestion; + /** + * The question driving the CURRENT run's phases. Equals + * {@link #originalQuestion} for the initial round; a continuation round sets it + * to the follow-up question so an HITL resume re-runs the remaining phases with + * the right question. Kept separate from {@code originalQuestion} (which the UI + * renders as the conversation title) so continuations don't rewrite that title. + * {@code null} on legacy documents β€” resume falls back to + * {@code originalQuestion}. + */ + private String resumeQuestion; private List transcript = Collections.synchronizedList(new ArrayList<>()); private Map memberConversationIds = new ConcurrentHashMap<>(); + /** + * Maps agentId β†’ displayName for all group members. Populated at discussion + * start. + */ + private Map 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 dynamicMembers = Collections.synchronizedList(new ArrayList<>()); @@ -155,7 +174,9 @@ 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 { @@ -163,7 +184,12 @@ public enum GroupConversationState { /** Discussion was cancelled before completion β€” HITL foundation (Phase 9b). */ CANCELLED, /** 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 } public enum HitlPauseType { @@ -212,6 +238,14 @@ public void setOriginalQuestion(String originalQuestion) { this.originalQuestion = originalQuestion; } + public String getResumeQuestion() { + return resumeQuestion; + } + + public void setResumeQuestion(String resumeQuestion) { + this.resumeQuestion = resumeQuestion; + } + public List getTranscript() { return transcript; } @@ -264,6 +298,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; } @@ -337,6 +379,47 @@ public void setDynamicAgentConfig(AgentGroupConfiguration.DynamicAgentConfig dyn this.dynamicAgentConfig = dynamicAgentConfig; } + public Map getMemberDisplayNames() { + return Collections.unmodifiableMap(memberDisplayNames); + } + + public void setMemberDisplayNames(Map 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 derived from {@link #state} β€” tells clients which + * operations are available. It is serialized (so REST/MCP clients see it, and + * it therefore also lands in the stored document), but {@code READ_ONLY} access + * means it is never read back in: the value is always recomputed from + * {@code state}, so a stale value in an old document cannot be trusted or used. + */ + @JsonProperty(value = "availableActions", access = JsonProperty.Access.READ_ONLY) + public List getAvailableActions() { + if (state == null) { + return List.of(); + } + return switch (state) { + case COMPLETED -> List.of("followup", "continue", "close"); + // FAILED and CANCELLED are terminal but closeable β€” close ends member + // conversations and reclaims ephemeral agents. + case FAILED, CANCELLED -> List.of("close"); + case IN_PROGRESS, SYNTHESIZING, CREATED, AWAITING_APPROVAL -> List.of(); + case CLOSED -> List.of(); + }; + } + @JsonIgnore public List getAttachments() { return attachments; diff --git a/src/main/java/ai/labs/eddi/configs/groups/mongo/GroupConversationStore.java b/src/main/java/ai/labs/eddi/configs/groups/mongo/GroupConversationStore.java index 480fac54db..382c665074 100644 --- a/src/main/java/ai/labs/eddi/configs/groups/mongo/GroupConversationStore.java +++ b/src/main/java/ai/labs/eddi/configs/groups/mongo/GroupConversationStore.java @@ -68,7 +68,7 @@ public GroupConversation read(String id) throws IResourceStore.ResourceNotFoundE try { IResourceStorage.IResource resource = storage.read(id, SINGLE_VERSION); if (resource == null) { - throw new IResourceStore.ResourceNotFoundException("Group conversation not found: " + id); + throw new IResourceStore.ResourceNotFoundException("Group conversation not found."); } GroupConversation conversation = resource.getData(); conversation.setId(id); @@ -132,6 +132,34 @@ public List 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) { + // Fast path: clearly the wrong state β€” no need to attempt the write. + return false; + } + gc.setState(newState); + gc.setLastModified(java.time.Instant.now()); + try { + // Conditional write β€” the persisted state must STILL be expectedState. The + // read-check above alone was a read-check-update (single-node only): two + // racing callers could both pass it and both write. storeIfFieldEquals makes + // the transition atomic across processes. + updateIfState(gc, expectedState); + return true; + } catch (IResourceStore.ResourceModifiedException e) { + // Another writer transitioned the conversation between our read and our + // write β€” this CAS lost the race. + return false; + } catch (GroupConversationGoneException e) { + throw new IResourceStore.ResourceNotFoundException( + "Group conversation no longer exists."); + } + } + @Override public void updateIfState(GroupConversation gc, GroupConversation.GroupConversationState expectedState) throws IResourceStore.ResourceStoreException, IResourceStore.ResourceModifiedException { @@ -142,7 +170,7 @@ public void updateIfState(GroupConversation gc, GroupConversation.GroupConversat // deleted-vs-mismatch distinction from the storage CAS: surface the // deletion as its own (unchecked) type so callers can answer 404 throw new GroupConversationGoneException( - "Group conversation " + gc.getId() + " no longer exists", e); + "Group conversation no longer exists.", e); } catch (IOException e) { throw new IResourceStore.ResourceStoreException("Failed conditional update: " + e.getMessage(), e); } diff --git a/src/main/java/ai/labs/eddi/engine/api/IGroupConversationService.java b/src/main/java/ai/labs/eddi/engine/api/IGroupConversationService.java index df6d9ada34..ed87b3771d 100644 --- a/src/main/java/ai/labs/eddi/engine/api/IGroupConversationService.java +++ b/src/main/java/ai/labs/eddi/engine/api/IGroupConversationService.java @@ -82,14 +82,57 @@ GroupConversation readGroupConversation(String groupConversationId) /** * Delete a group conversation and cascade-delete member conversations. + * + * @throws GroupDiscussionException + * if another operation (follow-up / continue / close) is currently + * in progress for this conversation β€” a retryable conflict (REST: + * 409), not a store failure. */ - void deleteGroupConversation(String groupConversationId) throws IResourceStore.ResourceStoreException; + void deleteGroupConversation(String groupConversationId) + throws GroupDiscussionException, IResourceStore.ResourceStoreException; /** * List group conversations for a given group config. */ List 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. + * + *

+ * 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; + /** * Cancel a running or paused group discussion. * @@ -151,6 +194,8 @@ default void onTaskPlanCreated(GroupConversationEventSink.TaskPlanCreatedEvent e } default void onTaskVerified(GroupConversationEventSink.TaskVerifiedEvent event) { } + default void onRoundStart(GroupConversationEventSink.RoundStartEvent event) { + } default void onHitlPause(GroupConversationEventSink.HitlPauseEvent event) { } default void onHitlResume(GroupConversationEventSink.HitlResumeEvent event) { @@ -178,4 +223,42 @@ public GroupDepthExceededException(String message) { super(message); } } + + /** + * The follow-up target agent is not a member of this group conversation β€” a + * client error (typically a typo'd agent id / display name). REST surfaces this + * as {@code 404}, distinct from the {@code 409} used for state/concurrency + * conflicts: retrying with the same target will never succeed. + */ + class GroupMemberNotFoundException extends GroupDiscussionException { + public GroupMemberNotFoundException(String message) { + super(message); + } + } + + /** + * The operation could not be completed because a member agent or model call + * failed β€” an upstream-dependency failure, not a client or state error. REST + * surfaces this as {@code 502}, so clients do not mistake a provider outage for + * a retryable "conversation is busy" conflict. + */ + class GroupExecutionException extends GroupDiscussionException { + public GroupExecutionException(String message) { + super(message); + } + + public GroupExecutionException(String message, Throwable cause) { + super(message, cause); + } + } + + /** + * A member agent did not respond within the configured timeout. REST surfaces + * this as {@code 504}. + */ + class GroupTimeoutException extends GroupExecutionException { + public GroupTimeoutException(String message, Throwable cause) { + super(message, cause); + } + } } diff --git a/src/main/java/ai/labs/eddi/engine/api/IRestGroupConversation.java b/src/main/java/ai/labs/eddi/engine/api/IRestGroupConversation.java index 4488e08352..5dfca41b4f 100644 --- a/src/main/java/ai/labs/eddi/engine/api/IRestGroupConversation.java +++ b/src/main/java/ai/labs/eddi/engine/api/IRestGroupConversation.java @@ -69,6 +69,7 @@ public interface IRestGroupConversation { @Operation(summary = "Delete a group conversation", description = "Deletes a group conversation and its member conversations.") @APIResponse(responseCode = "200", description = "Group conversation deleted.") @APIResponse(responseCode = "404", description = "Group conversation not found.") + @APIResponse(responseCode = "409", description = "Another operation (follow-up / continue / close) is in progress β€” retry.") Response deleteGroupConversation(@PathParam("groupId") String groupId, @PathParam("groupConversationId") String groupConversationId); @GET @@ -81,6 +82,78 @@ List listGroupConversations(@PathParam("groupId") String grou @QueryParam("limit") @DefaultValue("20") Integer limit); + @POST + @Path("/{groupId}/conversations/{groupConversationId}/followup") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Operation(summary = "Follow up with a group member", + description = "Send a follow-up question to a specific member agent in a completed " + + "group conversation. The agent retains full context from the discussion. " + + "Both the question and response are recorded on the group transcript. " + + "The targetAgentId field accepts either an agent ID or a display name. " + + "Returns the full updated GroupConversation including the new transcript entries.") + @APIResponse(responseCode = "200", description = "Updated group conversation with follow-up on transcript.") + @APIResponse(responseCode = "400", description = "Missing 'question' or 'targetAgentId'.") + @APIResponse(responseCode = "404", description = "Group conversation not found, or the target agent is not a member.") + @APIResponse(responseCode = "409", description = "Conversation not in COMPLETED state, or another operation is in progress.") + @APIResponse(responseCode = "502", description = "The member agent could not be reached / the agent call failed.") + @APIResponse(responseCode = "504", description = "The member agent did not respond within the timeout.") + Response followUpWithMember(@PathParam("groupId") String groupId, + @PathParam("groupConversationId") String gcId, + FollowUpRequest request); + + @POST + @Path("/{groupId}/conversations/{groupConversationId}/continue") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Operation(summary = "Continue a group discussion", + description = "Re-run all discussion phases with a new question. All agents retain " + + "memory of prior rounds. The round counter increments. NOTE: 'attachments' are " + + "NOT supported on a continuation (they are only shared with member agents when " + + "the discussion starts) and are rejected with 400 rather than silently ignored.") + @APIResponse(responseCode = "200", description = "Updated group conversation with new round.") + @APIResponse(responseCode = "400", description = "Missing 'question', or 'attachments' supplied (unsupported on continuation).") + @APIResponse(responseCode = "404", description = "Group conversation not found.") + @APIResponse(responseCode = "409", description = "Conversation not in COMPLETED state, or another operation is in progress.") + @APIResponse(responseCode = "502", description = "A member agent could not be reached during the round.") + @APIResponse(responseCode = "504", description = "A member agent did not respond within the timeout.") + Response continueDiscussion(@PathParam("groupId") String groupId, + @PathParam("groupConversationId") String gcId, + DiscussRequest request); + + @POST + @Path("/{groupId}/conversations/{groupConversationId}/continue/stream") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.SERVER_SENT_EVENTS) + @Operation(summary = "Continue a group discussion with SSE streaming", + description = "Re-run all discussion phases with SSE event streaming for progress. " + + "Emits round_start (new round marker) followed by the same events as the " + + "initial stream (phase_start, speaker_start, speaker_complete, phase_complete, " + + "synthesis_start, group_complete, group_error), plus the HITL events " + + "(awaiting_approval, hitl_resume, cancelled, member_pause_skipped). NOTE: " + + "'attachments' are NOT supported on a continuation and are rejected with a " + + "terminal group_error event rather than silently ignored.") + @APIResponse(responseCode = "200", description = "SSE event stream of continuation progress.") + @APIResponse(responseCode = "404", description = "Group conversation not found.") + void continueDiscussionStreaming(@PathParam("groupId") String groupId, + @PathParam("groupConversationId") String gcId, + DiscussRequest request, + @Context SseEventSink eventSink, @Context Sse sse); + + @POST + @Path("/{groupId}/conversations/{groupConversationId}/close") + @Produces(MediaType.APPLICATION_JSON) + @Operation(summary = "Close a group conversation", + description = "Permanently close a group conversation. Ends all member conversations " + + "and cleans up ephemeral agents. No further follow-ups or continuations " + + "are accepted after closing. " + + "Lifecycle: discuss β†’ COMPLETED β†’ [followup|continue]* β†’ close β†’ CLOSED (terminal).") + @APIResponse(responseCode = "200", description = "Closed group conversation.") + @APIResponse(responseCode = "404", description = "Group conversation not found.") + @APIResponse(responseCode = "409", description = "Conversation not in COMPLETED, FAILED or CANCELLED state.") + Response closeGroupConversation(@PathParam("groupId") String groupId, + @PathParam("groupConversationId") String gcId); + @POST @Path("/{groupId}/conversations/{groupConversationId}/cancel") @Consumes(MediaType.APPLICATION_JSON) @@ -149,6 +222,13 @@ public DiscussRequest(String question, String userId) { } } + /** + * Request body for following up with a specific group member. + * {@code targetAgentId} accepts either a raw agent ID or a display name. + */ + record FollowUpRequest(String question, String targetAgentId, String userId) { + } + /** * A single attachment reference on a group discussion request. Provide either * inline base64 {@code data} (+ {@code mimeType}) or a hosted {@code url}. diff --git a/src/main/java/ai/labs/eddi/engine/internal/GroupConversationService.java b/src/main/java/ai/labs/eddi/engine/internal/GroupConversationService.java index f38fcfe216..5784d2682f 100644 --- a/src/main/java/ai/labs/eddi/engine/internal/GroupConversationService.java +++ b/src/main/java/ai/labs/eddi/engine/internal/GroupConversationService.java @@ -111,6 +111,16 @@ public class GroupConversationService implements IGroupConversationService { // amortized instead of O(NΒ²)). Cleaned up when conversations complete. private final ConcurrentHashMap lastVerifiedIndex = new ConcurrentHashMap<>(); + // In-node fast-fail guard for concurrent post-discussion operations + // (follow-up, continue, close) on the same conversation: a second + // operation on the same gcId is rejected rather than queued. The Set is + // single-node only, but it is NOT the cluster-wide safety mechanism: + // cross-node races are prevented by conversationStore.compareAndSetState, + // which performs an atomic storage-layer conditional update (Mongo + // updateOne / Postgres UPDATE filtered on the current state field). The + // Set only avoids redundant work within a single node. + private final Set operationsInProgress = ConcurrentHashMap.newKeySet(); + // Metrics private final Timer timerGroupDiscussion; private final Counter counterGroupDiscussion; @@ -118,6 +128,13 @@ public class GroupConversationService implements IGroupConversationService { private final Counter counterGroupHitlPause; private final Counter counterGroupHitlResume; private final Counter counterGroupMemberPauseSkipped; + /** + * Post-discussion operations (follow-up / continue / close) β€” REST and MCP + * surfaces. + */ + private final Counter counterGroupFollowUp; + private final Counter counterGroupContinue; + private final Counter counterGroupClose; @Inject public GroupConversationService(IAgentGroupStore groupStore, IGroupConversationStore conversationStore, IConversationService conversationService, @@ -148,6 +165,9 @@ public GroupConversationService(IAgentGroupStore groupStore, IGroupConversationS this.counterGroupHitlPause = meterRegistry.counter("eddi_hitl_pause_count", "surface", "group"); this.counterGroupHitlResume = meterRegistry.counter("eddi_hitl_resume_count", "surface", "group"); this.counterGroupMemberPauseSkipped = meterRegistry.counter("eddi_group_member_pause_skipped_count"); + this.counterGroupFollowUp = meterRegistry.counter("eddi_group_followup_count"); + this.counterGroupContinue = meterRegistry.counter("eddi_group_continue_count"); + this.counterGroupClose = meterRegistry.counter("eddi_group_close_count"); } @PreDestroy @@ -191,17 +211,17 @@ public GroupConversation discuss(String groupId, String question, String userId, // PostgreSQL IResourceStore.IResourceId currentGroupId = groupStore.getCurrentResourceId(groupId); if (currentGroupId == null) { - throw new IResourceStore.ResourceNotFoundException("Group not found: " + groupId); + throw new IResourceStore.ResourceNotFoundException("Group not found."); } AgentGroupConfiguration config = groupStore.read(groupId, currentGroupId.getVersion()); if (config == null) { - throw new IResourceStore.ResourceNotFoundException("Group configuration not found: " + groupId); + throw new IResourceStore.ResourceNotFoundException("Group configuration not found."); } // Resolve phases List phases = resolvePhases(config); if (phases.isEmpty()) { - throw new GroupDiscussionException("No phases defined for group: " + groupId); + throw new GroupDiscussionException("No discussion phases are defined for this group."); } GroupConversation gc = createGroupConversation(groupId, question, userId, depth); @@ -227,16 +247,16 @@ public GroupConversation startAndDiscussAsync(String groupId, String question, S // Validate early β€” so errors are returned synchronously IResourceStore.IResourceId currentGroupId = groupStore.getCurrentResourceId(groupId); if (currentGroupId == null) { - throw new IResourceStore.ResourceNotFoundException("Group not found: " + groupId); + throw new IResourceStore.ResourceNotFoundException("Group not found."); } AgentGroupConfiguration config = groupStore.read(groupId, currentGroupId.getVersion()); if (config == null) { - throw new IResourceStore.ResourceNotFoundException("Group configuration not found: " + groupId); + throw new IResourceStore.ResourceNotFoundException("Group configuration not found."); } List phases = resolvePhases(config); if (phases.isEmpty()) { - throw new GroupDiscussionException("No phases defined for group: " + groupId); + throw new GroupDiscussionException("No discussion phases are defined for this group."); } // Create the conversation synchronously so we can return its ID @@ -257,7 +277,10 @@ public GroupConversation startAndDiscussAsync(String groupId, String question, S } catch (Exception e) { LOGGER.errorf("Async group discussion failed for %s: %s", groupId, e.getMessage()); if (listener != null) { - listener.onGroupError(new GroupConversationEventSink.GroupErrorEvent(e.getMessage())); + // Curated: the raw exception text (LLM/DB/driver detail, and possibly the + // caller's own input) must never be pushed to an SSE client. Logged above. + listener.onGroupError(new GroupConversationEventSink.GroupErrorEvent( + "The group discussion could not be started.")); } } }); @@ -409,6 +432,15 @@ private GroupConversation executeDiscussion(GroupConversation gc, AgentGroupConf // AgentOrchestrator to enforce group-level guardrails on dynamic tools. gc.setDynamicAgentConfig(config.getDynamicAgents()); + // Populate member display name map (idempotent β€” safe on continuation rounds) + if (gc.getMemberDisplayNames().isEmpty() && config.getMembers() != null) { + for (var member : config.getMembers()) { + if (member.displayName() != null) { + gc.addMemberDisplayName(member.agentId(), member.displayName()); + } + } + } + // Re-hydrate shared attachments (transient like dynamicAgentConfig above) from // the durable blob store so a HITL resume doesn't silently drop them for a // member whose first turn lands after the resume. See the method comment. @@ -430,11 +462,18 @@ private GroupConversation executeDiscussion(GroupConversation gc, AgentGroupConf // must NOT be wiped by a fresh token here. activeTokens.computeIfAbsent(gc.getId(), k -> new DiscussionControlToken()); - // MINOR-1: Only fire GROUP_START on fresh discussion, not resume + // MINOR-1: Only fire a start event on fresh execution (startPhaseIndex == 0), + // not on an HITL resume. Round 1 β†’ GROUP_START; continuation rounds β†’ + // ROUND_START. if (startPhaseIndex == 0 && listener != null) { - listener.onGroupStart(new GroupConversationEventSink.GroupStartEvent(gc.getId(), gc.getGroupId(), question, - config.getStyle() != null ? config.getStyle().name() : "ROUND_TABLE", phases.size(), - config.getMembers().stream().map(GroupMember::agentId).toList())); + if (gc.getRound() <= 1) { + listener.onGroupStart(new GroupConversationEventSink.GroupStartEvent(gc.getId(), gc.getGroupId(), question, + config.getStyle() != null ? config.getStyle().name() : "ROUND_TABLE", phases.size(), + config.getMembers().stream().map(GroupMember::agentId).toList())); + } else { + listener.onRoundStart(new GroupConversationEventSink.RoundStartEvent( + gc.getId(), gc.getRound(), question, phases.size())); + } } try { @@ -606,6 +645,10 @@ private GroupConversation executeDiscussion(GroupConversation gc, AgentGroupConf LOGGER.infof("Group discussion %s was terminated elsewhere (expected %s) β€” not overwriting with COMPLETED", gc.getId(), expectedRunningState); var persisted = conversationStore.read(gc.getId()); + // This leg optimistically set COMPLETED before the CAS; align the + // in-memory state with the terminal value the racing writer committed so + // the finally cleans up ephemeral agents for a CANCELLED/FAILED outcome. + gc.setState(persisted.getState()); if (listener != null && persisted.getState() == GroupConversationState.CANCELLED) { notifyCancelled(persisted, listener); } @@ -632,11 +675,23 @@ private GroupConversation executeDiscussion(GroupConversation gc, AgentGroupConf notifyCancelled(gc, listener); return gc; } + LOGGER.errorf(e, "Group discussion %s failed", LogSanitizer.sanitize(gc.getId())); failConversation(gc); if (listener != null) { - listener.onGroupError(new GroupConversationEventSink.GroupErrorEvent(e.getMessage())); - } - throw e; + // Curated: the raw exception text (LLM/DB/driver detail, and possibly the + // caller's own input) must never be pushed to an SSE client β€” it is logged + // above and the exception is rethrown for the non-streaming callers. + listener.onGroupError(new GroupConversationEventSink.GroupErrorEvent( + "The group discussion failed.")); + } + // Every GroupDiscussionException thrown inside the phase loop is an execution + // failure (agent unavailable/unreachable/timeout, quota, config) β€” never a + // state/concurrency conflict. Re-throw as GroupExecutionException so it maps to + // 5xx at REST, preserving a more specific subtype (e.g. GroupTimeoutException). + if (e instanceof GroupExecutionException) { + throw e; + } + throw new GroupExecutionException(e.getMessage(), e); } catch (Exception e) { // R2: If the exception was caused by a cancel, route to CANCELLED var cancelToken = activeTokens.get(gc.getId()); @@ -647,11 +702,14 @@ private GroupConversation executeDiscussion(GroupConversation gc, AgentGroupConf notifyCancelled(gc, listener); return gc; } + LOGGER.errorf(e, "Group discussion %s failed", LogSanitizer.sanitize(gc.getId())); failConversation(gc); if (listener != null) { - listener.onGroupError(new GroupConversationEventSink.GroupErrorEvent(e.getMessage())); + // Curated β€” see above. + listener.onGroupError(new GroupConversationEventSink.GroupErrorEvent( + "The group discussion failed.")); } - throw new GroupDiscussionException("Group discussion failed: " + e.getMessage(), e); + throw new GroupExecutionException("Group discussion failed: " + e.getMessage(), e); } finally { timerGroupDiscussion.record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); // NEW-2: Always remove the control token β€” paused conversations have no @@ -659,9 +717,18 @@ private GroupConversation executeDiscussion(GroupConversation gc, AgentGroupConf // the no-op signal branch. Resume re-registers a fresh token. Re-check the // removed token so a cancel that raced this remove is not silently dropped. removeTokenAndConvertIfSignalled(gc, listener); - // Only clean up ephemeral agents when the discussion is truly done + // Drop the incremental verification cursor once this leg ends, but keep it + // across an HITL pause so a resume continues from where it left off. if (gc.getState() != GroupConversationState.AWAITING_APPROVAL) { lastVerifiedIndex.remove(gc.getId()); + } + // Defer ephemeral cleanup to closeGroupConversation()/deleteGroupConversation() + // for COMPLETED rounds so follow-ups and continuations can reuse + // dynamically-created agents; keep them alive while AWAITING_APPROVAL (the + // discussion will resume). Clean up immediately only on terminal states with + // no follow-up or close path (FAILED, CANCELLED). + if (gc.getState() == GroupConversationState.FAILED + || gc.getState() == GroupConversationState.CANCELLED) { cleanupEphemeralAgents(gc, config); } } @@ -696,7 +763,19 @@ private boolean persistedTerminalOverride(GroupConversation gc, GroupDiscussionE var persistedState = conversationStore.read(gc.getId()).getState(); if (persistedState == GroupConversationState.CANCELLED || persistedState == GroupConversationState.FAILED - || persistedState == GroupConversationState.COMPLETED) { + || persistedState == GroupConversationState.COMPLETED + // CLOSED is terminal too: without it, a leg that keeps running past a + // concurrent close would fall through to the unconditional whole-document + // write below and RESURRECT the closed conversation (its member + // conversations are already ended and its ephemeral agents deleted). + || persistedState == GroupConversationState.CLOSED) { + // Align the in-memory state with the terminal value another pod/writer + // committed so executeDiscussion's finally makes the correct ephemeral- + // agent cleanup decision β€” this leg's gc is otherwise still a running + // state (IN_PROGRESS/SYNTHESIZING) and cleanup would be skipped. (CLOSED + // is deliberately NOT in the finally's cleanup set β€” close already + // reclaimed the agents.) + gc.setState(persistedState); LOGGER.infof("Group discussion %s was moved to %s elsewhere β€” stopping this leg at the phase boundary", gc.getId(), persistedState); if (persistedState == GroupConversationState.CANCELLED) { @@ -934,7 +1013,19 @@ public GroupConversation readGroupConversation(String groupConversationId) } @Override - public void deleteGroupConversation(String groupConversationId) throws IResourceStore.ResourceStoreException { + public void deleteGroupConversation(String groupConversationId) + throws GroupDiscussionException, IResourceStore.ResourceStoreException { + // Serialize against an in-flight follow-up/continue/close on the same + // conversation + // (single-node) β€” delete is terminal (it ends member conversations and reclaims + // ephemeral agents), so racing an active discussion could tear those down + // mid-run + // and let a later update() resurrect a stale "zombie" document. + if (!operationsInProgress.add(groupConversationId)) { + // A retryable conflict, not a store failure β€” surfaces as 409, not 500. + throw new GroupDiscussionException( + "Cannot delete: another operation is already in progress for this group conversation"); + } try { GroupConversation gc = conversationStore.read(groupConversationId); // #12: deleting a paused discussion must run the same cleanup as @@ -953,9 +1044,15 @@ public void deleteGroupConversation(String groupConversationId) throws IResource LOGGER.warnf("Failed to end private conversation %s: %s", privateConvId, e.getMessage()); } } + // Ephemeral agent cleanup β€” deferred from executeDiscussion() to terminal + // operations. Delete is terminal, so reclaim any dynamically-created agents + // here; otherwise deleting a COMPLETED conversation would orphan them. + cleanupEphemeralAgentsForGroup(gc); conversationStore.delete(groupConversationId); } catch (IResourceStore.ResourceNotFoundException e) { - LOGGER.warnf("Group conversation %s not found for deletion", groupConversationId); + LOGGER.warnf("Group conversation %s not found for deletion", LogSanitizer.sanitize(groupConversationId)); + } finally { + operationsInProgress.remove(groupConversationId); } } @@ -964,6 +1061,310 @@ public List listGroupConversations(String groupId, int index, return conversationStore.listByGroupId(groupId, index, limit); } + @Override + public GroupConversation followUpWithMember(String groupConversationId, String targetAgentId, + String question) + throws GroupDiscussionException, IResourceStore.ResourceStoreException, IResourceStore.ResourceNotFoundException { + + // Validate BEFORE taking the guard or transitioning state: a null targetAgentId + // would otherwise NPE deep in the member-resolution scan (500 instead of 400), + // and a null question would be appended to the transcript and sent to the + // agent. + if (targetAgentId == null || targetAgentId.isBlank()) { + throw new IllegalArgumentException("targetAgentId must not be null or blank"); + } + if (question == null || question.isBlank()) { + throw new IllegalArgumentException("question must not be null or blank"); + } + + if (!operationsInProgress.add(groupConversationId)) { + throw new GroupDiscussionException( + "Another operation is already in progress for this group conversation"); + } + try { + GroupConversation gc = conversationStore.read(groupConversationId); + + // Atomic state transition: COMPLETED β†’ IN_PROGRESS + if (!conversationStore.compareAndSetState(groupConversationId, GroupConversationState.COMPLETED, GroupConversationState.IN_PROGRESS)) { + throw new GroupDiscussionException( + "Cannot follow up: conversation is not in COMPLETED state (current: %s)".formatted(gc.getState())); + } + + boolean success = false; + try { + // Re-read after CAS to get the freshest transcript + gc = conversationStore.read(groupConversationId); + + // Resolve targetAgentId β€” accept either agent ID or display name + String resolvedAgentId = targetAgentId; + String privateConvId = gc.getMemberConversationIds().get(targetAgentId); + if (privateConvId == null) { + // Try resolving as display name + for (var entry : gc.getMemberDisplayNames().entrySet()) { + if (targetAgentId.equalsIgnoreCase(entry.getValue())) { + resolvedAgentId = entry.getKey(); + privateConvId = gc.getMemberConversationIds().get(resolvedAgentId); + break; + } + } + } + if (privateConvId == null) { + throw new GroupMemberNotFoundException( + // The caller-supplied targetAgentId is deliberately NOT echoed. + // REST maps this to 404 with a curated body; keeping the id out + // keeps the message safe wherever it DOES surface β€” e.g. the MCP + // tools, which return it as their error string. + "The requested agent is not a member of this group conversation. Available members: %s" + .formatted(gc.getMemberDisplayNames())); + } + + // Resolve display name + String displayName = gc.getMemberDisplayNames().getOrDefault(resolvedAgentId, resolvedAgentId); + + // Record the user's follow-up question on the transcript + gc.getTranscript().add(new TranscriptEntry( + "user", "User", question, -1, "Follow-up", + TranscriptEntryType.FOLLOW_UP, Instant.now(), null, resolvedAgentId)); + + // Call the agent's private conversation + InputData inputData = new InputData(); + inputData.setInput(question); + Map context = new LinkedHashMap<>(); + context.put("groupTranscript", new Context(Context.ContextType.object, gc.getTranscript())); + context.put("groupId", new Context(Context.ContextType.string, gc.getGroupId())); + context.put("groupConversationId", new Context(Context.ContextType.string, gc.getId())); + inputData.setContext(context); + + CompletableFuture responseFuture = new CompletableFuture<>(); + try { + conversationService.say(DEFAULT_ENV, resolvedAgentId, privateConvId, true, true, null, inputData, false, snapshot -> { + String response = extractResponse(snapshot); + if ((response == null || response.isEmpty()) && snapshot != null + && snapshot.getConversationState() == ConversationState.ERROR) { + response = "[Agent failed to produce output β€” conversation entered ERROR state]"; + } + responseFuture.complete(response); + }); + } catch (Exception e) { + throw new GroupExecutionException("Failed to call agent '%s': %s".formatted(resolvedAgentId, e.getMessage()), e); + } + + int timeoutSeconds = resolveAgentTimeoutSeconds(gc); + String response; + try { + response = responseFuture.get(timeoutSeconds, TimeUnit.SECONDS); + } catch (TimeoutException e) { + throw new GroupTimeoutException("Follow-up timed out for agent '%s'".formatted(resolvedAgentId), e); + } catch (ExecutionException | InterruptedException e) { + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + throw new GroupExecutionException("Follow-up failed for agent '%s': %s".formatted(resolvedAgentId, e.getMessage()), e); + } + + // Record the agent's response on the transcript + gc.getTranscript().add(new TranscriptEntry( + resolvedAgentId, displayName, response, -1, "Follow-up", + TranscriptEntryType.FOLLOW_UP, Instant.now(), null, null)); + + // Transition back to COMPLETED β€” atomically (CAS on IN_PROGRESS) so a + // follow-up that races a cancel cannot resurrect a CANCELLED terminal + // state via an unconditional whole-document write. Mirrors the CAS the + // error path below already uses. + gc.setState(GroupConversationState.COMPLETED); + gc.setLastModified(Instant.now()); + try { + conversationStore.updateIfState(gc, GroupConversationState.IN_PROGRESS); + } catch (IResourceStore.ResourceModifiedException + | IGroupConversationStore.GroupConversationGoneException e) { + // A concurrent cancel/delete moved the conversation out of + // IN_PROGRESS while the follow-up ran β€” do not overwrite that + // terminal state; the follow-up exchange is not applied. + throw new GroupDiscussionException( + "Follow-up could not be applied: the conversation was concurrently " + + "cancelled or deleted", + e); + } + + success = true; + counterGroupFollowUp.increment(); + return gc; + + } finally { + if (!success) { + // Restore COMPLETED state so the conversation remains usable. + // Wrap in try-catch to avoid masking the original exception. + try { + conversationStore.compareAndSetState(groupConversationId, + GroupConversationState.IN_PROGRESS, GroupConversationState.COMPLETED); + } catch (Exception recoveryEx) { + LOGGER.warnf("Failed to restore COMPLETED state after follow-up error for %s: %s", + LogSanitizer.sanitize(groupConversationId), recoveryEx.getMessage()); + } + } + } + } finally { + operationsInProgress.remove(groupConversationId); + } + } + + @Override + public GroupConversation continueDiscussion(String groupConversationId, String question, + GroupDiscussionEventListener listener) + throws GroupDiscussionException, IResourceStore.ResourceStoreException, IResourceStore.ResourceNotFoundException { + + // Validate before taking the guard / transitioning state β€” a blank question + // would + // otherwise be appended to the transcript and drive every phase's agent input. + if (question == null || question.isBlank()) { + throw new IllegalArgumentException("question must not be null or blank"); + } + + if (!operationsInProgress.add(groupConversationId)) { + throw new GroupDiscussionException( + "Another operation is already in progress for this group conversation"); + } + try { + GroupConversation gc = conversationStore.read(groupConversationId); + + // Atomic state transition: COMPLETED β†’ IN_PROGRESS + if (!conversationStore.compareAndSetState(groupConversationId, GroupConversationState.COMPLETED, GroupConversationState.IN_PROGRESS)) { + throw new GroupDiscussionException( + "Cannot continue: conversation is not in COMPLETED state (current: %s)".formatted(gc.getState())); + } + + // Re-read after CAS + gc = conversationStore.read(groupConversationId); + + // Increment round and append the new question. Persist the follow-up as the + // run's resumeQuestion so that if a continuation round pauses at an HITL gate, + // resumeDiscussion re-runs the remaining phases with THIS question rather than + // the stale round-1 one. Uses a dedicated field (not originalQuestion, which + // the UI shows as the conversation title) so continuations don't rewrite it. + gc.setRound(gc.getRound() + 1); + gc.setResumeQuestion(question); + gc.getTranscript().add(new TranscriptEntry( + "user", "User", question, 0, "Question", + TranscriptEntryType.QUESTION, Instant.now(), null, null)); + gc.setLastModified(Instant.now()); + // Conditional write (CAS on IN_PROGRESS): an unconditional whole-document + // update here would resurrect a conversation that a concurrent + // cancel/close/delete moved to a terminal state in the window after our CAS + // above. Terminal states must stay irreversible (mirrors followUpWithMember). + try { + conversationStore.updateIfState(gc, GroupConversationState.IN_PROGRESS); + } catch (IResourceStore.ResourceModifiedException + | IGroupConversationStore.GroupConversationGoneException e) { + throw new GroupDiscussionException( + "Cannot continue: the conversation was concurrently cancelled, closed or deleted", e); + } + counterGroupContinue.increment(); + + // Pre-register the control token BEFORE the config-load window so a cancel + // racing the gap between the CAS above and executeDiscussion's own token + // registration takes the signal path (stops at the top-of-phase check) + // rather than the DB branch, which would CAS to CANCELLED and then be + // overwritten by this leg (mirrors startAndDiscussAsync / resumeDiscussion). + activeTokens.put(groupConversationId, new DiscussionControlToken()); + + // Load the group config and re-execute β€” wrapped in try-catch so that + // failures before executeDiscussion() (which has its own failConversation + // logic) still set the GC to FAILED rather than leaving it IN_PROGRESS. + try { + IResourceStore.IResourceId currentGroupId = groupStore.getCurrentResourceId(gc.getGroupId()); + if (currentGroupId == null) { + throw new IResourceStore.ResourceNotFoundException("Group not found."); + } + AgentGroupConfiguration config = groupStore.read(gc.getGroupId(), currentGroupId.getVersion()); + + // Resolve phases and re-execute + List phases = resolvePhases(config); + if (phases.isEmpty()) { + // A group config with no phases is a server-side misconfiguration the + // caller cannot fix by retrying, not a conversation-state conflict. + throw new GroupExecutionException("No discussion phases are defined for this group."); + } + + // Continuation re-runs the full protocol from the first phase. + return executeDiscussion(gc, config, phases, question, listener, 0); + } catch (Exception e) { + // executeDiscussion handles its own failures, so this only catches + // errors from config loading / phase resolution above. If it was never + // reached, its finally never removed the pre-registered token β€” drop it + // here (idempotent: a no-op if executeDiscussion already removed it). + activeTokens.remove(groupConversationId); + if (gc.getState() == GroupConversationState.IN_PROGRESS) { + failConversation(gc); + } + if (e instanceof GroupDiscussionException gde) { + throw gde; + } + if (e instanceof IResourceStore.ResourceNotFoundException rnfe) { + throw rnfe; + } + if (e instanceof IResourceStore.ResourceStoreException rse) { + throw rse; + } + throw new GroupExecutionException("Continue discussion failed: " + e.getMessage(), e); + } + } finally { + operationsInProgress.remove(groupConversationId); + } + } + + @Override + public GroupConversation closeGroupConversation(String groupConversationId) + throws GroupDiscussionException, IResourceStore.ResourceStoreException, IResourceStore.ResourceNotFoundException { + + if (!operationsInProgress.add(groupConversationId)) { + throw new GroupDiscussionException( + "Another operation is already in progress for this group conversation"); + } + try { + GroupConversation gc = conversationStore.read(groupConversationId); + + // Atomic state transition: try COMPLETED β†’ CLOSED, then FAILED β†’ CLOSED, + // then CANCELLED β†’ CLOSED. CANCELLED is closeable so an operator can reclaim + // the ephemeral agents of a discussion cancelled in a window where no running + // leg cleaned them up (CANCELLED has no follow-up/continue path otherwise). + boolean transitioned = conversationStore.compareAndSetState( + groupConversationId, GroupConversationState.COMPLETED, GroupConversationState.CLOSED); + if (!transitioned) { + transitioned = conversationStore.compareAndSetState( + groupConversationId, GroupConversationState.FAILED, GroupConversationState.CLOSED); + } + if (!transitioned) { + transitioned = conversationStore.compareAndSetState( + groupConversationId, GroupConversationState.CANCELLED, GroupConversationState.CLOSED); + } + if (!transitioned) { + throw new GroupDiscussionException( + "Cannot close: conversation is in %s state (expected COMPLETED, FAILED, or CANCELLED)".formatted(gc.getState())); + } + counterGroupClose.increment(); + + // End all member conversations + for (String privateConvId : gc.getMemberConversationIds().values()) { + try { + conversationService.endConversation(privateConvId); + } catch (Exception e) { + LOGGER.warnf("Failed to end private conversation %s during close: %s", privateConvId, e.getMessage()); + } + } + + // Ephemeral agent cleanup (deferred from executeDiscussion) + cleanupEphemeralAgentsForGroup(gc); + + LOGGER.infof("Group conversation %s closed β€” member conversations ended, ephemeral agents cleaned up", + LogSanitizer.sanitize(groupConversationId)); + + // Re-read to return the final CLOSED state + return conversationStore.read(groupConversationId); + } finally { + operationsInProgress.remove(groupConversationId); + } + } + @Override public List listGroupPendingApprovals(String groupId, int limit) throws IResourceStore.ResourceStoreException { @@ -1049,6 +1450,47 @@ private ProtocolConfig resolveProtocol(AgentGroupConfiguration config) { : new ProtocolConfig(60, ProtocolConfig.MemberFailurePolicy.SKIP, 2, ProtocolConfig.MemberUnavailablePolicy.SKIP); } + /** + * Resolve the per-agent timeout (seconds) for a follow-up turn from the group's + * protocol config, so follow-ups honor the same configurable limit as + * discussion turns. Defaults to 60 if the config cannot be loaded. + */ + private int resolveAgentTimeoutSeconds(GroupConversation gc) { + try { + IResourceStore.IResourceId currentGroupId = groupStore.getCurrentResourceId(gc.getGroupId()); + if (currentGroupId != null) { + AgentGroupConfiguration config = groupStore.read(gc.getGroupId(), currentGroupId.getVersion()); + if (config != null) { + int timeout = resolveProtocol(config).agentTimeoutSeconds(); + if (timeout > 0) { + return timeout; + } + } + } + } catch (Exception e) { + LOGGER.debugf("Could not resolve agent timeout for group %s, using default: %s", + LogSanitizer.sanitize(gc.getGroupId()), e.getMessage()); + } + return 60; + } + + /** + * Load the group config and run ephemeral-agent cleanup for a terminal + * operation (close / delete). Tolerant of config-load failures. + */ + private void cleanupEphemeralAgentsForGroup(GroupConversation gc) { + try { + IResourceStore.IResourceId currentGroupId = groupStore.getCurrentResourceId(gc.getGroupId()); + if (currentGroupId != null) { + AgentGroupConfiguration config = groupStore.read(gc.getGroupId(), currentGroupId.getVersion()); + cleanupEphemeralAgents(gc, config); + } + } catch (Exception e) { + LOGGER.warnf("Ephemeral agent cleanup failed for group conversation %s: %s", + LogSanitizer.sanitize(gc.getId()), e.getMessage()); + } + } + /** * Determines which members participate in a phase based on the * {@code participants} field: "ALL", "MODERATOR", or "ROLE:<name>". @@ -2151,7 +2593,10 @@ private TranscriptEntry executeAgentTurn(GroupMember member, GroupConversation g continue; } if (protocol.onAgentFailure() == ProtocolConfig.MemberFailurePolicy.ABORT) { - throw new GroupDiscussionException("Agent %s timed out and onAgentFailure=ABORT".formatted(member.agentId())); + // A member-agent timeout β€” surface as GroupTimeoutException so it maps + // to 504 at REST (executeDiscussion's re-wrap preserves the subtype). + throw new GroupTimeoutException( + "Agent %s timed out and onAgentFailure=ABORT".formatted(member.agentId()), null); } return new TranscriptEntry(member.agentId(), member.displayName(), null, phaseIdx, phase.name(), TranscriptEntryType.SKIPPED, Instant.now(), "Timeout after " + timeout + "s", targetAgentId); @@ -2595,15 +3040,65 @@ private TranscriptEntry errorEntry(GroupMember member, int phaseIdx, DiscussionP return new TranscriptEntry(agentId, displayName, null, phaseIdx, phase.name(), TranscriptEntryType.ERROR, Instant.now(), message, null); } + /** Terminal states: no further transition may overwrite them. */ + private static boolean isTerminalState(GroupConversationState state) { + return state == GroupConversationState.COMPLETED + || state == GroupConversationState.FAILED + || state == GroupConversationState.CANCELLED + || state == GroupConversationState.CLOSED; + } + private void failConversation(GroupConversation gc) { + // Never write unconditionally: conversationStore.update() is a whole-document + // UPSERT, so it would RE-CREATE a conversation another pod deleted and would + // clobber a terminal state (e.g. a cross-pod CANCELLED) with FAILED. + // + // The CAS expectation must come from the PERSISTED state, not the in-memory + // one: + // executeDiscussion flips gc to SYNTHESIZING in memory BEFORE the synthesis + // phase + // runs and only persists it afterwards, so a CAS on the in-memory value would + // lose + // the race and silently strand the conversation IN_PROGRESS forever. + var inMemoryState = gc.getState(); + GroupConversationState expected; + try { + expected = conversationStore.read(gc.getId()).getState(); + } catch (Exception e) { + expected = inMemoryState; // best effort β€” the re-read failed + } + if (expected == null) { + expected = inMemoryState; + } + gc.setState(GroupConversationState.FAILED); gc.setLastModified(Instant.now()); + // Count the failure itself, never the outcome of the race β€” otherwise a lost + // CAS + // would hide the failure from operators entirely. + counterGroupFailure.increment(); + + if (expected == null || isTerminalState(expected)) { + // Another writer already made it terminal β€” honor that. Align the in-memory + // state with it (mirrors persistedTerminalOverride) so executeDiscussion's + // finally makes the RIGHT ephemeral-agent decision: leaving a stale FAILED + // here would undeploy the agents of a conversation that is actually COMPLETED + // (whose agents a follow-up/continue must reuse) or already CLOSED. + if (expected != null) { + gc.setState(expected); + } + LOGGER.infof("Not failing group conversation %s β€” it is already terminal (%s)", + LogSanitizer.sanitize(gc.getId()), expected); + return; + } try { - conversationStore.update(gc); + conversationStore.updateIfState(gc, expected); + } catch (IResourceStore.ResourceModifiedException | IGroupConversationStore.GroupConversationGoneException e) { + LOGGER.infof("Not failing group conversation %s β€” another writer made it terminal or deleted it", + LogSanitizer.sanitize(gc.getId())); } catch (Exception e) { LOGGER.warnf("Failed to update group conversation state to FAILED: %s", e.getMessage()); } - counterGroupFailure.increment(); } /** @@ -2837,11 +3332,15 @@ public boolean cancelDiscussion(String conversationId, ControlSignal mode) // resurrect a terminal state. var gc = conversationStore.read(conversationId); var state = gc.getState(); - // Only cancel from non-terminal states β€” guard against - // overwriting COMPLETED or FAILED after a race. + // Only cancel from non-terminal states β€” guard against overwriting COMPLETED, + // FAILED or CLOSED after a race. CLOSED is irreversible: without it here a + // cancel + // would CAS CLOSED β†’ CANCELLED and un-terminalize an already-reclaimed + // conversation. if (state == GroupConversationState.COMPLETED || state == GroupConversationState.CANCELLED - || state == GroupConversationState.FAILED) { + || state == GroupConversationState.FAILED + || state == GroupConversationState.CLOSED) { LOGGER.infof("Cancel skipped: GC %s already in terminal state %s", conversationId, state); return false; } @@ -3065,9 +3564,12 @@ public GroupConversation resumeDiscussion(String groupConversationId, GroupAppro decision != null ? decision.getDecidedBy() : null)); } - // Resume execution in background thread + // Resume execution in background thread. Use the current run's resumeQuestion + // (set by continueDiscussion for a continuation round) so the remaining phases + // re-run with the follow-up question; fall back to originalQuestion for the + // initial round and legacy documents that predate the field. var groupId = gc.getGroupId(); - var question = gc.getOriginalQuestion(); + var question = gc.getResumeQuestion() != null ? gc.getResumeQuestion() : gc.getOriginalQuestion(); // BLOCKER fix: TASK pauses mid-phase β†’ re-enter at same phase (idempotent). // PHASE pauses after phase completes β†’ resume at +1. int startFromPhase = (pauseType == GroupConversation.HitlPauseType.TASK) @@ -3095,7 +3597,7 @@ public GroupConversation resumeDiscussion(String groupConversationId, GroupAppro try { IResourceStore.IResourceId currentGroupId = groupStore.getCurrentResourceId(groupId); if (currentGroupId == null) { - throw new IResourceStore.ResourceNotFoundException("Group not found: " + groupId); + throw new IResourceStore.ResourceNotFoundException("Group not found."); } groupConfig = groupStore.read(groupId, currentGroupId.getVersion()); phases = resolvePhases(groupConfig); @@ -3148,8 +3650,9 @@ public GroupConversation resumeDiscussion(String groupConversationId, GroupAppro // remove-and-recheck so a signal racing the remove is not dropped. removeTokenAndConvertIfSignalled(gc, listener); if (listener != null) { + // Curated: never push the raw exception text to an SSE client. listener.onGroupError(new GroupConversationEventSink.GroupErrorEvent( - "Resume failed: " + e.getMessage() + " β€” the discussion remains awaiting approval; retry")); + "Resume failed β€” the discussion remains awaiting approval; retry.")); } return; } diff --git a/src/main/java/ai/labs/eddi/engine/internal/RestGroupConversation.java b/src/main/java/ai/labs/eddi/engine/internal/RestGroupConversation.java index 2c7e87485c..e409afe6c5 100644 --- a/src/main/java/ai/labs/eddi/engine/internal/RestGroupConversation.java +++ b/src/main/java/ai/labs/eddi/engine/internal/RestGroupConversation.java @@ -18,6 +18,7 @@ import ai.labs.eddi.engine.security.OwnershipValidator; import io.quarkus.security.ForbiddenException; import io.quarkus.security.identity.SecurityIdentity; +import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.InternalServerErrorException; @@ -29,6 +30,9 @@ import java.net.URI; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import static ai.labs.eddi.engine.exception.SneakyThrow.sneakyThrow; import static ai.labs.eddi.utils.LogSanitizer.sanitize; @@ -48,6 +52,7 @@ public class RestGroupConversation implements IRestGroupConversation { private final IJsonSerialization jsonSerialization; private final SecurityIdentity identity; private final OwnershipValidator ownershipValidator; + private final ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor(); private final HitlAccessGuard hitlAccessGuard; @Inject @@ -63,6 +68,49 @@ public RestGroupConversation(IGroupConversationService groupConversationService, this.hitlAccessGuard = hitlAccessGuard; } + @PreDestroy + void shutdown() { + executorService.shutdown(); + try { + if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + } + } catch (InterruptedException e) { + executorService.shutdownNow(); + Thread.currentThread().interrupt(); + } + } + + /** + * Load a group conversation and verify it belongs to the group in the path. + * Throws {@link IResourceStore.ResourceNotFoundException} on mismatch so each + * caller's existing not-found handling (404 or SSE error) applies uniformly. + */ + private GroupConversation loadInGroup(String groupId, String gcId) + throws IResourceStore.ResourceNotFoundException, IResourceStore.ResourceStoreException { + GroupConversation gc; + try { + gc = groupConversationService.readGroupConversation(gcId); + } catch (IllegalArgumentException e) { + // Scoped deliberately to the id lookup ONLY. A malformed id reaches the + // storage layer's ObjectId parser, whose message embeds the raw caller string + // ("invalid hexadecimal representation of an ObjectId: [...]") and would be + // echoed by the global mapper β€” a reflected-value sink. A malformed id cannot + // name a conversation, so "not found" is the honest answer. Catching this any + // wider would mask a genuine internal IllegalArgumentException as a 404. + LOGGER.infof("Malformed group conversation id: %s", sanitize(gcId)); + throw new IResourceStore.ResourceNotFoundException("Group conversation not found."); + } + if (gc.getGroupId() == null || !gc.getGroupId().equals(groupId)) { + // Curated body: the caller-supplied groupId/gcId are never reflected back + // (CodeQL reflected-value/XSS) β€” several callers echo e.getMessage() into the + // 404. The detail is logged server-side with both ids sanitized. + LOGGER.infof("Group conversation %s does not belong to group %s", sanitize(gcId), sanitize(groupId)); + throw new IResourceStore.ResourceNotFoundException("Group conversation not found."); + } + return gc; + } + @Override public Response discuss(String groupId, DiscussRequest request) { try { @@ -76,9 +124,27 @@ public Response discuss(String groupId, DiscussRequest request) { URI location = URI.create("/groups/" + groupId + "/conversations/" + gc.getId()); return Response.created(location).entity(gc).build(); } catch (IGroupConversationService.GroupDepthExceededException e) { - return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); + // Curated bodies throughout this class: the raw exception text is never + // returned to the caller (CodeQL: information exposure / reflected value β€” + // several of these messages used to embed the caller-supplied groupId/gcId). + // The detail is logged server-side with the ids sanitized. + LOGGER.infof("Group discussion rejected (depth) for group %s", sanitize(groupId)); + return Response.status(Response.Status.BAD_REQUEST).type(TEXT_PLAIN) + .entity("Maximum group nesting depth exceeded.").build(); } catch (IResourceStore.ResourceNotFoundException e) { - return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); + LOGGER.infof("Group discussion β†’ not found for group %s", sanitize(groupId)); + return Response.status(Response.Status.NOT_FOUND).type(TEXT_PLAIN) + .entity("Group not found.").build(); + } catch (IllegalArgumentException e) { + // Usually a malformed groupId: it reaches the storage layer's ObjectId parser, + // whose message embeds the raw caller string and would be echoed by the global + // mapper. discuss() has no loadInGroup to scope this to the id lookup, so log + // the full exception β€” a genuine internal IllegalArgumentException must stay + // diagnosable rather than vanish behind a "not found". + LOGGER.error("Group discussion rejected for group " + sanitize(groupId) + + " (malformed id, or an internal IllegalArgumentException)", e); + return Response.status(Response.Status.NOT_FOUND).type(TEXT_PLAIN) + .entity("Group not found.").build(); } catch (Exception e) { LOGGER.errorf("Group discussion failed: %s", e.getMessage()); throw sneakyThrow(e); @@ -101,13 +167,14 @@ public void discussStreaming(String groupId, DiscussRequest request, SseEventSin } } catch (IResourceStore.ResourceNotFoundException e) { - sendEvent(eventSink, sse, GroupConversationEventSink.EVENT_GROUP_ERROR, - toJson(new GroupConversationEventSink.GroupErrorEvent(e.getMessage()))); + // Curated event text: the SSE body is rendered by the chat UI, so never push + // the raw message (it used to embed the caller-supplied groupId). + LOGGER.infof("Group streaming discussion β†’ not found for group %s: %s", sanitize(groupId), e.getMessage()); + sendErrorEvent(eventSink, sse, "Group not found."); closeQuietly(eventSink); } catch (Exception e) { LOGGER.errorf("Group streaming discussion failed: %s", e.getMessage()); - sendEvent(eventSink, sse, GroupConversationEventSink.EVENT_GROUP_ERROR, - toJson(new GroupConversationEventSink.GroupErrorEvent(e.getMessage()))); + sendErrorEvent(eventSink, sse, "Group discussion could not be started."); closeQuietly(eventSink); } } @@ -149,8 +216,7 @@ private static List toAttachments(List refs) { @Override public GroupConversation readGroupConversation(String groupId, String groupConversationId) { try { - GroupConversation gc = groupConversationService.readGroupConversation(groupConversationId); - requireGroupMembership(groupId, groupConversationId, gc); + GroupConversation gc = loadInGroup(groupId, groupConversationId); ownershipValidator.requireOwnerOrAdmin(identity, gc.getUserId(), "group conversation"); return gc; } catch (ForbiddenException e) { @@ -163,34 +229,27 @@ public GroupConversation readGroupConversation(String groupId, String groupConve @Override public Response deleteGroupConversation(String groupId, String groupConversationId) { try { - GroupConversation gc = groupConversationService.readGroupConversation(groupConversationId); - requireGroupMembership(groupId, groupConversationId, gc); + GroupConversation gc = loadInGroup(groupId, groupConversationId); ownershipValidator.requireOwnerOrAdmin(identity, gc.getUserId(), "group conversation"); groupConversationService.deleteGroupConversation(groupConversationId); return Response.ok().build(); } catch (ForbiddenException e) { throw e; + } catch (IGroupConversationService.GroupDiscussionException e) { + // Another operation (follow-up / continue / close) is mid-flight β€” a retryable + // conflict, not a server error. Curated body: never surface the raw exception + // text to the client (CodeQL: information exposure through an error message); + // the detail is logged server-side with the id sanitized. + LOGGER.infof("Delete of group conversation %s conflicted: %s", + sanitize(groupConversationId), sanitize(e.getMessage())); + return Response.status(Response.Status.CONFLICT).type(TEXT_PLAIN) + .entity("Group conversation is busy β€” another operation is in progress. Please retry.") + .build(); } catch (IResourceStore.ResourceNotFoundException | IResourceStore.ResourceStoreException e) { throw sneakyThrow(e); } } - /** - * Guards against a wrong-group path: the target conversation must belong to - * {groupId}, else 404 β€” so the {groupId} path parameter is meaningful and - * read/delete cannot act on a conversation under an arbitrary group. - */ - private void requireGroupMembership(String groupId, String gcId, GroupConversation gc) { - if (groupId != null && gc != null && !groupId.equals(gc.getGroupId())) { - // Curated body: the caller-supplied gcId/groupId are never reflected - // (CodeQL reflected-value/XSS β€” there is no ExceptionMapper for jakarta - // NotFoundException, so RESTEasy would echo the message verbatim); the - // detail is logged server-side with both ids sanitized. - LOGGER.infof("Group conversation %s does not belong to group %s", sanitize(gcId), sanitize(groupId)); - throw new jakarta.ws.rs.NotFoundException("Group conversation not found."); - } - } - @Override public List listGroupConversations(String groupId, Integer index, Integer limit) { try { @@ -209,6 +268,60 @@ public List listGroupConversations(String groupId, Integer in } } + /** True when the string is absent or whitespace-only. */ + private static boolean blank(String s) { + return s == null || s.isBlank(); + } + + @Override + public Response followUpWithMember(String groupId, String gcId, FollowUpRequest request) { + // Reject an incomplete body up front: without this a missing targetAgentId NPEs + // during member resolution and surfaces as a 500 rather than a 400. + if (request == null || blank(request.question()) || blank(request.targetAgentId())) { + return Response.status(Response.Status.BAD_REQUEST).type(TEXT_PLAIN) + .entity("Both 'question' and 'targetAgentId' are required.").build(); + } + try { + GroupConversation gc = loadInGroup(groupId, gcId); + ownershipValidator.requireOwnerOrAdmin(identity, gc.getUserId(), "group conversation"); + GroupConversation result = groupConversationService.followUpWithMember(gcId, request.targetAgentId(), request.question()); + return Response.ok(result).build(); + } catch (ForbiddenException e) { + throw e; + } catch (IGroupConversationService.GroupMemberNotFoundException e) { + // A typo'd / non-member agent β€” a client error, not a conflict. 404, curated: + // the exception text carries the member list (server data), never the caller + // id. + LOGGER.infof("Follow-up on %s β†’ target not a member: %s", sanitize(gcId), sanitize(e.getMessage())); + return Response.status(Response.Status.NOT_FOUND).type(TEXT_PLAIN) + .entity("The target agent is not a member of this group conversation.").build(); + } catch (IGroupConversationService.GroupTimeoutException e) { + LOGGER.warn("Follow-up on " + sanitize(gcId) + " timed out", e); + return Response.status(Response.Status.GATEWAY_TIMEOUT).type(TEXT_PLAIN) + .entity("The member agent did not respond in time. Try again.").build(); + } catch (IGroupConversationService.GroupExecutionException e) { + // A member agent / model call failed β€” an upstream-dependency failure, 5xx, not + // a retryable "conflict". Log the full cause; the client gets a curated body. + LOGGER.error("Follow-up on " + sanitize(gcId) + " failed to execute", e); + return Response.status(Response.Status.BAD_GATEWAY).type(TEXT_PLAIN) + .entity("The follow-up could not be completed because the member agent could not be reached.") + .build(); + } catch (IGroupConversationService.GroupDiscussionException e) { + // Base type now means only a state / concurrency conflict. + LOGGER.infof("Follow-up on %s conflicted: %s", sanitize(gcId), sanitize(e.getMessage())); + return Response.status(Response.Status.CONFLICT).type(TEXT_PLAIN) + .entity("The follow-up could not be applied: the conversation must be COMPLETED and have no " + + "other operation in progress.") + .build(); + } catch (IResourceStore.ResourceNotFoundException e) { + return Response.status(Response.Status.NOT_FOUND).type(TEXT_PLAIN) + .entity("Group conversation not found.").build(); + } catch (Exception e) { + LOGGER.errorf("Follow-up with member failed: %s", e.getMessage()); + throw sneakyThrow(e); + } + } + @Override public Response cancelDiscussion(String groupId, String gcId) { validateGroupConversationOwnership(groupId, gcId, true); @@ -295,6 +408,117 @@ public Response approveGroupPhase(String groupId, String gcId, GroupApprovalRequ } } + /** + * A continuation round cannot share NEW files: attachments are granted and + * injected to a member only on its first-ever turn, and on a continuation every + * member conversation already exists. Rather than accept them and silently drop + * them (or store an orphaned blob), reject them explicitly. Honouring them + * requires reworking the attachment fan-out β€” tracked as follow-up work. + */ + private static Response rejectAttachmentsOnContinue() { + return Response.status(Response.Status.BAD_REQUEST).type(TEXT_PLAIN) + .entity("Attachments cannot be added on a continuation round β€” they are only " + + "shared with member agents when the discussion starts. Start a new " + + "discussion to share new files.") + .build(); + } + + @Override + public Response continueDiscussion(String groupId, String gcId, DiscussRequest request) { + if (request == null || blank(request.question())) { + return Response.status(Response.Status.BAD_REQUEST).type(TEXT_PLAIN) + .entity("'question' is required.").build(); + } + if (request.attachments() != null && !request.attachments().isEmpty()) { + return rejectAttachmentsOnContinue(); + } + try { + GroupConversation gc = loadInGroup(groupId, gcId); + ownershipValidator.requireOwnerOrAdmin(identity, gc.getUserId(), "group conversation"); + GroupConversation result = groupConversationService.continueDiscussion(gcId, request.question(), null); + return Response.ok(result).build(); + } catch (ForbiddenException e) { + throw e; + } catch (IGroupConversationService.GroupTimeoutException e) { + LOGGER.warn("Continue on " + sanitize(gcId) + " timed out", e); + return Response.status(Response.Status.GATEWAY_TIMEOUT).type(TEXT_PLAIN) + .entity("A member agent did not respond in time. Try again.").build(); + } catch (IGroupConversationService.GroupExecutionException e) { + // The round could not be executed β€” a member agent / model call failed, or the + // group config is unrunnable. An upstream/server failure (5xx), not a retryable + // conflict. Hedged body: this catch covers both the agent-call and config + // paths. + LOGGER.error("Continue on " + sanitize(gcId) + " failed to execute", e); + return Response.status(Response.Status.BAD_GATEWAY).type(TEXT_PLAIN) + .entity("The continuation round could not be completed: a member agent or a required " + + "dependency could not be reached, or the group is misconfigured.") + .build(); + } catch (IGroupConversationService.GroupDiscussionException e) { + // Base type now means only a state / concurrency conflict. + LOGGER.infof("Continue on %s conflicted: %s", sanitize(gcId), sanitize(e.getMessage())); + return Response.status(Response.Status.CONFLICT).type(TEXT_PLAIN) + .entity("The continuation could not be applied: the conversation must be COMPLETED and have no " + + "other operation in progress.") + .build(); + } catch (IResourceStore.ResourceNotFoundException e) { + return Response.status(Response.Status.NOT_FOUND).type(TEXT_PLAIN) + .entity("Group conversation not found.").build(); + } catch (Exception e) { + LOGGER.errorf("Continue discussion failed: %s", e.getMessage()); + throw sneakyThrow(e); + } + } + + @Override + public void continueDiscussionStreaming(String groupId, String gcId, DiscussRequest request, + SseEventSink eventSink, Sse sse) { + if (request == null || blank(request.question())) { + sendEvent(eventSink, sse, GroupConversationEventSink.EVENT_GROUP_ERROR, + toJson(new GroupConversationEventSink.GroupErrorEvent("'question' is required"))); + closeQuietly(eventSink); + return; + } + if (request.attachments() != null && !request.attachments().isEmpty()) { + // See rejectAttachmentsOnContinue β€” a continuation cannot share new files. + sendEvent(eventSink, sse, GroupConversationEventSink.EVENT_GROUP_ERROR, + toJson(new GroupConversationEventSink.GroupErrorEvent( + "Attachments cannot be added on a continuation round."))); + closeQuietly(eventSink); + return; + } + try { + GroupConversation gc = loadInGroup(groupId, gcId); + ownershipValidator.requireOwnerOrAdmin(identity, gc.getUserId(), "group conversation"); + + // Reuse the shared streaming listener so a continuation that pauses or is + // cancelled for HITL streams the awaiting_approval / cancelled / + // member_pause_skipped events (and round_start) instead of silently + // swallowing them and hanging the client. + var listener = createStreamingListener(eventSink, sse); + + executorService.submit(() -> { + try { + groupConversationService.continueDiscussion(gcId, request.question(), listener); + } catch (Exception e) { + // Curated event text β€” never forward the raw message over SSE. + LOGGER.errorf("Continue discussion streaming failed: %s", e.getMessage()); + listener.onGroupError(new GroupConversationEventSink.GroupErrorEvent( + "The continuation could not be completed.")); + } + }); + + } catch (ForbiddenException e) { + throw e; + } catch (IResourceStore.ResourceNotFoundException e) { + sendErrorEvent(eventSink, sse, "Group conversation not found."); + closeQuietly(eventSink); + } catch (Exception e) { + LOGGER.errorf("Continue discussion streaming setup failed: %s", e.getMessage()); + sendErrorEvent(eventSink, sse, "The continuation could not be started."); + closeQuietly(eventSink); + } + } + @Override public void approveGroupPhaseStreaming(String groupId, String gcId, GroupApprovalRequest request, SseEventSink eventSink, Sse sse) { @@ -357,6 +581,32 @@ public void approveGroupPhaseStreaming(String groupId, String gcId, GroupApprova } } + @Override + public Response closeGroupConversation(String groupId, String gcId) { + try { + GroupConversation gc = loadInGroup(groupId, gcId); + ownershipValidator.requireOwnerOrAdmin(identity, gc.getUserId(), "group conversation"); + GroupConversation result = groupConversationService.closeGroupConversation(gcId); + return Response.ok(result).build(); + } catch (ForbiddenException e) { + throw e; + } catch (IGroupConversationService.GroupDiscussionException e) { + LOGGER.infof("Close of %s conflicted: %s", sanitize(gcId), sanitize(e.getMessage())); + return Response.status(Response.Status.CONFLICT).type(TEXT_PLAIN) + .entity("Close not possible: the conversation must be COMPLETED, FAILED or CANCELLED " + + "(it may still be running or already closed), and no other operation may be in progress.") + .build(); + } catch (IResourceStore.ResourceNotFoundException e) { + return Response.status(Response.Status.NOT_FOUND).type(TEXT_PLAIN) + .entity("Group conversation not found.").build(); + } catch (Exception e) { + // Genuine store/DB failures (ResourceStoreException) map to 500 via the + // global mapper β€” only business conflicts above are 409. + LOGGER.errorf("Close group conversation failed: %s", e.getMessage()); + throw sneakyThrow(e); + } + } + /** * JSON-safe error event β€” the message goes through the serializer, never string * concatenation. @@ -472,6 +722,11 @@ private void setDecidedByFromIdentity(GroupApprovalRequest request) { private GroupDiscussionEventListener createStreamingListener(SseEventSink eventSink, Sse sse) { return new GroupDiscussionEventListener() { + @Override + public void onRoundStart(GroupConversationEventSink.RoundStartEvent event) { + sendEvent(eventSink, sse, GroupConversationEventSink.EVENT_ROUND_START, toJson(event)); + } + @Override public void onGroupStart(GroupConversationEventSink.GroupStartEvent event) { sendEvent(eventSink, sse, GroupConversationEventSink.EVENT_GROUP_START, toJson(event)); diff --git a/src/main/java/ai/labs/eddi/engine/lifecycle/GroupConversationEventSink.java b/src/main/java/ai/labs/eddi/engine/lifecycle/GroupConversationEventSink.java index 176a70e0a9..d6062ba01d 100644 --- a/src/main/java/ai/labs/eddi/engine/lifecycle/GroupConversationEventSink.java +++ b/src/main/java/ai/labs/eddi/engine/lifecycle/GroupConversationEventSink.java @@ -34,6 +34,7 @@ private GroupConversationEventSink() { public static final String EVENT_GROUP_ERROR = "group_error"; public static final String EVENT_TASK_PLAN_CREATED = "task_plan_created"; public static final String EVENT_TASK_VERIFIED = "task_verified"; + public static final String EVENT_ROUND_START = "round_start"; public static final String EVENT_CANCELLED = "cancelled"; public static final String EVENT_AWAITING_APPROVAL = "awaiting_approval"; public static final String EVENT_HITL_RESUME = "hitl_resume"; @@ -89,6 +90,9 @@ public record TaskVerifiedEvent(String taskId, String taskSubject, boolean passe public record TaskSummary(String id, String subject, String assignedTo, int priority) { } + public record RoundStartEvent(String groupConversationId, int round, String question, int phaseCount) { + } + public record CancelledEvent(String reason, String cancelledBy) { } diff --git a/src/main/java/ai/labs/eddi/engine/mcp/McpGroupTools.java b/src/main/java/ai/labs/eddi/engine/mcp/McpGroupTools.java index a91dcc203c..217ad9712f 100644 --- a/src/main/java/ai/labs/eddi/engine/mcp/McpGroupTools.java +++ b/src/main/java/ai/labs/eddi/engine/mcp/McpGroupTools.java @@ -13,10 +13,14 @@ import ai.labs.eddi.configs.groups.model.DiscussionStylePresets; import ai.labs.eddi.configs.groups.model.GroupConversation; import ai.labs.eddi.configs.descriptors.model.DocumentDescriptor; +import ai.labs.eddi.datastore.IResourceStore; import ai.labs.eddi.datastore.serialization.IJsonSerialization; import ai.labs.eddi.engine.api.IGroupConversationService; +import ai.labs.eddi.engine.security.OwnershipValidator; +import ai.labs.eddi.utils.LogSanitizer; import io.quarkiverse.mcp.server.Tool; import io.quarkiverse.mcp.server.ToolArg; +import io.quarkus.security.ForbiddenException; import io.quarkus.security.identity.SecurityIdentity; import io.smallrye.common.annotation.Blocking; import jakarta.enterprise.context.ApplicationScoped; @@ -47,18 +51,59 @@ public class McpGroupTools { private final IGroupConversationService groupConversationService; private final IJsonSerialization jsonSerialization; private final SecurityIdentity identity; + private final OwnershipValidator ownershipValidator; private final boolean authEnabled; @Inject public McpGroupTools(IRestAgentGroupStore groupStore, IGroupConversationService groupConversationService, IJsonSerialization jsonSerialization, - SecurityIdentity identity, @ConfigProperty(name = "authorization.enabled", defaultValue = "false") boolean authEnabled) { + SecurityIdentity identity, OwnershipValidator ownershipValidator, + @ConfigProperty(name = "authorization.enabled", defaultValue = "false") boolean authEnabled) { this.groupStore = groupStore; this.groupConversationService = groupConversationService; this.jsonSerialization = jsonSerialization; this.identity = identity; + this.ownershipValidator = ownershipValidator; this.authEnabled = authEnabled; } + /** + * MCP parity with the REST surface: a specific group conversation may only be + * read or mutated by its owner (or an admin). The MCP role check alone is a + * coarse gate β€” without this, any caller holding the baseline MCP role could + * read, append to, re-run or close ANOTHER user's group conversation, while the + * equivalent REST endpoints all enforce {@code requireOwnerOrAdmin} (403). + */ + private void requireConversationOwner(String groupConversationId) + throws IResourceStore.ResourceNotFoundException, IResourceStore.ResourceStoreException { + GroupConversation gc = groupConversationService.readGroupConversation(groupConversationId); + ownershipValidator.requireOwnerOrAdmin(identity, gc.getUserId(), "group conversation"); + } + + /** + * Resolves the owner to record on a conversation created over MCP. With auth + * enabled this is the CALLING principal (a blank {@code userId} resolves to the + * caller, and a non-admin naming someone else is rejected) β€” so the creator can + * subsequently read/continue/close their own conversation through the ownership + * gate, and cannot create one owned by another user. The legacy "mcp-client" + * default only applies when auth is off (with auth on, {@code requireRole} has + * already rejected anonymous callers before this runs). + */ + private String resolveOwner(String userId) { + String resolved = ownershipValidator.validateAndResolveUserId(identity, userId); + return resolved != null && !resolved.isBlank() ? resolved : "mcp-client"; + } + + /** + * Uniform, non-leaking denial for an MCP call on someone else's conversation. + */ + private String accessDenied(String tool, String groupConversationId) { + // WARN, not INFO: an authorization denial is a security-relevant event that log + // monitoring should be able to alert on. + LOGGER.warnf("%s denied: caller does not own group conversation %s", + tool, LogSanitizer.sanitize(groupConversationId)); + return errorJson("Access denied: you do not own this group conversation"); + } + // --- Discovery --- @Tool(description = "Describe all available discussion styles for agent " + "groups. Returns the name, phase flow, and recommended use case " @@ -292,12 +337,15 @@ public String delete_group(@ToolArg(description = "Group ID") String groupId, + "poll with read_group_conversation).") public String discuss_with_group(@ToolArg(description = "Group configuration ID (from create_group " + "or list_groups)") String groupId, @ToolArg(description = "The question or topic for the group to " + "discuss") String question, - @ToolArg(description = "User ID (optional, defaults to " + "'mcp-client')") String userId) { + @ToolArg(description = "User ID (optional). With authorization enabled this defaults to the " + + "calling user and may not name another user.") String userId) { requireRole(identity, authEnabled, "eddi-viewer"); try { - String user = userId != null && !userId.isBlank() ? userId : "mcp-client"; + String user = resolveOwner(userId); GroupConversation gc = groupConversationService.discuss(groupId, question, user, 0); return jsonSerialization.serialize(gc); + } catch (ForbiddenException e) { + return errorJson("Access denied: you cannot start a conversation as another user"); } catch (Exception e) { LOGGER.errorf("discuss_with_group failed: %s", e.getMessage()); return errorJson(e.getMessage()); @@ -316,7 +364,10 @@ public String read_group_conversation( requireRole(identity, authEnabled, "eddi-viewer"); try { GroupConversation gc = groupConversationService.readGroupConversation(groupConversationId); + ownershipValidator.requireOwnerOrAdmin(identity, gc.getUserId(), "group conversation"); return jsonSerialization.serialize(gc); + } catch (ForbiddenException e) { + return accessDenied("read_group_conversation", groupConversationId); } catch (Exception e) { LOGGER.errorf("read_group_conversation failed: %s", e.getMessage()); return errorJson(e.getMessage()); @@ -332,6 +383,20 @@ public String list_group_conversations(@ToolArg(description = "Group configurati int idx = parseIntOrDefault(index, 0); int lim = parseIntOrDefault(limit, 20); List conversations = groupConversationService.listGroupConversations(groupId, idx, lim); + // Owner-filter (mirrors RestGroupConversation.listGroupConversations): these + // are + // FULL conversation documents (transcript, synthesized answer). Without this + // the + // per-conversation ownership gate is pointless β€” a non-owner could just list + // the + // group and read everyone's transcripts. + if (ownershipValidator.isAuthEnabled() && identity != null && !identity.isAnonymous() + && !identity.hasRole("eddi-admin")) { + String callerId = identity.getPrincipal().getName(); + conversations = conversations.stream() + .filter(gc -> callerId.equals(gc.getUserId())) + .toList(); + } return jsonSerialization.serialize(conversations); } catch (Exception e) { LOGGER.errorf("list_group_conversations failed: %s", e.getMessage()); @@ -349,15 +414,17 @@ public String list_group_conversations(@ToolArg(description = "Group configurati public String start_group_discussion( @ToolArg(description = "Group configuration ID (from create_group or list_groups)") String groupId, @ToolArg(description = "The question or topic for the group to discuss") String question, - @ToolArg(description = "User ID (optional, defaults to 'mcp-client')") String userId) { + @ToolArg(description = "User ID (optional). With authorization enabled this defaults to the calling user and may not name another user.") String userId) { requireRole(identity, authEnabled, "eddi-viewer"); try { - String user = userId != null && !userId.isBlank() ? userId : "mcp-client"; + String user = resolveOwner(userId); GroupConversation gc = groupConversationService.startAndDiscussAsync(groupId, question, user, null); return jsonSerialization.serialize(java.util.Map.of( "groupConversationId", gc.getId(), "state", String.valueOf(gc.getState()), "message", "Discussion started. Poll read_group_conversation with this ID to check progress.")); + } catch (ForbiddenException e) { + return errorJson("Access denied: you cannot start a conversation as another user"); } catch (Exception e) { LOGGER.errorf("start_group_discussion failed: %s", e.getMessage()); return errorJson(e.getMessage()); @@ -370,11 +437,84 @@ public String delete_group_conversation( @ToolArg(description = "Group conversation ID to delete") String groupConversationId) { requireRole(identity, authEnabled, "eddi-editor"); try { + requireConversationOwner(groupConversationId); groupConversationService.deleteGroupConversation(groupConversationId); return "Deleted group conversation " + groupConversationId; + } catch (ForbiddenException e) { + return accessDenied("delete_group_conversation", groupConversationId); } catch (Exception e) { LOGGER.errorf("delete_group_conversation failed: %s", e.getMessage()); return errorJson(e.getMessage()); } } + + // --- Follow-up Operations --- + + @Blocking + @Tool(description = "Ask a follow-up question to a specific member agent in a " + + "completed group conversation. The agent retains full context from " + + "the discussion. Both the question and response are recorded on the " + + "group transcript. Works for any member including the moderator. " + + "The targetAgentId accepts either an agent ID or a member's display name.") + public String followup_with_member( + @ToolArg(description = "Group conversation ID") String groupConversationId, + @ToolArg(description = "Agent ID or display name of the member to address") String targetAgentId, + @ToolArg(description = "The follow-up question") String question) { + requireRole(identity, authEnabled, "eddi-viewer"); + try { + requireConversationOwner(groupConversationId); + GroupConversation gc = groupConversationService.followUpWithMember( + groupConversationId, targetAgentId, question); + return jsonSerialization.serialize(gc); + } catch (ForbiddenException e) { + return accessDenied("followup_with_member", groupConversationId); + } catch (Exception e) { + // Curated payload β€” never echo the raw exception text to MCP callers + // (info exposure). Full detail (with stack trace) goes to the server log. + // Matches the McpHitlTools convention. + LOGGER.error("followup_with_member failed", e); + return errorJson("Failed to process follow-up with member", "INTERNAL", null); + } + } + + @Blocking + @Tool(description = "Continue a completed group conversation with a new question. " + + "All agents re-run through the full discussion phases, retaining memory " + + "of prior rounds. The round counter increments. Returns the updated " + + "GroupConversation with new synthesis.") + public String continue_group_discussion( + @ToolArg(description = "Group conversation ID") String groupConversationId, + @ToolArg(description = "The follow-up question for the group") String question) { + requireRole(identity, authEnabled, "eddi-viewer"); + try { + requireConversationOwner(groupConversationId); + GroupConversation gc = groupConversationService.continueDiscussion( + groupConversationId, question, null); + return jsonSerialization.serialize(gc); + } catch (ForbiddenException e) { + return accessDenied("continue_group_discussion", groupConversationId); + } catch (Exception e) { + LOGGER.error("continue_group_discussion failed", e); + return errorJson("Failed to continue group discussion", "INTERNAL", null); + } + } + + @Tool(description = "Close a group conversation permanently. Ends all member " + + "conversations and cleans up dynamically-created agents. No further " + + "follow-ups or continuations are possible after closing. " + + "Returns the closed GroupConversation.") + public String close_group_conversation( + @ToolArg(description = "Group conversation ID") String groupConversationId) { + requireRole(identity, authEnabled, "eddi-editor"); + try { + requireConversationOwner(groupConversationId); + GroupConversation gc = groupConversationService.closeGroupConversation(groupConversationId); + return jsonSerialization.serialize(gc); + } catch (ForbiddenException e) { + return accessDenied("close_group_conversation", groupConversationId); + } catch (Exception e) { + LOGGER.error("close_group_conversation failed", e); + return errorJson("Failed to close group conversation", "INTERNAL", null); + } + } } diff --git a/src/main/java/ai/labs/eddi/engine/mcp/McpToolFilter.java b/src/main/java/ai/labs/eddi/engine/mcp/McpToolFilter.java index d60553a454..954ed44a26 100644 --- a/src/main/java/ai/labs/eddi/engine/mcp/McpToolFilter.java +++ b/src/main/java/ai/labs/eddi/engine/mcp/McpToolFilter.java @@ -50,6 +50,8 @@ public class McpToolFilter implements ToolFilter { // Group Conversations (Phase 10) "describe_discussion_styles", "list_groups", "read_group", "create_group", "update_group", "delete_group", "discuss_with_group", "read_group_conversation", "list_group_conversations", "start_group_discussion", "delete_group_conversation", + // Group Conversation Follow-Ups + "followup_with_member", "continue_group_discussion", "close_group_conversation", // Schedule Management "create_schedule", "list_schedules", "read_schedule", "delete_schedule", "fire_schedule_now", "retry_failed_schedule", // Channel Integrations diff --git a/src/main/java/ai/labs/eddi/modules/llm/model/ToolExecutionTrace.java b/src/main/java/ai/labs/eddi/modules/llm/model/ToolExecutionTrace.java index 3f3575bf59..95159d9a5f 100644 --- a/src/main/java/ai/labs/eddi/modules/llm/model/ToolExecutionTrace.java +++ b/src/main/java/ai/labs/eddi/modules/llm/model/ToolExecutionTrace.java @@ -354,13 +354,15 @@ public String toString() { } /** - * Add a successful tool call to the trace + * Add a successful tool call to the trace. + * + *

+ * {@code synchronized} because a single trace is shared across all tasks of a + * parallel tool run (ToolExecutionService.executeToolsParallel passes one trace + * to every concurrent executeTool call). Without it, the backing + * ArrayList/HashMap and the primitive accumulators race β€” most visibly + * HashMap.computeIfAbsent throwing a ConcurrentModificationException. */ - // synchronized: ToolExecutionService.executeToolsParallel shares one trace - // across parallel - // tool executions, so the backing ArrayList + counter mutations here must be - // serialized - // (concurrent ArrayList.add corrupts the array β†’ ArrayIndexOutOfBounds). public synchronized void addToolCall(String toolName, String arguments, String result, long executionTimeMs, double cost, boolean fromCache) { ToolCall call = new ToolCall(); call.setToolName(toolName); @@ -386,10 +388,10 @@ public synchronized void addToolCall(String toolName, String arguments, String r } /** - * Add a failed tool call to the trace + * Add a failed tool call to the trace. {@code synchronized} for the same reason + * as {@link #addToolCall} β€” it is the other writer invoked concurrently from a + * shared trace during parallel tool execution. */ - // synchronized: see addToolCall β€” shared across parallel executions in - // executeToolsParallel. public synchronized void addFailedToolCall(String toolName, String arguments, String error, long executionTimeMs, double cost) { ToolCall call = new ToolCall(); call.setToolName(toolName); diff --git a/src/test/java/ai/labs/eddi/configs/groups/model/GroupConversationHitlTest.java b/src/test/java/ai/labs/eddi/configs/groups/model/GroupConversationHitlTest.java index 4f6e1b8f81..0cdd4bc001 100644 --- a/src/test/java/ai/labs/eddi/configs/groups/model/GroupConversationHitlTest.java +++ b/src/test/java/ai/labs/eddi/configs/groups/model/GroupConversationHitlTest.java @@ -49,8 +49,9 @@ void awaitingApprovalExists() { void valuesContainAllExpected() { var values = GroupConversationState.values(); // CREATED, IN_PROGRESS, SYNTHESIZING, COMPLETED, FAILED, CANCELLED, - // AWAITING_APPROVAL - assertEquals(7, values.length); + // AWAITING_APPROVAL, CLOSED (CLOSED added by the group follow-up feature) + assertEquals(8, values.length); + assertEquals(GroupConversationState.CLOSED, GroupConversationState.valueOf("CLOSED")); } } diff --git a/src/test/java/ai/labs/eddi/configs/groups/model/GroupConversationTest.java b/src/test/java/ai/labs/eddi/configs/groups/model/GroupConversationTest.java index f57a602623..4d9518bc74 100644 --- a/src/test/java/ai/labs/eddi/configs/groups/model/GroupConversationTest.java +++ b/src/test/java/ai/labs/eddi/configs/groups/model/GroupConversationTest.java @@ -39,6 +39,7 @@ void defaults() { assertNull(gc.getCurrentPhaseName()); assertNull(gc.getSynthesizedAnswer()); assertEquals(0, gc.getDepth()); + assertEquals(1, gc.getRound()); assertNull(gc.getCreated()); assertNull(gc.getLastModified()); } @@ -218,24 +219,26 @@ class EnumTests { @DisplayName("TranscriptEntryType β€” all values") void transcriptEntryTypes() { var values = TranscriptEntryType.values(); - assertEquals(14, values.length); + assertEquals(15, values.length); assertNotNull(TranscriptEntryType.valueOf("QUESTION")); assertNotNull(TranscriptEntryType.valueOf("SYNTHESIS")); assertNotNull(TranscriptEntryType.valueOf("SKIPPED")); assertNotNull(TranscriptEntryType.valueOf("PLAN")); assertNotNull(TranscriptEntryType.valueOf("TASK_RESULT")); assertNotNull(TranscriptEntryType.valueOf("VERIFICATION")); + assertNotNull(TranscriptEntryType.valueOf("FOLLOW_UP")); } @Test @DisplayName("GroupConversationState β€” all values") void groupConversationStates() { var values = GroupConversationState.values(); - assertEquals(7, values.length); + assertEquals(8, values.length); assertNotNull(GroupConversationState.valueOf("CREATED")); assertNotNull(GroupConversationState.valueOf("COMPLETED")); assertNotNull(GroupConversationState.valueOf("FAILED")); assertNotNull(GroupConversationState.valueOf("AWAITING_APPROVAL")); + assertNotNull(GroupConversationState.valueOf("CLOSED")); assertNotNull(GroupConversationState.valueOf("CANCELLED")); } } @@ -262,4 +265,117 @@ void setTranscript() { assertEquals(1, gc.getTranscript().size()); } + + @Test + @DisplayName("round setter round-trips") + void round_setterRoundTrips() { + var gc = new GroupConversation(); + gc.setRound(3); + assertEquals(3, gc.getRound()); + } + + // ==================== availableActions (computed) ==================== + + @Nested + @DisplayName("availableActions") + class AvailableActionsTests { + + @Test + @DisplayName("COMPLETED offers followup, continue, close") + void completed() { + var gc = new GroupConversation(); + gc.setState(GroupConversationState.COMPLETED); + assertEquals(List.of("followup", "continue", "close"), gc.getAvailableActions()); + } + + @Test + @DisplayName("FAILED offers close only") + void failed() { + var gc = new GroupConversation(); + gc.setState(GroupConversationState.FAILED); + assertEquals(List.of("close"), gc.getAvailableActions()); + } + + @Test + @DisplayName("CANCELLED offers close only") + void cancelled() { + var gc = new GroupConversation(); + gc.setState(GroupConversationState.CANCELLED); + assertEquals(List.of("close"), gc.getAvailableActions()); + } + + @Test + @DisplayName("CLOSED offers nothing") + void closed() { + var gc = new GroupConversation(); + gc.setState(GroupConversationState.CLOSED); + assertTrue(gc.getAvailableActions().isEmpty()); + } + + @Test + @DisplayName("non-terminal states offer nothing") + void nonTerminal() { + for (var state : List.of(GroupConversationState.CREATED, GroupConversationState.IN_PROGRESS, + GroupConversationState.SYNTHESIZING, GroupConversationState.AWAITING_APPROVAL)) { + var gc = new GroupConversation(); + gc.setState(state); + assertTrue(gc.getAvailableActions().isEmpty(), "expected no actions for " + state); + } + } + + @Test + @DisplayName("null state yields empty list, not null") + void nullState() { + var gc = new GroupConversation(); + assertNotNull(gc.getAvailableActions()); + assertTrue(gc.getAvailableActions().isEmpty()); + } + } + + // ==================== memberDisplayNames encapsulation ==================== + + @Nested + @DisplayName("memberDisplayNames") + class MemberDisplayNamesTests { + + @Test + @DisplayName("getter returns an unmodifiable view") + void getterUnmodifiable() { + var gc = new GroupConversation(); + gc.addMemberDisplayName("a", "Alice"); + assertThrows(UnsupportedOperationException.class, + () -> gc.getMemberDisplayNames().put("b", "Bob")); + } + + @Test + @DisplayName("addMemberDisplayName populates the map") + void addPopulates() { + var gc = new GroupConversation(); + gc.addMemberDisplayName("a", "Alice"); + gc.addMemberDisplayName("b", "Bob"); + assertEquals("Alice", gc.getMemberDisplayNames().get("a")); + assertEquals(2, gc.getMemberDisplayNames().size()); + } + + @Test + @DisplayName("setter defensively copies the input map") + void setterDefensiveCopy() { + var gc = new GroupConversation(); + var src = new LinkedHashMap(); + src.put("a", "Alice"); + gc.setMemberDisplayNames(src); + src.put("b", "Bob"); // mutate caller's map afterward β€” must not leak in + assertEquals(1, gc.getMemberDisplayNames().size()); + } + + @Test + @DisplayName("setter treats null as empty and stays mutable via add") + void setterNull() { + var gc = new GroupConversation(); + gc.setMemberDisplayNames(null); + assertTrue(gc.getMemberDisplayNames().isEmpty()); + assertDoesNotThrow(() -> gc.addMemberDisplayName("a", "Alice")); + assertEquals("Alice", gc.getMemberDisplayNames().get("a")); + } + } } diff --git a/src/test/java/ai/labs/eddi/configs/groups/mongo/GroupConversationStoreTest.java b/src/test/java/ai/labs/eddi/configs/groups/mongo/GroupConversationStoreTest.java index b3a6e8e018..9fd99900bd 100644 --- a/src/test/java/ai/labs/eddi/configs/groups/mongo/GroupConversationStoreTest.java +++ b/src/test/java/ai/labs/eddi/configs/groups/mongo/GroupConversationStoreTest.java @@ -90,6 +90,23 @@ void readNotFound() { assertThrows(IResourceStore.ResourceNotFoundException.class, () -> store.read("missing")); } + @Test + @DisplayName("read β€” the not-found message never embeds the caller-supplied id") + void readNotFound_messageDoesNotEmbedTheId() { + // This message is surfaced to clients by ResourceNotFoundExceptionMapper (which + // echoes getLocalizedMessage()) and by every REST handler that forwards it, so + // an + // id in here is a reflected-value sink (CodeQL) on every group endpoint. + String payload = ""; + when(storage.read(payload, 1)).thenReturn(null); + + var thrown = assertThrows(IResourceStore.ResourceNotFoundException.class, + () -> store.read(payload)); + + assertFalse(String.valueOf(thrown.getMessage()).contains(payload), + "the caller-supplied id must not appear in the exception message"); + } + // ==================== update ==================== @Test @@ -144,6 +161,85 @@ void listByGroupIdEmpty() throws Exception { assertTrue(result.isEmpty()); } + // ==================== compareAndSetState ==================== + + @Test + @DisplayName("compareAndSetState β€” transitions and returns true when state matches") + void compareAndSetState_matches() throws Exception { + GroupConversation gc = new GroupConversation(); + gc.setState(GroupConversation.GroupConversationState.COMPLETED); + IResourceStorage.IResource readResource = mock(IResourceStorage.IResource.class); + when(readResource.getData()).thenReturn(gc); + when(storage.read("gc-1", 1)).thenReturn(readResource); + IResourceStorage.IResource writeResource = mock(IResourceStorage.IResource.class); + when(storage.newResource(eq("gc-1"), eq(1), any(GroupConversation.class))).thenReturn(writeResource); + + boolean result = store.compareAndSetState("gc-1", + GroupConversation.GroupConversationState.COMPLETED, + GroupConversation.GroupConversationState.IN_PROGRESS); + + assertTrue(result); + // read() returns the same object that compareAndSetState mutates + assertEquals(GroupConversation.GroupConversationState.IN_PROGRESS, gc.getState()); + assertNotNull(gc.getLastModified()); + // The transition must be a CONDITIONAL write (expected state still persisted), + // not + // an unconditional store β€” otherwise two racing callers could both pass the + // read-check and both write. + verify(storage).storeIfFieldEquals(writeResource, "state", "COMPLETED"); + verify(storage, never()).store(any()); + } + + @Test + @DisplayName("compareAndSetState β€” returns false when the conditional write loses the race") + void compareAndSetState_lostRace_returnsFalse() throws Exception { + GroupConversation gc = new GroupConversation(); + gc.setState(GroupConversation.GroupConversationState.COMPLETED); + IResourceStorage.IResource readResource = mock(IResourceStorage.IResource.class); + when(readResource.getData()).thenReturn(gc); + when(storage.read("gc-1", 1)).thenReturn(readResource); + IResourceStorage.IResource writeResource = mock(IResourceStorage.IResource.class); + when(storage.newResource(eq("gc-1"), eq(1), any(GroupConversation.class))).thenReturn(writeResource); + // Another writer moved the state between our read and our conditional write. + doThrow(new IResourceStore.ResourceModifiedException("state changed")) + .when(storage).storeIfFieldEquals(eq(writeResource), eq("state"), anyString()); + + boolean result = store.compareAndSetState("gc-1", + GroupConversation.GroupConversationState.COMPLETED, + GroupConversation.GroupConversationState.IN_PROGRESS); + + assertFalse(result, "a lost CAS must report false, not silently overwrite the winner"); + } + + @Test + @DisplayName("compareAndSetState β€” returns false and does not update when state differs") + void compareAndSetState_mismatch() throws Exception { + GroupConversation gc = new GroupConversation(); + gc.setState(GroupConversation.GroupConversationState.FAILED); + IResourceStorage.IResource readResource = mock(IResourceStorage.IResource.class); + when(readResource.getData()).thenReturn(gc); + when(storage.read("gc-1", 1)).thenReturn(readResource); + + boolean result = store.compareAndSetState("gc-1", + GroupConversation.GroupConversationState.COMPLETED, + GroupConversation.GroupConversationState.CLOSED); + + assertFalse(result); + assertEquals(GroupConversation.GroupConversationState.FAILED, gc.getState()); + verify(storage, never()).store(any()); + } + + @Test + @DisplayName("compareAndSetState β€” throws ResourceNotFoundException when missing") + void compareAndSetState_notFound() { + when(storage.read("missing", 1)).thenReturn(null); + + assertThrows(IResourceStore.ResourceNotFoundException.class, + () -> store.compareAndSetState("missing", + GroupConversation.GroupConversationState.COMPLETED, + GroupConversation.GroupConversationState.CLOSED)); + } + @Test @DisplayName("listByGroupId β€” null groupId returns empty without NPE") void listByGroupIdNull() throws Exception { diff --git a/src/test/java/ai/labs/eddi/engine/api/IRestGroupConversationRoutingTest.java b/src/test/java/ai/labs/eddi/engine/api/IRestGroupConversationRoutingTest.java new file mode 100644 index 0000000000..99c09394e9 --- /dev/null +++ b/src/test/java/ai/labs/eddi/engine/api/IRestGroupConversationRoutingTest.java @@ -0,0 +1,144 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.engine.api; + +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Guards the JAX-RS routing contract of {@link IRestGroupConversation}. + *

+ * This exists because of a real regression: the class-level {@code @Path} was + * flattened from {@code /groups/{groupId}/conversations} to {@code /groups} (so + * the cross-group approvals inbox could live alongside the per-group routes), + * and every method was supposed to carry the {@code /{groupId}/conversations} + * prefix itself. Four methods kept their old class-relative paths, so they lost + * the {@code {groupId}} template segment while still declaring + * {@code @PathParam("groupId")} β€” RESTEasy bound {@code groupId} to + * {@code null} and every follow-up / continue / close request would have 404'd + * in production. + *

+ * The unit tests could not see this: they invoke the resource methods directly + * and never exercise JAX-RS path binding. These assertions check the invariant + * on the annotations themselves, which is exactly what a direct-invocation test + * cannot. + */ +class IRestGroupConversationRoutingTest { + + private static String classPath() { + Path p = IRestGroupConversation.class.getAnnotation(Path.class); + return p == null ? "" : p.value(); + } + + /** + * The full external path of a resource method: class-level @Path + + * method @Path. + */ + private static String effectivePath(Method m) { + Path p = m.getAnnotation(Path.class); + String methodPath = p == null ? "" : p.value(); + return (classPath() + "/" + methodPath).replace("//", "/"); + } + + private static List resourceMethods() { + var out = new ArrayList(); + for (Method m : IRestGroupConversation.class.getDeclaredMethods()) { + if (m.isSynthetic()) { + continue; + } + out.add(m); + } + return out; + } + + @Test + @DisplayName("every @PathParam a method declares must exist as a template in its effective path") + void everyPathParamHasATemplateSegment() { + var violations = new ArrayList(); + + for (Method m : resourceMethods()) { + String path = effectivePath(m); + for (Parameter param : m.getParameters()) { + PathParam pp = param.getAnnotation(PathParam.class); + if (pp == null) { + continue; + } + String template = "{" + pp.value() + "}"; + if (!path.contains(template)) { + violations.add(m.getName() + " declares @PathParam(\"" + pp.value() + + "\") but its path '" + path + "' has no " + template + " segment"); + } + } + } + + // A @PathParam with no matching template binds to null at runtime β€” the exact + // failure that made followup/continue/continue-stream/close 404 for every + // caller. + assertTrue(violations.isEmpty(), + "JAX-RS path/param mismatch (the parameter would bind to null):\n " + String.join("\n ", violations)); + } + + @Test + @DisplayName("every per-conversation route is nested under /groups/{groupId}/conversations/{groupConversationId}") + void perConversationRoutesKeepTheGroupPrefix() { + var violations = new ArrayList(); + + for (Method m : resourceMethods()) { + boolean takesConversationId = false; + for (Parameter param : m.getParameters()) { + PathParam pp = param.getAnnotation(PathParam.class); + if (pp != null && "groupConversationId".equals(pp.value())) { + takesConversationId = true; + } + } + if (!takesConversationId) { + continue; + } + String path = effectivePath(m); + if (!path.startsWith("/groups/{groupId}/conversations/{groupConversationId}")) { + violations.add(m.getName() + " -> " + path); + } + } + + assertTrue(violations.isEmpty(), + "per-conversation routes must stay under /groups/{groupId}/conversations/{groupConversationId} " + + "(external URLs must not change):\n " + String.join("\n ", violations)); + } + + @Test + @DisplayName("the four post-discussion endpoints resolve to their documented external URLs") + void postDiscussionEndpointsHaveTheirDocumentedUrls() throws Exception { + String base = "/groups/{groupId}/conversations/{groupConversationId}"; + + assertPath("followUpWithMember", base + "/followup"); + assertPath("continueDiscussion", base + "/continue"); + assertPath("continueDiscussionStreaming", base + "/continue/stream"); + assertPath("closeGroupConversation", base + "/close"); + } + + private static void assertPath(String methodName, String expected) { + Method target = null; + for (Method m : resourceMethods()) { + if (m.getName().equals(methodName)) { + target = m; + break; + } + } + assertFalse(target == null, "no such resource method: " + methodName); + String actual = effectivePath(target); + assertTrue(expected.equals(actual), + methodName + " must be exposed at " + expected + " but is at " + actual); + } +} diff --git a/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceExtendedTest.java b/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceExtendedTest.java index 7b33a35a3a..f966d64da1 100644 --- a/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceExtendedTest.java +++ b/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceExtendedTest.java @@ -29,6 +29,7 @@ import ai.labs.eddi.modules.templating.ITemplatingEngine; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -57,6 +58,8 @@ class GroupConversationServiceExtendedTest { private IJsonSerialization jsonSerialization; private GroupConversationService service; + private ai.labs.eddi.configs.agents.IAgentStore agentStore; + private static final String GROUP_ID = "test-group"; private static final String USER_ID = "test-user"; private static final String QUESTION = "What is the best approach?"; @@ -70,10 +73,11 @@ void setUp() throws Exception { templatingEngine = mock(ITemplatingEngine.class); jsonSerialization = mock(IJsonSerialization.class); + agentStore = mock(ai.labs.eddi.configs.agents.IAgentStore.class); service = new GroupConversationService(groupStore, conversationStore, conversationService, agentFactory, templatingEngine, jsonSerialization, new SimpleMeterRegistry(), - null, null, null, null, null, "default", 3); + null, agentStore, null, null, null, "default", 3); when(conversationStore.create(any())).thenReturn("gc-1"); @@ -587,7 +591,10 @@ void unavailablePolicy_fail_throwsException() throws Exception { when(agentFactory.getLatestReadyAgent(any(Environment.class), eq("a1"))) .thenReturn(null); - assertThrows(GroupDiscussionException.class, + // executeDiscussion must surface an execution failure as + // GroupExecutionException + // (which REST maps to 5xx), not a bare GroupDiscussionException (409). + assertThrows(ai.labs.eddi.engine.api.IGroupConversationService.GroupExecutionException.class, () -> service.discuss(GROUP_ID, QUESTION, USER_ID, 0)); } @@ -603,7 +610,7 @@ void unavailablePolicy_fail_agentThrowsException() throws Exception { when(agentFactory.getLatestReadyAgent(any(Environment.class), eq("a1"))) .thenThrow(new RuntimeException("Agent check failed")); - assertThrows(GroupDiscussionException.class, + assertThrows(ai.labs.eddi.engine.api.IGroupConversationService.GroupExecutionException.class, () -> service.discuss(GROUP_ID, QUESTION, USER_ID, 0)); } @@ -653,6 +660,35 @@ void retryPolicy_agentFails_retriesAndThenSkips() throws Exception { .anyMatch(e -> e.type() == TranscriptEntryType.SKIPPED && "a1".equals(e.speakerAgentId()))); } + + @Test + void abortPolicy_agentTimesOut_throwsGroupTimeoutException() throws Exception { + var cfg = config(DiscussionStyle.ROUND_TABLE, 1, + new GroupMember("a1", "Alice", 1, null)); + cfg.setModeratorAgentId("mod"); + // 1s timeout, ABORT on failure, no retries β†’ a member timeout aborts fast. + cfg.setProtocol(new ProtocolConfig(1, + ProtocolConfig.MemberFailurePolicy.ABORT, 0, + ProtocolConfig.MemberUnavailablePolicy.SKIP)); + setupStore(cfg); + + when(agentFactory.getLatestReadyAgent(any(Environment.class), eq("a1"))) + .thenReturn(mock(IAgent.class)); + when(conversationService.startConversation(any(), eq("a1"), any(), any())) + .thenReturn(new IConversationService.ConversationResult("conv-a1", null)); + // say() never invokes the response handler β†’ the future never completes β†’ the + // get(timeout) call times out, and under ABORT the round is aborted. + doNothing().when(conversationService).say(any(Environment.class), eq("a1"), + anyString(), any(), any(), any(), any(InputData.class), + anyBoolean(), any(ConversationResponseHandler.class)); + + // A real member-agent timeout must be a GroupTimeoutException so REST maps it + // to + // 504 (not the 502 an ordinary execution failure gets). executeDiscussion's + // re-wrap preserves the subtype. + assertThrows(ai.labs.eddi.engine.api.IGroupConversationService.GroupTimeoutException.class, + () -> service.discuss(GROUP_ID, QUESTION, USER_ID, 0)); + } } // ========================================================= @@ -1360,4 +1396,105 @@ void ownFeedbackScope_onlyIncludesFeedbackTargetedAtSpeaker() throws Exception { .anyMatch(e -> e.type() == TranscriptEntryType.REVISION)); } } + + // ========================================================= + // Regression guards for bugs the direct-invocation tests could not see. + // Each of these was a surviving mutant: the fix could be reverted with the + // whole suite still green. + // ========================================================= + + @Nested + class MergeRegressionGuards { + + @Test + @DisplayName("a failed discussion streams a CURATED error β€” never the raw exception text") + void failedDiscussion_doesNotLeakRawExceptionTextToTheListener() throws Exception { + var cfg = config(DiscussionStyle.ROUND_TABLE, 1, + new GroupMember("a1", "Alice", 1, null)); + cfg.setProtocol(new ProtocolConfig(60, + ProtocolConfig.MemberFailurePolicy.SKIP, 2, + ProtocolConfig.MemberUnavailablePolicy.FAIL)); + setupStore(cfg); + // Agent unavailable + FAIL policy => executeDiscussion throws. + when(agentFactory.getLatestReadyAgent(any(Environment.class), eq("a1"))) + .thenReturn(null); + + var listener = mock(GroupDiscussionEventListener.class); + + assertThrows(GroupDiscussionException.class, + () -> service.discuss(GROUP_ID, QUESTION, USER_ID, 0, listener)); + + var captor = ArgumentCaptor.forClass(GroupConversationEventSink.GroupErrorEvent.class); + verify(listener, atLeastOnce()).onGroupError(captor.capture()); + + // The listener installed by RestGroupConversation forwards this text straight + // to the browser over SSE. The raw message can carry LLM/DB/driver detail and + // the caller's own input, so it must never be the event payload. + for (var event : captor.getAllValues()) { + String text = String.valueOf(event.error()); + assertFalse(text.contains("a1"), + "the SSE error event must not carry the raw exception text: " + text); + assertFalse(text.toLowerCase().contains("agent unavailable"), + "the SSE error event must be curated, not the raw message: " + text); + } + } + + @Test + @DisplayName("a continuation re-runs from the FIRST phase (startPhaseIndex 0), not from phase 1") + void continuation_restartsAtPhaseZero() throws Exception { + var cfg = config(DiscussionStyle.ROUND_TABLE, 1, + new GroupMember("a1", "Alice", 1, null)); + cfg.setModeratorAgentId("mod"); + setupStore(cfg); + stubAgent("a1", "Opinion"); + stubAgent("mod", "Synthesis"); + + var completed = new GroupConversation(); + completed.setId("gc-1"); + completed.setGroupId(GROUP_ID); + completed.setState(GroupConversation.GroupConversationState.COMPLETED); + completed.setRound(1); + when(conversationStore.read("gc-1")).thenReturn(completed); + when(conversationStore.compareAndSetState("gc-1", + GroupConversation.GroupConversationState.COMPLETED, + GroupConversation.GroupConversationState.IN_PROGRESS)).thenReturn(true); + + var listener = mock(GroupDiscussionEventListener.class); + + service.continueDiscussion("gc-1", "round two question", listener); + + // A continuation re-runs the WHOLE protocol. If startPhaseIndex were anything + // but 0, phase 0 would be silently skipped and the round would be incomplete. + var phases = ArgumentCaptor.forClass(GroupConversationEventSink.PhaseStartEvent.class); + verify(listener, atLeastOnce()).onPhaseStart(phases.capture()); + assertTrue(phases.getAllValues().stream().anyMatch(p -> p.phaseIndex() == 0), + "the first phase must run on a continuation round"); + // It is a new ROUND, not a new discussion. + verify(listener).onRoundStart(any(GroupConversationEventSink.RoundStartEvent.class)); + verify(listener, never()).onGroupStart(any(GroupConversationEventSink.GroupStartEvent.class)); + } + + @Test + @DisplayName("ephemeral agents survive a COMPLETED round (follow-ups reuse them) but are reclaimed on failure") + void ephemeralCleanup_isDeferredForCompleted_butRunsOnFailure() throws Exception { + var cfg = config(DiscussionStyle.ROUND_TABLE, 1, + new GroupMember("a1", "Alice", 1, null)); + cfg.setModeratorAgentId("mod"); + setupStore(cfg); + stubAgent("a1", "Opinion"); + stubAgent("mod", "Synthesis"); + // A dynamically-created agent that a follow-up/continue would want to reuse. + when(conversationStore.create(any())).thenAnswer(inv -> { + GroupConversation gc = inv.getArgument(0); + gc.getCreatedAgentIds().add("ephemeral-1"); + return "gc-1"; + }); + + service.discuss(GROUP_ID, QUESTION, USER_ID, 0); + + // COMPLETED must DEFER cleanup to close/delete β€” otherwise a follow-up or a + // continuation has no agents left to talk to. + verify(agentStore, never()).deleteAllPermanently(anyString()); + } + } } diff --git a/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceHitlCoverage2Test.java b/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceHitlCoverage2Test.java index a5075d50bf..d2b7149390 100644 --- a/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceHitlCoverage2Test.java +++ b/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceHitlCoverage2Test.java @@ -450,7 +450,8 @@ void failConversationSuccess() throws Exception { invoke(m, gc); assertEquals(GroupConversationState.FAILED, gc.getState()); - verify(conversationStore).update(gc); + // Conditional write (CAS on the running state), never an unconditional upsert. + verify(conversationStore).updateIfState(gc, GroupConversationState.IN_PROGRESS); } @Test @@ -458,7 +459,8 @@ void failConversationSuccess() throws Exception { void failConversationUpdateThrows() throws Exception { var gc = pausedPhaseGc("gc-fail-throw"); gc.setState(GroupConversationState.IN_PROGRESS); - doThrow(new RuntimeException("update failed")).when(conversationStore).update(gc); + doThrow(new RuntimeException("update failed")) + .when(conversationStore).updateIfState(gc, GroupConversationState.IN_PROGRESS); var m = method("failConversation", GroupConversation.class); assertDoesNotThrow(() -> invoke(m, gc)); diff --git a/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceHitlTest.java b/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceHitlTest.java index 47631eb953..dff7086b86 100644 --- a/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceHitlTest.java +++ b/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceHitlTest.java @@ -37,6 +37,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -45,6 +46,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; @@ -310,6 +312,59 @@ void resumeStartsFromNextPhase() throws Exception { // Verify updateIfState was called with AWAITING_APPROVAL (CAS) verify(conversationStore).updateIfState(gc, GroupConversationState.AWAITING_APPROVAL); } + + @Test + @DisplayName("resuming a paused CONTINUATION re-runs the remaining phases with the follow-up question") + void resumeUsesTheContinuationQuestion_notTheStaleRoundOneQuestion() throws Exception { + // A continuation round sets resumeQuestion; originalQuestion still holds the + // round-1 question (the UI renders it as the conversation title). If resume + // read originalQuestion, every post-pause phase β€” and the final synthesis β€” + // would silently answer the WRONG question. + var gc = new GroupConversation(); + gc.setId("gc-resume"); + gc.setGroupId(GROUP_ID); + gc.setState(GroupConversationState.AWAITING_APPROVAL); + gc.setPausedAtPhaseIndex(0); + gc.setPausedPhaseName("Phase0"); + gc.setPausedAt(Instant.now()); + gc.setOriginalQuestion("round one question"); + gc.setResumeQuestion("round two question"); + gc.setRound(2); + + doReturn(gc).when(conversationStore).read("gc-resume"); + + var phases = List.of( + new DiscussionPhase("Phase0", PhaseType.OPINION), + new DiscussionPhase("Phase1", PhaseType.CRITIQUE)); + var config = buildConfig(phases); + var resId = mockResourceId(); + doReturn(resId).when(groupStore).getCurrentResourceId(GROUP_ID); + doReturn(config).when(groupStore).read(GROUP_ID, 1); + stubAgentSay(); + + var request = new GroupApprovalRequest(); + var decision = new HitlDecision(); + decision.setVerdict(HitlVerdict.APPROVED); + request.setDecision(decision); + + service.resumeDiscussion("gc-resume", request, null); + + // The resumed leg runs on a background thread; the phase prompt is built from + // this data map, so it carries the question the agents actually answer. + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(templatingEngine, timeout(3000).atLeastOnce()) + .processTemplate(anyString(), captor.capture(), any(ITemplatingEngine.TemplateMode.class)); + + var questions = captor.getAllValues().stream() + .map(d -> String.valueOf(d.get("question"))) + .distinct() + .toList(); + assertTrue(questions.contains("round two question"), + "resume must re-run the phases with the continuation question, but used: " + questions); + assertFalse(questions.contains("round one question"), + "resume must NOT fall back to the stale round-1 question: " + questions); + } } // ================================================================= diff --git a/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceTest.java b/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceTest.java index ddb2e11723..c5e91a5808 100644 --- a/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceTest.java +++ b/src/test/java/ai/labs/eddi/engine/internal/GroupConversationServiceTest.java @@ -24,7 +24,9 @@ import ai.labs.eddi.engine.api.IConversationService; import ai.labs.eddi.engine.api.IGroupConversationService.GroupDepthExceededException; import ai.labs.eddi.engine.api.IGroupConversationService.GroupDiscussionException; +import ai.labs.eddi.engine.api.IGroupConversationService.GroupDiscussionEventListener; import ai.labs.eddi.engine.attachments.IAttachmentStore; +import ai.labs.eddi.engine.lifecycle.model.ControlSignal; import ai.labs.eddi.engine.model.Context; import ai.labs.eddi.engine.memory.model.Attachment; import ai.labs.eddi.engine.memory.model.ConversationOutput; @@ -45,6 +47,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @@ -77,6 +80,8 @@ class GroupConversationServiceTest { private NonceCacheService nonceCacheService; private GroupConversationService service; + /** Real registry (not a mock) so the new operation counters can be asserted. */ + private SimpleMeterRegistry meterRegistry; private static final int MAX_DEPTH = 3; private static final String DEFAULT_TENANT = "default"; @@ -84,10 +89,11 @@ class GroupConversationServiceTest { @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); + meterRegistry = new SimpleMeterRegistry(); service = new GroupConversationService( groupStore, conversationStore, conversationService, agentFactory, templatingEngine, jsonSerialization, - new SimpleMeterRegistry(), agentSigningService, agentStore, + meterRegistry, agentSigningService, agentStore, mock(IScheduleStore.class), nonceCacheService, null, DEFAULT_TENANT, MAX_DEPTH); } @@ -891,7 +897,11 @@ void failConversation_setsStateToFailed() throws Exception { assertEquals(GroupConversationState.FAILED, gc.getState()); assertNotNull(gc.getLastModified()); - verify(conversationStore).update(gc); + // Conditional write (CAS on the running state) β€” an unconditional update() is + // an upsert and would resurrect a conversation another pod deleted, or + // overwrite a terminal CANCELLED with FAILED. + verify(conversationStore).updateIfState(gc, GroupConversationState.IN_PROGRESS); + verify(conversationStore, never()).update(gc); } @Test @@ -900,12 +910,538 @@ void failConversation_handlesUpdateException() throws Exception { gc.setId("gc-1"); gc.setState(GroupConversationState.IN_PROGRESS); doThrow(new IResourceStore.ResourceStoreException("DB error")) - .when(conversationStore).update(gc); + .when(conversationStore).updateIfState(gc, GroupConversationState.IN_PROGRESS); // Should not throw β€” logs warning instead assertDoesNotThrow(() -> failConversationMethod.invoke(service, gc)); assertEquals(GroupConversationState.FAILED, gc.getState()); } + + @Test + void failConversation_countsTheFailureEvenWhenTheCasIsLost() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setState(GroupConversationState.IN_PROGRESS); + var persisted = new GroupConversation(); + persisted.setId("gc-1"); + persisted.setState(GroupConversationState.CANCELLED); + when(conversationStore.read("gc-1")).thenReturn(persisted); + + failConversationMethod.invoke(service, gc); + + // The metric must record the failure itself, not the outcome of the race β€” + // otherwise a lost CAS hides the failure from operators entirely. + assertEquals(1.0, meterRegistry.counter("eddi_group_discussion_failure_count").count()); + } + + @Test + void failConversation_casesOnThePersistedState_notTheStaleInMemoryOne() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc-1"); + // executeDiscussion flips the conversation to SYNTHESIZING in memory BEFORE the + // synthesis phase runs, and only persists it afterwards. A CAS on the in-memory + // value would therefore expect SYNTHESIZING while the document still says + // IN_PROGRESS β€” it would lose, skip the write, and strand the conversation + // IN_PROGRESS forever. + gc.setState(GroupConversationState.SYNTHESIZING); + var persisted = new GroupConversation(); + persisted.setId("gc-1"); + persisted.setState(GroupConversationState.IN_PROGRESS); + when(conversationStore.read("gc-1")).thenReturn(persisted); + + failConversationMethod.invoke(service, gc); + + assertEquals(GroupConversationState.FAILED, gc.getState()); + verify(conversationStore).updateIfState(gc, GroupConversationState.IN_PROGRESS); + } + + @Test + void failConversation_alreadyTerminalInStore_writesNothing() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setState(GroupConversationState.IN_PROGRESS); + var persisted = new GroupConversation(); + persisted.setId("gc-1"); + persisted.setState(GroupConversationState.CANCELLED); // another pod cancelled it + when(conversationStore.read("gc-1")).thenReturn(persisted); + + failConversationMethod.invoke(service, gc); + + // Neither a conditional nor an unconditional write β€” the terminal state stands. + verify(conversationStore, never()).updateIfState(any(), any()); + verify(conversationStore, never()).update(any()); + } + + @Test + void failConversation_doesNotResurrectATerminalOrDeletedConversation() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setState(GroupConversationState.IN_PROGRESS); + // Another pod already cancelled (or deleted) it β€” the CAS must lose. + doThrow(new IResourceStore.ResourceModifiedException("cancelled elsewhere")) + .when(conversationStore).updateIfState(gc, GroupConversationState.IN_PROGRESS); + + assertDoesNotThrow(() -> failConversationMethod.invoke(service, gc)); + + // Crucially: no unconditional write β€” update() upserts and would re-create a + // deleted document / clobber the terminal state. + verify(conversationStore, never()).update(any()); + } + } + + // ================================================================= + // Post-discussion operations: follow-up / continue / close + // ================================================================= + + /** Reflectively access the private per-conversation concurrency guard set. */ + @SuppressWarnings("unchecked") + private java.util.Set operationsInProgress() throws Exception { + var field = GroupConversationService.class.getDeclaredField("operationsInProgress"); + field.setAccessible(true); + return (java.util.Set) field.get(service); + } + + @Nested + class FollowUpWithMemberTests { + + private GroupConversation completedGc() { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setGroupId("group-1"); + gc.setState(GroupConversationState.COMPLETED); + gc.setMemberConversationIds(new LinkedHashMap<>(Map.of("agentA", "convA"))); + gc.addMemberDisplayName("agentA", "Alice"); + return gc; + } + + @Test + void followUp_resolvesDisplayName_callsCorrectAgentAndRecordsTranscript() throws Exception { + var gc = completedGc(); + when(conversationStore.read("gc-1")).thenReturn(gc); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.COMPLETED, GroupConversationState.IN_PROGRESS)).thenReturn(true); + + var snapshot = new SimpleConversationMemorySnapshot(); + var output = new ConversationOutput(); + output.put("output", List.of("Sure, here is the answer")); + snapshot.setConversationOutputs(new LinkedList<>(List.of(output))); + doAnswer(inv -> { + IConversationService.ConversationResponseHandler handler = inv.getArgument(8); + handler.onComplete(snapshot); + return null; + }).when(conversationService).say(any(), eq("agentA"), eq("convA"), + any(), any(), any(), any(), anyBoolean(), any()); + + // Address the member by display name (case-insensitive) rather than agent id + GroupConversation result = service.followUpWithMember("gc-1", "alice", "What now?"); + + verify(conversationService).say(any(), eq("agentA"), eq("convA"), + any(), any(), any(), any(), anyBoolean(), any()); + assertEquals(GroupConversationState.COMPLETED, result.getState()); + var transcript = result.getTranscript(); + assertEquals(2, transcript.size()); + assertEquals(TranscriptEntryType.FOLLOW_UP, transcript.get(0).type()); + assertEquals("What now?", transcript.get(0).content()); + assertEquals("agentA", transcript.get(1).speakerAgentId()); + assertEquals("Sure, here is the answer", transcript.get(1).content()); + // Success path now writes atomically (CAS on IN_PROGRESS) so a racing cancel + // cannot be clobbered β€” see followUpWithMember. + verify(conversationStore).updateIfState(gc, GroupConversationState.IN_PROGRESS); + // New feature => must be observable (AGENTS.md). + assertEquals(1.0, meterRegistry.counter("eddi_group_followup_count").count()); + } + + @Test + void followUp_unknownMember_throwsAndDoesNotCallAgent() throws Exception { + var gc = completedGc(); + when(conversationStore.read("gc-1")).thenReturn(gc); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.COMPLETED, GroupConversationState.IN_PROGRESS)).thenReturn(true); + + // Specific subtype so REST can map an unknown member to 404 (not a 409 + // conflict). + assertThrows(ai.labs.eddi.engine.api.IGroupConversationService.GroupMemberNotFoundException.class, + () -> service.followUpWithMember("gc-1", "ghost", "hello")); + verify(conversationService, never()) + .say(any(), any(), any(), any(), any(), any(), any(), anyBoolean(), any()); + } + + @Test + void followUp_agentCallFails_throwsGroupExecutionException() throws Exception { + var gc = completedGc(); + when(conversationStore.read("gc-1")).thenReturn(gc); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.COMPLETED, GroupConversationState.IN_PROGRESS)).thenReturn(true); + // The agent call itself blows up (provider error) β€” an upstream failure, which + // REST must map to 5xx, not a 409 "conflict, retry". + doThrow(new RuntimeException("provider 500")).when(conversationService) + .say(any(), eq("agentA"), any(), any(), any(), any(), any(), anyBoolean(), any()); + + assertThrows(ai.labs.eddi.engine.api.IGroupConversationService.GroupExecutionException.class, + () -> service.followUpWithMember("gc-1", "agentA", "hello")); + } + + @Test + void followUp_notCompleted_throwsAndDoesNotCallAgent() throws Exception { + var gc = completedGc(); + gc.setState(GroupConversationState.IN_PROGRESS); + when(conversationStore.read("gc-1")).thenReturn(gc); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.COMPLETED, GroupConversationState.IN_PROGRESS)).thenReturn(false); + + assertThrows(GroupDiscussionException.class, + () -> service.followUpWithMember("gc-1", "Alice", "hello")); + verify(conversationService, never()) + .say(any(), any(), any(), any(), any(), any(), any(), anyBoolean(), any()); + } + + @Test + void followUp_concurrentOperation_rejected() throws Exception { + operationsInProgress().add("gc-1"); + + assertThrows(GroupDiscussionException.class, + () -> service.followUpWithMember("gc-1", "Alice", "hello")); + verify(conversationStore, never()).compareAndSetState(any(), any(), any()); + } + + @Test + void followUp_agentCallFails_restoresCompletedState() throws Exception { + var gc = completedGc(); + when(conversationStore.read("gc-1")).thenReturn(gc); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.COMPLETED, GroupConversationState.IN_PROGRESS)).thenReturn(true); + doThrow(new RuntimeException("agent boom")).when(conversationService) + .say(any(), eq("agentA"), eq("convA"), any(), any(), any(), any(), anyBoolean(), any()); + + assertThrows(GroupDiscussionException.class, + () -> service.followUpWithMember("gc-1", "Alice", "hello")); + // finally-block must restore COMPLETED so the conversation stays usable + verify(conversationStore).compareAndSetState("gc-1", + GroupConversationState.IN_PROGRESS, GroupConversationState.COMPLETED); + } + } + + @Nested + class ContinueDiscussionTests { + + @Test + void continue_notCompleted_throws() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setState(GroupConversationState.IN_PROGRESS); + when(conversationStore.read("gc-1")).thenReturn(gc); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.COMPLETED, GroupConversationState.IN_PROGRESS)).thenReturn(false); + + assertThrows(GroupDiscussionException.class, + () -> service.continueDiscussion("gc-1", "next", null)); + } + + @Test + void continue_concurrentOperation_rejected() throws Exception { + operationsInProgress().add("gc-1"); + + assertThrows(GroupDiscussionException.class, + () -> service.continueDiscussion("gc-1", "q", null)); + verify(conversationStore, never()).compareAndSetState(any(), any(), any()); + } + + @Test + void continue_incrementsRoundAndAppendsQuestion() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setGroupId("group-1"); + gc.setState(GroupConversationState.COMPLETED); + gc.setRound(1); + // Model the real sequence: the pre-CAS read sees COMPLETED, the post-CAS + // re-read sees IN_PROGRESS. Without this the config-load failure would skip + // failConversation() and the FAILED recovery path would never be exercised. + var inProgress = new GroupConversation(); + inProgress.setId("gc-1"); + inProgress.setGroupId("group-1"); + inProgress.setState(GroupConversationState.IN_PROGRESS); + inProgress.setRound(1); + when(conversationStore.read("gc-1")).thenReturn(gc, inProgress); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.COMPLETED, GroupConversationState.IN_PROGRESS)).thenReturn(true); + // Fail fast right after the round/question mutation: group config not found. + when(groupStore.getCurrentResourceId("group-1")).thenReturn(null); + + assertThrows(IResourceStore.ResourceNotFoundException.class, + () -> service.continueDiscussion("gc-1", "round two question", null)); + + assertEquals(2, inProgress.getRound()); + var transcript = inProgress.getTranscript(); + assertFalse(transcript.isEmpty()); + var last = transcript.get(transcript.size() - 1); + assertEquals(TranscriptEntryType.QUESTION, last.type()); + assertEquals("round two question", last.content()); + // The round/question mutation is persisted with a CAS on IN_PROGRESS so a + // racing cancel/close cannot be resurrected by an unconditional write. + // (failConversation below also CASes on IN_PROGRESS, hence atLeastOnce.) + verify(conversationStore, atLeastOnce()).updateIfState(inProgress, GroupConversationState.IN_PROGRESS); + verify(conversationStore, never()).update(inProgress); + // The round was committed, so the continuation is counted (AGENTS.md: new + // features must be observable). + assertEquals(1.0, meterRegistry.counter("eddi_group_continue_count").count()); + // Config load failed after the transition β€” the conversation must be FAILED, + // not left stranded IN_PROGRESS. + assertEquals(GroupConversationState.FAILED, inProgress.getState()); + } + + @Test + void continue_concurrentTerminalTransition_isNotResurrected() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setGroupId("group-1"); + gc.setState(GroupConversationState.COMPLETED); + var inProgress = new GroupConversation(); + inProgress.setId("gc-1"); + inProgress.setGroupId("group-1"); + inProgress.setState(GroupConversationState.IN_PROGRESS); + when(conversationStore.read("gc-1")).thenReturn(gc, inProgress); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.COMPLETED, GroupConversationState.IN_PROGRESS)).thenReturn(true); + // A cancel/close/delete on another node wins the window after our CAS. + doThrow(new IResourceStore.ResourceModifiedException("terminal elsewhere")) + .when(conversationStore).updateIfState(inProgress, GroupConversationState.IN_PROGRESS); + + assertThrows(GroupDiscussionException.class, + () -> service.continueDiscussion("gc-1", "round two", null)); + + // Must NOT fall through to running the discussion on a terminal conversation. + verify(groupStore, never()).getCurrentResourceId(any()); + } + } + + /** Reflective access to the private control-token map. */ + @SuppressWarnings("unchecked") + private Map activeTokens() throws Exception { + var field = GroupConversationService.class.getDeclaredField("activeTokens"); + field.setAccessible(true); + return (Map) field.get(service); + } + + /** + * Regression tests for the cross-feature defects found reviewing the + * origin/main merge (continue/follow-up/close vs HITL pause/cancel/resume). + */ + @Nested + class MergeReviewFixTests { + + private GroupConversation completedGc() { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setGroupId("group-1"); + gc.setState(GroupConversationState.COMPLETED); + gc.setOriginalQuestion("round one"); + gc.setRound(1); + return gc; + } + + /** + * Arms the CAS and fails fast at config load, after the round/question + * mutation. + */ + private GroupConversation armContinue() throws Exception { + var gc = completedGc(); + when(conversationStore.read("gc-1")).thenReturn(gc); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.COMPLETED, GroupConversationState.IN_PROGRESS)).thenReturn(true); + return gc; + } + + @Test + void continue_persistsResumeQuestion_andLeavesOriginalQuestionAlone() throws Exception { + var gc = armContinue(); + when(groupStore.getCurrentResourceId("group-1")).thenReturn(null); + + assertThrows(IResourceStore.ResourceNotFoundException.class, + () -> service.continueDiscussion("gc-1", "round two", null)); + + // resumeDiscussion reads resumeQuestion β€” a paused continuation must resume + // with + // THIS question, while originalQuestion (the UI title) stays as round one. + assertEquals("round two", gc.getResumeQuestion()); + assertEquals("round one", gc.getOriginalQuestion()); + } + + @Test + void continue_preRegistersControlToken_andRemovesItWhenExecutionNeverStarts() throws Exception { + armContinue(); + var tokenPresentInWindow = new AtomicBoolean(false); + when(groupStore.getCurrentResourceId("group-1")).thenAnswer(inv -> { + tokenPresentInWindow.set(activeTokens().containsKey("gc-1")); + return null; // -> ResourceNotFoundException, so executeDiscussion is never reached + }); + + assertThrows(IResourceStore.ResourceNotFoundException.class, + () -> service.continueDiscussion("gc-1", "q", null)); + + assertTrue(tokenPresentInWindow.get(), + "a cancel racing the CAS->execute window must find a signalable token"); + assertFalse(activeTokens().containsKey("gc-1"), + "the pre-registered token must not leak when execution never started"); + } + + @Test + void followUp_blankInput_rejectedBeforeAnyStateChange() { + assertThrows(IllegalArgumentException.class, + () -> service.followUpWithMember("gc-1", " ", "question")); + assertThrows(IllegalArgumentException.class, + () -> service.followUpWithMember("gc-1", "agentA", null)); + verifyNoInteractions(conversationStore); + } + + @Test + void continue_blankQuestion_rejectedBeforeAnyStateChange() { + assertThrows(IllegalArgumentException.class, + () -> service.continueDiscussion("gc-1", " ", null)); + verifyNoInteractions(conversationStore); + } + + @Test + void delete_whileAnotherOperationRuns_isAConflictNotAStoreError() throws Exception { + operationsInProgress().add("gc-1"); + + // GroupDiscussionException -> REST 409; a ResourceStoreException would be a + // 500. + assertThrows(GroupDiscussionException.class, + () -> service.deleteGroupConversation("gc-1")); + } + + @Test + void cancel_closedConversation_isATerminalNoOp() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setState(GroupConversationState.CLOSED); + when(conversationStore.read("gc-1")).thenReturn(gc); + + boolean cancelled = service.cancelDiscussion("gc-1", ControlSignal.CANCEL_GRACEFUL); + + assertFalse(cancelled, "CLOSED is irreversible β€” a cancel must not un-terminalize it"); + verify(conversationStore, never()).compareAndSetState(any(), + eq(GroupConversationState.CLOSED), eq(GroupConversationState.CANCELLED)); + } + + @Test + void persistedTerminalOverride_stopsTheLegAndAlignsStateForEveryTerminalState() throws Exception { + var method = GroupConversationService.class.getDeclaredMethod( + "persistedTerminalOverride", GroupConversation.class, GroupDiscussionEventListener.class); + method.setAccessible(true); + + for (var terminal : List.of(GroupConversationState.CANCELLED, GroupConversationState.FAILED, + GroupConversationState.COMPLETED, GroupConversationState.CLOSED)) { + var running = new GroupConversation(); + running.setId("gc-1"); + running.setState(GroupConversationState.IN_PROGRESS); + + var persisted = new GroupConversation(); + persisted.setId("gc-1"); + persisted.setState(terminal); + when(conversationStore.read("gc-1")).thenReturn(persisted); + + boolean stop = (boolean) method.invoke(service, running, null); + + assertTrue(stop, "the leg must stop when another writer moved the state to " + terminal); + // Without the alignment the finally would decide cleanup on a stale running + // state (leaking ephemeral agents); CLOSED additionally prevents the leg's + // whole-document write from resurrecting a closed conversation. + assertEquals(terminal, running.getState(), + "in-memory state must be aligned to the persisted terminal state: " + terminal); + } + } + } + + @Nested + class CloseGroupConversationTests { + + @Test + void close_completed_transitionsToClosedAndEndsMembers() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setGroupId("group-1"); + gc.setState(GroupConversationState.COMPLETED); + gc.setMemberConversationIds(new LinkedHashMap<>(Map.of("agentA", "convA", "agentB", "convB"))); + // close() re-reads the conversation to return the final state; the mocked CAS + // does not mutate gc, so model the post-transition read explicitly β€” otherwise + // asserting on the returned object would accept a stale, non-CLOSED response. + var closed = new GroupConversation(); + closed.setId("gc-1"); + closed.setGroupId("group-1"); + closed.setState(GroupConversationState.CLOSED); + when(conversationStore.read("gc-1")).thenReturn(gc, closed); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.COMPLETED, GroupConversationState.CLOSED)).thenReturn(true); + when(groupStore.getCurrentResourceId("group-1")).thenReturn(null); // ephemeral cleanup no-op + + GroupConversation result = service.closeGroupConversation("gc-1"); + + verify(conversationService).endConversation("convA"); + verify(conversationService).endConversation("convB"); + assertEquals(GroupConversationState.CLOSED, result.getState()); + assertEquals(1.0, meterRegistry.counter("eddi_group_close_count").count()); + } + + @Test + void close_failedState_usesFallbackCas() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setGroupId("group-1"); + gc.setState(GroupConversationState.FAILED); + when(conversationStore.read("gc-1")).thenReturn(gc); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.COMPLETED, GroupConversationState.CLOSED)).thenReturn(false); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.FAILED, GroupConversationState.CLOSED)).thenReturn(true); + when(groupStore.getCurrentResourceId("group-1")).thenReturn(null); + + assertDoesNotThrow(() -> service.closeGroupConversation("gc-1")); + verify(conversationStore).compareAndSetState("gc-1", + GroupConversationState.FAILED, GroupConversationState.CLOSED); + } + + @Test + void close_cancelledState_usesCancelledCas() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setGroupId("group-1"); + gc.setState(GroupConversationState.CANCELLED); + when(conversationStore.read("gc-1")).thenReturn(gc); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.COMPLETED, GroupConversationState.CLOSED)).thenReturn(false); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.FAILED, GroupConversationState.CLOSED)).thenReturn(false); + when(conversationStore.compareAndSetState("gc-1", + GroupConversationState.CANCELLED, GroupConversationState.CLOSED)).thenReturn(true); + when(groupStore.getCurrentResourceId("group-1")).thenReturn(null); + + assertDoesNotThrow(() -> service.closeGroupConversation("gc-1")); + verify(conversationStore).compareAndSetState("gc-1", + GroupConversationState.CANCELLED, GroupConversationState.CLOSED); + } + + @Test + void close_wrongState_throwsGroupDiscussionException() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setState(GroupConversationState.IN_PROGRESS); + when(conversationStore.read("gc-1")).thenReturn(gc); + when(conversationStore.compareAndSetState(eq("gc-1"), any(), eq(GroupConversationState.CLOSED))) + .thenReturn(false); + + assertThrows(GroupDiscussionException.class, + () -> service.closeGroupConversation("gc-1")); + } + + @Test + void close_concurrentOperation_rejected() throws Exception { + operationsInProgress().add("gc-1"); + + assertThrows(GroupDiscussionException.class, + () -> service.closeGroupConversation("gc-1")); + verify(conversationStore, never()).compareAndSetState(any(), any(), any()); + } } } diff --git a/src/test/java/ai/labs/eddi/engine/internal/RestGroupConversationExtendedTest.java b/src/test/java/ai/labs/eddi/engine/internal/RestGroupConversationExtendedTest.java index 61f2425011..fe72d41e80 100644 --- a/src/test/java/ai/labs/eddi/engine/internal/RestGroupConversationExtendedTest.java +++ b/src/test/java/ai/labs/eddi/engine/internal/RestGroupConversationExtendedTest.java @@ -12,10 +12,12 @@ import ai.labs.eddi.engine.api.IRestGroupConversation.DiscussRequest; import ai.labs.eddi.engine.lifecycle.GroupConversationEventSink; import ai.labs.eddi.engine.security.OwnershipValidator; +import io.quarkus.security.ForbiddenException; import io.quarkus.security.identity.SecurityIdentity; import jakarta.ws.rs.sse.OutboundSseEvent; import jakarta.ws.rs.sse.Sse; import jakarta.ws.rs.sse.SseEventSink; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; @@ -71,6 +73,15 @@ void setUp() { when(eventBuilder.build()).thenReturn(sseEvent); } + @AfterEach + void tearDown() { + // Each test builds a fresh RestGroupConversation whose virtual-thread executor + // is otherwise only closed by the CDI @PreDestroy β€” never invoked in a plain + // unit test. Shut it down here so a full suite run does not accumulate + // un-terminated executors. + restGroupConversation.shutdown(); + } + // Helper factory methods for events matching actual record signatures private GroupConversationEventSink.GroupStartEvent groupStartEvent() { return new GroupConversationEventSink.GroupStartEvent( @@ -346,4 +357,157 @@ void closeQuietlyNoOpWhenAlreadyClosed() throws Exception { verify(eventSink, never()).close(); } } + + // ─── continue/stream endpoint ─────────────────────────── + @Nested + @DisplayName("continueDiscussionStreaming") + class ContinueDiscussionStreaming { + + private GroupConversation gcInGroup(String groupId) { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setGroupId(groupId); + gc.setUserId("user-1"); + return gc; + } + + @Test + @DisplayName("group mismatch sends group_error, closes, and does not delegate") + void groupMismatch_sendsErrorAndCloses() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("other-group")); + when(jsonSerialization.serialize(any())).thenReturn("{\"error\":\"not found\"}"); + + restGroupConversation.continueDiscussionStreaming("group-1", "gc-1", + new DiscussRequest("q", "user-1"), eventSink, sse); + + verify(eventSink).send(any(OutboundSseEvent.class)); + verify(eventSink).close(); + verify(groupService, never()).continueDiscussion(any(), any(), any()); + } + + @Test + @DisplayName("ForbiddenException is rethrown (maps to 403), not converted to an SSE error") + void forbidden_isRethrown() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + doThrow(new ForbiddenException("denied")) + .when(ownershipValidator).requireOwnerOrAdmin(any(), eq("user-1"), anyString()); + + assertThrows(ForbiddenException.class, + () -> restGroupConversation.continueDiscussionStreaming("group-1", "gc-1", + new DiscussRequest("q", "user-1"), eventSink, sse)); + + verify(eventSink, never()).send(any(OutboundSseEvent.class)); + verify(eventSink, never()).close(); + verify(groupService, never()).continueDiscussion(any(), any(), any()); + } + + @Test + @DisplayName("happy path delegates continue to the background executor") + void success_delegatesToExecutor() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.continueDiscussion(eq("gc-1"), eq("q"), any())).thenReturn(gcInGroup("group-1")); + when(jsonSerialization.serialize(any())).thenReturn("{}"); + + restGroupConversation.continueDiscussionStreaming("group-1", "gc-1", + new DiscussRequest("q", "user-1"), eventSink, sse); + + // continue runs on a background virtual thread β€” wait for the invocation + verify(groupService, timeout(2000)).continueDiscussion(eq("gc-1"), eq("q"), any()); + } + + @Test + @DisplayName("executor task failure routes the error to the SSE sink") + void executorTaskFailure_sendsErrorAndCloses() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.continueDiscussion(eq("gc-1"), eq("q"), any())) + .thenThrow(new IGroupConversationService.GroupDiscussionException("boom")); + when(jsonSerialization.serialize(any())).thenReturn("{\"error\":\"boom\"}"); + + restGroupConversation.continueDiscussionStreaming("group-1", "gc-1", + new DiscussRequest("q", "user-1"), eventSink, sse); + + // onGroupError runs on the background thread β€” wait for the close + verify(eventSink, timeout(2000)).close(); + verify(eventSink, atLeastOnce()).send(any(OutboundSseEvent.class)); + } + + @Test + @DisplayName("continuation streams HITL pause + cancel events (shared listener) instead of hanging the client") + void continueListenerForwardsHitlAndCancelEvents() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.continueDiscussion(eq("gc-1"), eq("q"), any())).thenReturn(gcInGroup("group-1")); + when(jsonSerialization.serialize(any())).thenReturn("{}"); + + restGroupConversation.continueDiscussionStreaming("group-1", "gc-1", + new DiscussRequest("q", "user-1"), eventSink, sse); + + var captor = ArgumentCaptor.forClass(GroupDiscussionEventListener.class); + verify(groupService, timeout(2000)).continueDiscussion(eq("gc-1"), eq("q"), captor.capture()); + var listener = captor.getValue(); + + // The old hand-rolled inline listener had no HITL overrides, so a continuation + // that paused for approval emitted NOTHING and the SSE client hung forever. + listener.onHitlPause(new GroupConversationEventSink.HitlPauseEvent(0, "Debate", "needs approval", "PHASE")); + + verify(eventSink, atLeastOnce()).send(any(OutboundSseEvent.class)); + verify(eventSink).close(); + } + + @Test + @DisplayName("continuation streams the cancelled event and closes the sink") + void continueListenerForwardsCancelledEvent() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.continueDiscussion(eq("gc-1"), eq("q"), any())).thenReturn(gcInGroup("group-1")); + when(jsonSerialization.serialize(any())).thenReturn("{}"); + + restGroupConversation.continueDiscussionStreaming("group-1", "gc-1", + new DiscussRequest("q", "user-1"), eventSink, sse); + + var captor = ArgumentCaptor.forClass(GroupDiscussionEventListener.class); + verify(groupService, timeout(2000)).continueDiscussion(eq("gc-1"), eq("q"), captor.capture()); + + // A cancelled continuation must terminate the stream β€” the old inline listener + // had no onCancelled override, so the client waited forever. + captor.getValue().onCancelled( + new GroupConversationEventSink.CancelledEvent("Discussion cancelled", "user-1")); + + verify(eventSink, atLeastOnce()).send(any(OutboundSseEvent.class)); + verify(eventSink).close(); + } + + @Test + @DisplayName("continue/stream rejects attachments with a terminal error, never silently drops them") + void continueStreaming_rejectsAttachments() throws Exception { + when(jsonSerialization.serialize(any())).thenReturn("{\"error\":\"attachments\"}"); + + restGroupConversation.continueDiscussionStreaming("group-1", "gc-1", + new DiscussRequest("q", "user-1", + List.of(new ai.labs.eddi.engine.api.IRestGroupConversation.AttachmentRef( + "image/png", "aGVsbG8=", null, "d.png"))), + eventSink, sse); + + verify(eventSink).send(any(OutboundSseEvent.class)); + verify(eventSink).close(); + verify(groupService, never()).continueDiscussion(any(), any(), any()); + } + + @Test + @DisplayName("continuation streams round_start (the shared listener keeps ours' event)") + void continueListenerForwardsRoundStart() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.continueDiscussion(eq("gc-1"), eq("q"), any())).thenReturn(gcInGroup("group-1")); + when(jsonSerialization.serialize(any())).thenReturn("{}"); + + restGroupConversation.continueDiscussionStreaming("group-1", "gc-1", + new DiscussRequest("q", "user-1"), eventSink, sse); + + var captor = ArgumentCaptor.forClass(GroupDiscussionEventListener.class); + verify(groupService, timeout(2000)).continueDiscussion(eq("gc-1"), eq("q"), captor.capture()); + + captor.getValue().onRoundStart( + new GroupConversationEventSink.RoundStartEvent("gc-1", 2, "q", 3)); + + verify(eventSink, atLeastOnce()).send(any(OutboundSseEvent.class)); + } + } } diff --git a/src/test/java/ai/labs/eddi/engine/internal/RestGroupConversationTest.java b/src/test/java/ai/labs/eddi/engine/internal/RestGroupConversationTest.java index c53f6860f1..badee418f3 100644 --- a/src/test/java/ai/labs/eddi/engine/internal/RestGroupConversationTest.java +++ b/src/test/java/ai/labs/eddi/engine/internal/RestGroupConversationTest.java @@ -10,6 +10,7 @@ import ai.labs.eddi.engine.api.IGroupConversationService; import ai.labs.eddi.engine.api.IRestGroupConversation.AttachmentRef; import ai.labs.eddi.engine.api.IRestGroupConversation.DiscussRequest; +import ai.labs.eddi.engine.api.IRestGroupConversation.FollowUpRequest; import ai.labs.eddi.engine.memory.model.Attachment; import ai.labs.eddi.engine.security.OwnershipValidator; import io.quarkus.security.ForbiddenException; @@ -345,4 +346,337 @@ void listGroupConversations_filtersForNonAdmin() throws Exception { assertEquals("gc-1", result.get(0).getId()); } } + + @Nested + @DisplayName("PostDiscussionOperations (followup / continue / close)") + class PostDiscussionOperations { + + private GroupConversation gcInGroup(String groupId) { + var gc = new GroupConversation(); + gc.setId("gc-1"); + gc.setGroupId(groupId); + gc.setUserId("user-1"); + return gc; + } + + @Test + @DisplayName("followUp β€” 404 when conversation belongs to a different group") + void followUp_groupMismatch_returns404() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("other-group")); + + Response response = restGroupConversation.followUpWithMember("group-1", "gc-1", + new FollowUpRequest("q", "agentA", "user-1")); + + assertEquals(404, response.getStatus()); + verify(groupService, never()).followUpWithMember(any(), any(), any()); + verify(ownershipValidator, never()).requireOwnerOrAdmin(any(), any(), any()); + } + + @Test + @DisplayName("followUp β€” 404 when conversation has no group set") + void followUp_nullGroup_returns404() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc-1"); // groupId left null + when(groupService.readGroupConversation("gc-1")).thenReturn(gc); + + Response response = restGroupConversation.followUpWithMember("group-1", "gc-1", + new FollowUpRequest("q", "agentA", "user-1")); + + assertEquals(404, response.getStatus()); + } + + @Test + @DisplayName("followUp β€” 409 on GroupDiscussionException (wrong state)") + void followUp_conflict_returns409() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.followUpWithMember("gc-1", "agentA", "q")) + .thenThrow(new IGroupConversationService.GroupDiscussionException("not COMPLETED")); + + Response response = restGroupConversation.followUpWithMember("group-1", "gc-1", + new FollowUpRequest("q", "agentA", "user-1")); + + assertEquals(409, response.getStatus()); + } + + @Test + @DisplayName("followUp β€” 404 (not 409) when the target agent is not a member") + void followUp_unknownMember_returns404() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.followUpWithMember("gc-1", "ghost", "q")) + .thenThrow(new IGroupConversationService.GroupMemberNotFoundException( + "The requested agent is not a member of this group conversation. Available members: {}")); + + Response response = restGroupConversation.followUpWithMember("group-1", "gc-1", + new FollowUpRequest("q", "ghost", "user-1")); + + // A typo'd agent is a client error, not a retryable conflict. + assertEquals(404, response.getStatus()); + assertFalse(String.valueOf(response.getEntity()).contains("ghost"), + "the caller-supplied targetAgentId must not be reflected"); + } + + @Test + @DisplayName("followUp β€” 502 (not 409) when the member agent call fails") + void followUp_agentFailure_returns502() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.followUpWithMember("gc-1", "agentA", "q")) + .thenThrow(new IGroupConversationService.GroupExecutionException( + "Failed to call agent 'agentA': provider 500")); + + Response response = restGroupConversation.followUpWithMember("group-1", "gc-1", + new FollowUpRequest("q", "agentA", "user-1")); + + // An upstream agent/model failure is a 5xx, not a "conflict β€” retry". + assertEquals(502, response.getStatus()); + } + + @Test + @DisplayName("followUp β€” 504 (not 409) when the member agent times out") + void followUp_timeout_returns504() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.followUpWithMember("gc-1", "agentA", "q")) + .thenThrow(new IGroupConversationService.GroupTimeoutException( + "Follow-up timed out for agent 'agentA'", new java.util.concurrent.TimeoutException())); + + Response response = restGroupConversation.followUpWithMember("group-1", "gc-1", + new FollowUpRequest("q", "agentA", "user-1")); + + assertEquals(504, response.getStatus()); + } + + @Test + @DisplayName("followUp β€” 200 and validates ownership before delegating") + void followUp_success_returns200() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.followUpWithMember("gc-1", "agentA", "q")).thenReturn(gcInGroup("group-1")); + + Response response = restGroupConversation.followUpWithMember("group-1", "gc-1", + new FollowUpRequest("q", "agentA", "user-1")); + + assertEquals(200, response.getStatus()); + verify(ownershipValidator).requireOwnerOrAdmin(identity, "user-1", "group conversation"); + } + + @Test + @DisplayName("continue β€” 404 when conversation belongs to a different group") + void continue_groupMismatch_returns404() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("other-group")); + + Response response = restGroupConversation.continueDiscussion("group-1", "gc-1", + new DiscussRequest("q", "user-1")); + + assertEquals(404, response.getStatus()); + verify(groupService, never()).continueDiscussion(any(), any(), any()); + } + + @Test + @DisplayName("continue β€” 200 on success") + void continue_success_returns200() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.continueDiscussion("gc-1", "q", null)).thenReturn(gcInGroup("group-1")); + + Response response = restGroupConversation.continueDiscussion("group-1", "gc-1", + new DiscussRequest("q", "user-1")); + + assertEquals(200, response.getStatus()); + } + + @Test + @DisplayName("continue β€” 502 (not 409) when a member agent fails mid-round") + void continue_agentFailure_returns502() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.continueDiscussion("gc-1", "q", null)) + .thenThrow(new IGroupConversationService.GroupExecutionException( + "Group discussion failed: provider 500")); + + Response response = restGroupConversation.continueDiscussion("group-1", "gc-1", + new DiscussRequest("q", "user-1")); + + assertEquals(502, response.getStatus()); + } + + @Test + @DisplayName("continue β€” 504 (not 409) when a member agent times out mid-round") + void continue_timeout_returns504() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.continueDiscussion("gc-1", "q", null)) + .thenThrow(new IGroupConversationService.GroupTimeoutException( + "timed out", new java.util.concurrent.TimeoutException())); + + Response response = restGroupConversation.continueDiscussion("group-1", "gc-1", + new DiscussRequest("q", "user-1")); + + assertEquals(504, response.getStatus()); + } + + @Test + @DisplayName("continue β€” still 409 for a genuine state/concurrency conflict") + void continue_stateConflict_returns409() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.continueDiscussion("gc-1", "q", null)) + .thenThrow(new IGroupConversationService.GroupDiscussionException("not COMPLETED")); + + Response response = restGroupConversation.continueDiscussion("group-1", "gc-1", + new DiscussRequest("q", "user-1")); + + assertEquals(409, response.getStatus()); + } + + @Test + @DisplayName("close β€” 404 when conversation belongs to a different group") + void close_groupMismatch_returns404() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("other-group")); + + Response response = restGroupConversation.closeGroupConversation("group-1", "gc-1"); + + assertEquals(404, response.getStatus()); + verify(groupService, never()).closeGroupConversation(any()); + } + + @Test + @DisplayName("close β€” 409 on GroupDiscussionException (wrong state / in progress)") + void close_conflict_returns409() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.closeGroupConversation("gc-1")) + .thenThrow(new IGroupConversationService.GroupDiscussionException("in progress")); + + Response response = restGroupConversation.closeGroupConversation("group-1", "gc-1"); + + assertEquals(409, response.getStatus()); + } + + @Test + @DisplayName("close β€” 500 on genuine store failure (not 409)") + void close_storeError_returns500() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.closeGroupConversation("gc-1")) + .thenThrow(new IResourceStore.ResourceStoreException("DB down")); + + // ResourceStoreException falls through to the generic mapper (500), not 409 + assertThrows(IResourceStore.ResourceStoreException.class, + () -> restGroupConversation.closeGroupConversation("group-1", "gc-1")); + } + + @Test + @DisplayName("close β€” 200 on success") + void close_success_returns200() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + when(groupService.closeGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + + Response response = restGroupConversation.closeGroupConversation("group-1", "gc-1"); + + assertEquals(200, response.getStatus()); + } + + // --- merge-review fixes --- + + @Test + @DisplayName("followUp β€” 400 (not 500) when targetAgentId is missing") + void followUp_missingTargetAgentId_returns400() { + Response response = restGroupConversation.followUpWithMember("group-1", "gc-1", + new FollowUpRequest("what did you mean?", null, "user-1")); + + assertEquals(400, response.getStatus()); + } + + @Test + @DisplayName("followUp β€” 400 when question is blank") + void followUp_blankQuestion_returns400() { + Response response = restGroupConversation.followUpWithMember("group-1", "gc-1", + new FollowUpRequest(" ", "agentA", "user-1")); + + assertEquals(400, response.getStatus()); + } + + @Test + @DisplayName("continue β€” 400 when question is blank") + void continue_blankQuestion_returns400() { + Response response = restGroupConversation.continueDiscussion("group-1", "gc-1", + new DiscussRequest("", "user-1")); + + assertEquals(400, response.getStatus()); + } + + @Test + @DisplayName("continue β€” attachments are rejected with 400, never silently dropped") + void continue_rejectsAttachments() throws Exception { + // A continuation cannot share NEW files: the fan-out grants/injects attachments + // only on a member's first-ever turn, and on a continuation every member + // conversation already exists. Reject explicitly instead of pretending. + var req = new DiscussRequest("round two", "user-1", + List.of(new AttachmentRef("image/png", "aGVsbG8=", null, "diagram.png"))); + + Response response = restGroupConversation.continueDiscussion("group-1", "gc-1", req); + + assertEquals(400, response.getStatus()); + verify(groupService, never()).continueDiscussion(any(), any(), any()); + } + + @Test + @DisplayName("delete β€” 409 (not 500) when another operation is in flight") + void delete_operationInProgress_returns409() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("group-1")); + doThrow(new IGroupConversationService.GroupDiscussionException( + "Cannot delete: another operation is already in progress for this group conversation")) + .when(groupService).deleteGroupConversation("gc-1"); + + Response response = restGroupConversation.deleteGroupConversation("group-1", "gc-1"); + + assertEquals(409, response.getStatus()); + // The raw exception text must not reach the client (CodeQL: information + // exposure through an error message) β€” the body is curated. + assertFalse(String.valueOf(response.getEntity()).contains("Cannot delete:"), + "the raw exception message must not be echoed to the caller"); + } + + @Test + @DisplayName("malformed id β€” the storage layer's raw payload is never reflected back") + void malformedId_doesNotReflectThePayload() throws Exception { + // Mongo's ObjectId parser puts the RAW caller string in its message. Echoing it + // (directly, or via the global IllegalArgumentException mapper) is an arbitrary + // reflected-value sink. + String payload = ""; + when(groupService.readGroupConversation(payload)) + .thenThrow(new IllegalArgumentException( + "invalid hexadecimal representation of an ObjectId: [" + payload + "]")); + + Response response = restGroupConversation.followUpWithMember("group-1", payload, + new FollowUpRequest("q", "Analyst", "user-1")); + + assertEquals(404, response.getStatus(), "a malformed id cannot name a conversation"); + assertFalse(String.valueOf(response.getEntity()).contains("script"), + "the caller-supplied payload must never be reflected back"); + assertFalse(String.valueOf(response.getEntity()).contains("ObjectId"), + "the storage layer's raw message must never be reflected back"); + } + + @Test + @DisplayName("group mismatch β€” the thrown 404's MESSAGE carries no groupId (read/delete surface it via the mapper)") + void groupMismatch_exceptionMessageIsCurated() throws Exception { + // readGroupConversation/deleteGroupConversation sneakyThrow this exception; the + // global ResourceNotFoundExceptionMapper echoes getLocalizedMessage() into the + // body. So the MESSAGE itself β€” not just the curated bodies of the endpoints + // that build their own Response β€” has to be free of caller input. + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("other-group")); + + var thrown = assertThrows(IResourceStore.ResourceNotFoundException.class, + () -> restGroupConversation.readGroupConversation("group-1", "gc-1")); + + assertFalse(String.valueOf(thrown.getMessage()).contains("group-1"), + "the exception message reaches the client via the mapper β€” it must not embed the groupId"); + } + + @Test + @DisplayName("group mismatch β€” 404 body does not reflect the caller-supplied groupId") + void groupMismatch_doesNotReflectGroupId() throws Exception { + when(groupService.readGroupConversation("gc-1")).thenReturn(gcInGroup("other-group")); + + Response response = restGroupConversation.followUpWithMember("group-1", "gc-1", + new FollowUpRequest("q", "Analyst", "user-1")); + + assertEquals(404, response.getStatus()); + assertFalse(String.valueOf(response.getEntity()).contains("group-1"), + "the caller-supplied groupId must not be reflected back (CodeQL reflected-value)"); + } + } } diff --git a/src/test/java/ai/labs/eddi/engine/mcp/McpGroupToolsTest.java b/src/test/java/ai/labs/eddi/engine/mcp/McpGroupToolsTest.java index 8b92b9b497..f5bee670a3 100644 --- a/src/test/java/ai/labs/eddi/engine/mcp/McpGroupToolsTest.java +++ b/src/test/java/ai/labs/eddi/engine/mcp/McpGroupToolsTest.java @@ -10,6 +10,8 @@ import ai.labs.eddi.configs.descriptors.model.DocumentDescriptor; import ai.labs.eddi.datastore.serialization.IJsonSerialization; import ai.labs.eddi.engine.api.IGroupConversationService; +import ai.labs.eddi.engine.security.OwnershipValidator; +import io.quarkus.security.identity.SecurityIdentity; import jakarta.ws.rs.core.Response; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -42,7 +44,10 @@ void setUp() throws Exception { var mockIdentity = mock(io.quarkus.security.identity.SecurityIdentity.class); lenient().when(mockIdentity.isAnonymous()).thenReturn(true); - tools = new McpGroupTools(groupStore, groupConversationService, jsonSerialization, mockIdentity, false); + // authorization disabled β€” OwnershipValidator's checks are no-ops, matching the + // pre-existing tests. Ownership enforcement is covered separately below. + tools = new McpGroupTools(groupStore, groupConversationService, jsonSerialization, mockIdentity, + new OwnershipValidator(false), false); } // --- describe_discussion_styles --- @@ -381,8 +386,20 @@ void startGroupDiscussion_handlesException() throws Exception { // --- delete_group_conversation --- + /** + * delete/followup/continue/close now load the conversation first to enforce the + * owner check (MCP parity with REST), so the read must be stubbed. + */ + private void stubConversation(String id) throws Exception { + GroupConversation gc = new GroupConversation(); + gc.setId(id); + when(groupConversationService.readGroupConversation(id)).thenReturn(gc); + } + @Test void deleteGroupConversation_success() throws Exception { + stubConversation("gc-del-1"); + tools.delete_group_conversation("gc-del-1"); verify(groupConversationService).deleteGroupConversation("gc-del-1"); @@ -390,6 +407,8 @@ void deleteGroupConversation_success() throws Exception { @Test void deleteGroupConversation_returnsConfirmation() throws Exception { + stubConversation("gc-del-1"); + String result = tools.delete_group_conversation("gc-del-1"); assertEquals("Deleted group conversation gc-del-1", result); @@ -397,6 +416,7 @@ void deleteGroupConversation_returnsConfirmation() throws Exception { @Test void deleteGroupConversation_handlesException() throws Exception { + stubConversation("gc-bad"); doThrow(new RuntimeException("Not found")).when(groupConversationService).deleteGroupConversation("gc-bad"); String result = tools.delete_group_conversation("gc-bad"); @@ -420,4 +440,250 @@ void startGroupDiscussion_doesNotHaveBlockingAnnotation() throws Exception { assertNull(method.getAnnotation(io.smallrye.common.annotation.Blocking.class), "start_group_discussion is async and should NOT have @Blocking"); } + + // --- ownership enforcement (MCP must match the REST surface) --- + + /** + * Builds the tools with auth ON, acting as {@code callerId} with the given + * roles. + */ + private McpGroupTools toolsAsUser(String callerId, String role) { + var identity = mock(SecurityIdentity.class); + lenient().when(identity.isAnonymous()).thenReturn(false); + var principal = mock(java.security.Principal.class); + lenient().when(principal.getName()).thenReturn(callerId); + lenient().when(identity.getPrincipal()).thenReturn(principal); + lenient().when(identity.hasRole(role)).thenReturn(true); + return new McpGroupTools(groupStore, groupConversationService, jsonSerialization, identity, + new OwnershipValidator(true), true); + } + + /** + * An admin caller: holds eddi-admin (plus the baseline roles the tools + * require). + */ + private McpGroupTools toolsAsAdmin(String callerId) { + var identity = mock(SecurityIdentity.class); + lenient().when(identity.isAnonymous()).thenReturn(false); + var principal = mock(java.security.Principal.class); + lenient().when(principal.getName()).thenReturn(callerId); + lenient().when(identity.getPrincipal()).thenReturn(principal); + lenient().when(identity.hasRole(anyString())).thenReturn(true); + return new McpGroupTools(groupStore, groupConversationService, jsonSerialization, identity, + new OwnershipValidator(true), true); + } + + @Test + void admin_mayActOnAnotherUsersConversation() throws Exception { + GroupConversation gc = ownedBy("alice"); + when(groupConversationService.followUpWithMember("gc1", "Analyst", "why?")).thenReturn(gc); + when(jsonSerialization.serialize(gc)).thenReturn("{\"id\":\"gc1\"}"); + + // The other half of requireOwnerOrAdmin: an admin is NOT the owner but must + // pass. + String result = toolsAsAdmin("root").followup_with_member("gc1", "Analyst", "why?"); + + assertFalse(result.contains("Access denied")); + verify(groupConversationService).followUpWithMember("gc1", "Analyst", "why?"); + } + + @Test + void admin_seesAllConversationsInTheGroupListing() throws Exception { + var mine = new GroupConversation(); + mine.setId("gc-mine"); + mine.setUserId("bob"); + var theirs = new GroupConversation(); + theirs.setId("gc-theirs"); + theirs.setUserId("alice"); + when(groupConversationService.listGroupConversations("g1", 0, 20)).thenReturn(List.of(mine, theirs)); + + toolsAsAdmin("root").list_group_conversations("g1", null, null); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); + verify(jsonSerialization).serialize(captor.capture()); + assertEquals(2, captor.getValue().size(), "the owner filter must exempt admins"); + } + + private GroupConversation ownedBy(String userId) throws Exception { + GroupConversation gc = new GroupConversation(); + gc.setId("gc1"); + gc.setUserId(userId); + when(groupConversationService.readGroupConversation("gc1")).thenReturn(gc); + return gc; + } + + @Test + void followupWithMember_deniedForNonOwner() throws Exception { + ownedBy("alice"); + + String result = toolsAsUser("bob", "eddi-viewer").followup_with_member("gc1", "Analyst", "why?"); + + assertTrue(result.contains("Access denied"), "a non-owner must not follow up on someone else's conversation"); + verify(groupConversationService, never()).followUpWithMember(any(), any(), any()); + } + + @Test + void continueGroupDiscussion_deniedForNonOwner() throws Exception { + ownedBy("alice"); + + String result = toolsAsUser("bob", "eddi-viewer").continue_group_discussion("gc1", "next?"); + + assertTrue(result.contains("Access denied"), "a non-owner must not continue someone else's conversation"); + verify(groupConversationService, never()).continueDiscussion(any(), any(), any()); + } + + @Test + void closeGroupConversation_deniedForNonOwner() throws Exception { + ownedBy("alice"); + + String result = toolsAsUser("bob", "eddi-editor").close_group_conversation("gc1"); + + assertTrue(result.contains("Access denied"), "a non-owner must not close someone else's conversation"); + verify(groupConversationService, never()).closeGroupConversation(any()); + } + + @Test + void readGroupConversation_deniedForNonOwner() throws Exception { + ownedBy("alice"); + + String result = toolsAsUser("bob", "eddi-viewer").read_group_conversation("gc1"); + + assertTrue(result.contains("Access denied"), "a non-owner must not read someone else's transcript"); + } + + @Test + void deleteGroupConversation_deniedForNonOwner() throws Exception { + ownedBy("alice"); + + String result = toolsAsUser("bob", "eddi-editor").delete_group_conversation("gc1"); + + assertTrue(result.contains("Access denied"), "a non-owner must not delete someone else's conversation"); + verify(groupConversationService, never()).deleteGroupConversation(any()); + } + + // --- curated error contract for the post-discussion mutation tools --- + // The generic catch(Exception) must NOT echo the raw exception text to the MCP + // caller (info exposure); it returns a stable curated message + INTERNAL code + // and + // logs the full throwable server-side. These pin that contract against + // regression. + + @Test + void followupWithMember_genericFailure_returnsCuratedErrorNotRawMessage() throws Exception { + stubConversation("gc1"); + when(groupConversationService.followUpWithMember(eq("gc1"), any(), any())) + .thenThrow(new RuntimeException("boom-internal-detail-42")); + + String result = tools.followup_with_member("gc1", "Analyst", "why?"); + + assertFalse(result.contains("boom-internal-detail-42"), + "the raw exception message must never reach the MCP caller"); + assertTrue(result.contains("Failed to process follow-up with member"), + "a stable curated message is returned instead"); + assertTrue(result.contains("\"errorCode\":\"INTERNAL\""), + "the curated error carries an INTERNAL errorCode"); + } + + @Test + void continueGroupDiscussion_genericFailure_returnsCuratedErrorNotRawMessage() throws Exception { + stubConversation("gc1"); + when(groupConversationService.continueDiscussion(eq("gc1"), any(), any())) + .thenThrow(new RuntimeException("boom-internal-detail-42")); + + String result = tools.continue_group_discussion("gc1", "next?"); + + assertFalse(result.contains("boom-internal-detail-42"), + "the raw exception message must never reach the MCP caller"); + assertTrue(result.contains("Failed to continue group discussion"), + "a stable curated message is returned instead"); + assertTrue(result.contains("\"errorCode\":\"INTERNAL\""), + "the curated error carries an INTERNAL errorCode"); + } + + @Test + void closeGroupConversation_genericFailure_returnsCuratedErrorNotRawMessage() throws Exception { + stubConversation("gc1"); + when(groupConversationService.closeGroupConversation("gc1")) + .thenThrow(new RuntimeException("boom-internal-detail-42")); + + String result = tools.close_group_conversation("gc1"); + + assertFalse(result.contains("boom-internal-detail-42"), + "the raw exception message must never reach the MCP caller"); + assertTrue(result.contains("Failed to close group conversation"), + "a stable curated message is returned instead"); + assertTrue(result.contains("\"errorCode\":\"INTERNAL\""), + "the curated error carries an INTERNAL errorCode"); + } + + @Test + void followupWithMember_allowedForOwner() throws Exception { + GroupConversation gc = ownedBy("alice"); + when(groupConversationService.followUpWithMember("gc1", "Analyst", "why?")).thenReturn(gc); + when(jsonSerialization.serialize(gc)).thenReturn("{\"id\":\"gc1\"}"); + + String result = toolsAsUser("alice", "eddi-viewer").followup_with_member("gc1", "Analyst", "why?"); + + assertEquals("{\"id\":\"gc1\"}", result); + verify(groupConversationService).followUpWithMember("gc1", "Analyst", "why?"); + } + + // --- owner resolution on creation (the gate must not lock out the creator) --- + + @Test + void startGroupDiscussion_recordsTheCallerAsOwner_notMcpClient() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc1"); + when(groupConversationService.startAndDiscussAsync(eq("g1"), eq("Q?"), eq("alice"), isNull())) + .thenReturn(gc); + + toolsAsUser("alice", "eddi-viewer").start_group_discussion("g1", "Q?", null); + + // If the conversation were owned by the literal "mcp-client", the ownership + // gate + // would then deny the creator on every follow-up read/continue/close. + verify(groupConversationService).startAndDiscussAsync("g1", "Q?", "alice", null); + } + + @Test + void startGroupDiscussion_cannotCreateAConversationOwnedByAnotherUser() throws Exception { + String result = toolsAsUser("bob", "eddi-viewer").start_group_discussion("g1", "Q?", "alice"); + + assertTrue(result.contains("Access denied"), "impersonating another owner must be rejected"); + verify(groupConversationService, never()).startAndDiscussAsync(any(), any(), any(), any()); + } + + @Test + void discussWithGroup_recordsTheCallerAsOwner() throws Exception { + var gc = new GroupConversation(); + gc.setId("gc1"); + when(groupConversationService.discuss("g1", "Q?", "alice", 0)).thenReturn(gc); + + toolsAsUser("alice", "eddi-viewer").discuss_with_group("g1", "Q?", null); + + verify(groupConversationService).discuss("g1", "Q?", "alice", 0); + } + + // --- listing must be owner-filtered, else the per-conversation gate is + // pointless --- + + @Test + @SuppressWarnings("unchecked") + void listGroupConversations_filtersToTheCallersOwnConversations() throws Exception { + var mine = new GroupConversation(); + mine.setId("gc-mine"); + mine.setUserId("bob"); + var theirs = new GroupConversation(); + theirs.setId("gc-theirs"); + theirs.setUserId("alice"); + when(groupConversationService.listGroupConversations("g1", 0, 20)).thenReturn(List.of(mine, theirs)); + + toolsAsUser("bob", "eddi-viewer").list_group_conversations("g1", null, null); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); + verify(jsonSerialization).serialize(captor.capture()); + assertEquals(1, captor.getValue().size(), "a non-owner must not see another user's transcript via list"); + assertEquals("gc-mine", captor.getValue().get(0).getId()); + } } diff --git a/src/test/java/ai/labs/eddi/modules/llm/tools/ToolExecutionServiceBranchTest.java b/src/test/java/ai/labs/eddi/modules/llm/tools/ToolExecutionServiceBranchTest.java index 40132f4b9d..ae8f017675 100644 --- a/src/test/java/ai/labs/eddi/modules/llm/tools/ToolExecutionServiceBranchTest.java +++ b/src/test/java/ai/labs/eddi/modules/llm/tools/ToolExecutionServiceBranchTest.java @@ -230,5 +230,50 @@ void executeMultipleInParallel() throws Exception { assertEquals("Hello, Alice!", r1); assertEquals("Hello, Bob!", r2); } + + @Test + @DisplayName("many tools sharing one trace must not corrupt it (thread-safety)") + void concurrentToolsShareTraceWithoutCorruption() throws Exception { + when(rateLimiter.tryAcquire("TestTool")).thenReturn(true); + when(cacheService.get(anyString(), anyString())).thenReturn(null); + when(costTracker.trackToolCall(anyString(), anyString())).thenReturn(0.0); + when(jsonSerialization.serialize(any())).thenReturn("[\"arg\"]"); + + TestTool tool = new TestTool(); + Method method = TestTool.class.getMethod("greet", String.class); + + // executeToolsParallel shares ONE ToolExecutionTrace across every task, and + // each task records into it. If the trace's recording is not synchronized, + // the ArrayList/HashMap inside it races: HashMap.computeIfAbsent throws + // ConcurrentModificationException (executeTool then returns + // "Error executing tool: ConcurrentModificationException"), or an ArrayList + // add is silently lost. One round of 2 tasks is flaky (tiny window); many + // rounds, each starting from a fresh empty trace whose map all tasks race to + // populate, makes the race reliably reproducible. + final int tasksPerRound = 32; + final int rounds = 50; + + for (int round = 0; round < rounds; round++) { + Object[] tools = new Object[tasksPerRound]; + Method[] methods = new Method[tasksPerRound]; + Object[][] args = new Object[tasksPerRound][]; + for (int i = 0; i < tasksPerRound; i++) { + tools[i] = tool; + methods[i] = method; + args[i] = new Object[]{"u" + i}; + } + + ToolExecutionTrace trace = new ToolExecutionTrace(); + CompletableFuture[] futures = service.executeToolsParallel(tools, methods, args, "conv-1", trace); + CompletableFuture.allOf(futures).join(); + + for (int i = 0; i < tasksPerRound; i++) { + assertEquals("Hello, u" + i + "!", futures[i].get(), + "round " + round + ": no tool call may fail on a shared-trace race"); + } + assertEquals(tasksPerRound, trace.getToolCalls().size(), + "round " + round + ": every call must be recorded exactly once (no lost updates)"); + } + } } }