diff --git a/FORK.md b/FORK.md index 51f0e8338dfb..455799f360ee 100644 --- a/FORK.md +++ b/FORK.md @@ -90,7 +90,7 @@ Against upstream pin `322f6544dfad0a3c8a0c8cbecf2c7f7874b14268`, the inventory h At every advance, review each new upstream tool and decide whether to admit it. A tool in a toolkit registered whole arrives exposed, and the case 4 test fails until its name is added; a tool in one of the five selected toolkits stays hidden until `upstreamCatalog.ts` names it. The 2026-10-17 advance admitted three (Jackson's decision that day): `t3_workflow_stop`, which `upstreamCatalog.ts` adds to `J5OrchestratorToolkit`, and the pull-request toolkit's `write_pull_request_guides` and `read_pull_request_guide`. Upstream's new `McpToolAccess.writesWithCapability` changes none of J5's declarations. The advance onto stable v0.1.3 brought one new tool, `t3_background_wait` (pingdotgg/t3code#24610: a Claude thread stays Working while background work it names runs), which `upstreamCatalog.ts` adds to `J5OrchestratorToolkit`. Jackson admitted it on 2026-10-27; upstream's Claude system prompt tells agents to call it. The advance onto stable v0.1.7 brought five new tools. `link_pull_requests` and `unlink_pull_requests`, in the pull-request toolkit, arrive exposed and are admitted as shipped. The three link tools, `t3_environment_links`, `t3_environment_link` and `t3_environment_unlink`, are added to `J5OrchestratorToolkit` (Jackson's decision 1 of 2026-11-05, linked environments as shipped) and are listed only while Settings › Labs turns linked environments on. With them `t3_thread_wait` and `t3_thread_interrupt` join `J5OrchestratorToolkit`, and `t3_thread_launch` joins `J5ProjectToolkit` behind `McpSchema.EnabledWhen` (case 111). About 32 admitted upstream tools gained an optional `environmentId`, which forwards the call to a linked machine; J5's re-declared transfer, organize and queue tools inherit it through upstream's parameter schemas, so their J5 rules run on the machine that receives the call. 3. The internal delivery-dedup contract proof: `apps/server/src/orchestration-v2/runtimeLayer.test.ts`, test `replays an internal thread send without injecting a second message`. The same file also carries the J5 Crew stop test `replaying a Crew stop does not dispatch a second real interrupt`, which replays upstream's `thread.stop` and proves a replayed Crew stop dispatches a seat's real interrupt only once; a rebase that drops either test is a regression. Upstream tests that build the V2 runtime provide `J5ThreadRegistrationLayer` (case 5); a new upstream test of that kind needs `Layer.provideMerge(J5ThreadRegistrationLayer)` too, as upstream's `layerQueueResumeDisabledInstanceTest` got at the 2026-10-17 advance. -4. The authenticated shared-toolkit integration proof: J5-owned `apps/server/src/j5/a2a/mcp/registration.test.ts`, test `production mcp layer lists worktree tools over http`. It asserts the exact production inventory, 88 tool names since the advance onto stable v0.1.7: the 84 of `j5/main` before it, plus `link_pull_requests`, `unlink_pull_requests`, `t3_thread_wait` and `t3_thread_interrupt` (case 2). The three link tools are admitted but not listed while linked environments are off, and `t3_thread_launch` is listed only to a link session, so none of the four is in the list; the test provides empty mocks of upstream's `PeerForwarding`, `PeerLinkRequests`, `PeerLinks` and `RemoteDelegation`, which they declare. The 84 were the 82 of stable v0.1.3 and J5's `j5_propose_persona` and `j5_read_persona`, added with persona drafts ([#938](https://github.com/Jacksondr5/j5code/pull/938)). Before stable v0.1.3 there were 99: the 79 from before the 2026-10-08 advance, the ten upstream tools admitted then (`html_preview`, `html_render`, `request_secret`, `preview_dialog`, `preview_hover`, `preview_select`, `preview_drag`, `preview_upload`, `watch_pull_request`, `unwatch_pull_request`; decision 7), the three admitted on 2026-10-11 (`t3_project_create`, `t3_project_update`, `t3_environment_preferences_update`; #519), less `t3_thread_send_attachments`, retired the same day, the three admitted on 2026-10-17 (`t3_workflow_stop`, `write_pull_request_guides`, `read_pull_request_guide`), J5's `j5_playbook_save`, added with the environment-wide playbook library ([#621](https://github.com/Jacksondr5/j5code/pull/621)), and the four queue tools admitted on 2026-10-24 (`t3_queue_edit`, `t3_queue_cancel`, `t3_queue_reorder`, `t3_queue_promote_to_steer`; #136). Upstream's merge of 18 tools into action tools (case 2) took out 22 names and brought in four (`t3_thread_transfer`, `t3_queue`, `t3_pending_request` and `preview_act`), and `t3_background_wait` is the fifth new name, admitted by Jackson on 2026-10-27 (case 2): 99 − 22 + 5 = 82. Upstream's registration asks for each tool's declared dependencies, so the test provides empty mocks of the J5 and upstream services those tools declare; listing tools never calls them. It also asserts the absence of the raw thread-send, launch and creation tools and `t3_project_delete` from an agent's list, the presence of `t3_thread_wait` and `t3_thread_interrupt`, and that a restricted session is refused `t3_thread_launch` and `t3_project_delete` when it calls them. Upstream deleted the file that held this test, `apps/server/src/mcp/toolkits/worktree/registration.test.ts`, at the 2026-10-24 advance (pingdotgg/t3code#22557), so the proof lives in J5's own file again. The upstream provider-adapter read-only-tool assertion derives its expectation from the upstream toolkit rather than the J5 production surface, so it is intentionally unchanged; this direct J5 exact-registration proof is the gate of record. Revisit that protected upstream read-only assertion only after an actual drift incident that this J5 proof fails to catch. +4. The authenticated shared-toolkit integration proof: J5-owned `apps/server/src/j5/a2a/mcp/registration.test.ts`, test `production mcp layer lists worktree tools over http`. It asserts the exact production inventory, 87 tool names since `j5_stop_agent` retired ([#955](https://github.com/Jacksondr5/j5code/issues/955)). The advance onto stable v0.1.7 made it 88: the 84 of `j5/main` before it, plus `link_pull_requests`, `unlink_pull_requests`, `t3_thread_wait` and `t3_thread_interrupt` (case 2). The three link tools are admitted but not listed while linked environments are off, and `t3_thread_launch` is listed only to a link session, so none of the four is in the list; the test provides empty mocks of upstream's `PeerForwarding`, `PeerLinkRequests`, `PeerLinks` and `RemoteDelegation`, which they declare. The 84 were the 82 of stable v0.1.3 and J5's `j5_propose_persona` and `j5_read_persona`, added with persona drafts ([#938](https://github.com/Jacksondr5/j5code/pull/938)). Before stable v0.1.3 there were 99: the 79 from before the 2026-10-08 advance, the ten upstream tools admitted then (`html_preview`, `html_render`, `request_secret`, `preview_dialog`, `preview_hover`, `preview_select`, `preview_drag`, `preview_upload`, `watch_pull_request`, `unwatch_pull_request`; decision 7), the three admitted on 2026-10-11 (`t3_project_create`, `t3_project_update`, `t3_environment_preferences_update`; #519), less `t3_thread_send_attachments`, retired the same day, the three admitted on 2026-10-17 (`t3_workflow_stop`, `write_pull_request_guides`, `read_pull_request_guide`), J5's `j5_playbook_save`, added with the environment-wide playbook library ([#621](https://github.com/Jacksondr5/j5code/pull/621)), and the four queue tools admitted on 2026-10-24 (`t3_queue_edit`, `t3_queue_cancel`, `t3_queue_reorder`, `t3_queue_promote_to_steer`; #136). Upstream's merge of 18 tools into action tools (case 2) took out 22 names and brought in four (`t3_thread_transfer`, `t3_queue`, `t3_pending_request` and `preview_act`), and `t3_background_wait` is the fifth new name, admitted by Jackson on 2026-10-27 (case 2): 99 − 22 + 5 = 82. Upstream's registration asks for each tool's declared dependencies, so the test provides empty mocks of the J5 and upstream services those tools declare; listing tools never calls them. It also asserts the absence of the raw thread-send, launch and creation tools and `t3_project_delete` from an agent's list, the presence of `t3_thread_wait` and `t3_thread_interrupt`, and that a restricted session is refused `t3_thread_launch` and `t3_project_delete` when it calls them. Upstream deleted the file that held this test, `apps/server/src/mcp/toolkits/worktree/registration.test.ts`, at the 2026-10-24 advance (pingdotgg/t3code#22557), so the proof lives in J5's own file again. The upstream provider-adapter read-only-tool assertion derives its expectation from the upstream toolkit rather than the J5 production surface, so it is intentionally unchanged; this direct J5 exact-registration proof is the gate of record. Revisit that protected upstream read-only assertion only after an actual drift incident that this J5 proof fails to catch. 5. Shared J5 server composition: `apps/server/src/server.ts` appends only `j5AuthenticatedRoutesLayer` to `layerMakeRoutes`, after upstream's `Ws.layer`, provides `J5ThreadRegistrationLayer` once to the V2 runtime (`RuntimeLayer.layerProduction`) and `J5A2AAuxiliaryLayer` once around the combined HTTP/MCP graph. Both transport registrations consume that shared graph and must never create nested J5 runtimes. The aggregate in case 9 owns all J5 authenticated route additions, including the human inbox. Upstream's `http.ts` carries no J5 edit; the desktop renderer origins it allows come from `httpCors.ts`, a branding site (`BRANDING.md`). 6. A4's visible human-inbox navigation append: in `apps/web/src/components/sidebar/SidebarChrome.tsx`, `SidebarChromeHeader` mounts the J5-owned `HumanInboxBell` and `FleetRailEntry` in a trailing control group, after the brand and optional environment pill, and `SidebarBrandMark` renders the J5 wordmark (`BRANDING.md`). Back behavior moved with upstream: `isSidebarUtilityPage` in `apps/web/src/components/sidebar/mainAppLocation.ts` names `/inbox`, `/fleet` and `/artifacts` beside upstream's utility pages (since stable v0.1.3 those are project pages and Pull Requests, because Settings and Usage open as modals over the thread), so none of them becomes the remembered Back target. Upstream's `SidebarBrandWidthProbe` measures the brand and not J5's two rail icons. The route files `routes/inbox.tsx` and `routes/fleet.tsx`, the pages, the bell, the rail entry, and their clients remain under J5-owned files (`j5/a2a`, `j5/fleet`); Settings, Pull Requests, Usage, and Back behavior are unchanged. 7. J5's user-message seam (the A2A timeline design of 2026-10-24, register D38, which replaced D16 and retired the A2A cards): `apps/web/src/components/chat/TimelineUserMessageRow.tsx` imports J5-owned `renderThreadA2ADelivery`, `useJ5UserMessagePresentation` and `J5MessageAuthorLine` from `apps/web/src/j5/a2a/ThreadA2ARenderer.tsx`. `UserMessageContent`, which upstream split out of `UserMessageRow` at v0.1.7 beneath its `ModelSwitchRow` wrapper, first calls `renderThreadA2ADelivery` with upstream's `formatDayAwareTimestamp` label and the participant labels, thread and markdown folder from `TimelineRowCtx` (case 24), and returns its answer when it is not null: group 4, one grey line through J5-owned `apps/web/src/j5/a2a/J5NoticeLine.tsx` for every J5 notice the classifier has a summary for and every Crew notice, plus a shared conversation's note (case 80). A notice nothing can read returns null and is upstream's row. Upstream's own platform messages never reach this row: `notificationTurnItem` makes them notification items, and `MessagesTimeline.logic.ts` draws `/compact` as a compaction row, so J5 leaves those rows alone. Group 5 reuses upstream's `AutomationMessageRow` instead of a J5 copy, because it already has the fold, find, copy, steer marker, status and revert: `UserMessageContent` also sends a message to it when J5-owned `j5PromptRow(row.message)` is not null; in the row, `j5Prompt ?? resolveUserMessagePresentation(row.message)` gives `text` and `scheduledTaskId`, `j5Prompt?.summary` leads `summary` ahead of upstream's `useScheduledTaskTitle`, and `j5Prompt?.label` and `j5Prompt?.icon` lead the heading, label and icon; and the row is `items-start` with `border border-border` in place of `items-end` and `bg-message text-message-foreground`, for upstream's automation runs too. A J5 prompt's pill is `w-full` while folded too, because the header caps its label at half the pill's width and J5's labels are long. In `UserTimelineRow`, `useJ5UserMessagePresentation(row.message)` replaces upstream's `resolveUserMessagePresentation`. It returns upstream's shape with the words without J5's envelope as `text`, and `"agent"` as the attribution of every participant who is not a person, so upstream's fold applies to agents, machine participants, outside agents, peers and spawn briefs; it adds `j5`, `literalContext`, `authorName`, `side` and `preview`. `resolvedContext` reads `userMessage.literalContext ?? resolveUserMessageContext(row.message)`, so a spawn brief's context is taken as written. The row is `items-start` when `userMessage.side === "left"`, as it already is for case 80's `sharedAuthor`. Case 80's author slot is ``: "You · via Inbox", another person's name with "· via Inbox", the participant identity line with its Exchange badge or tag, or else case 80's `SharedMessageAuthorLine`. In upstream's row action group, J5-owned `J5OpenSenderThread` (the sender's resolved scoped thread, so a spawn brief or a peer's message gets Open thread) takes the place of upstream's `senderThreadId` button for a message J5 read. `MessageAuthorHeading` reads `sharedAuthor?.name ?? userMessage.authorName ?? "You"`. `FoldedMessageHeader` renders its label span only when the label is not empty. For a message J5 read, the folded header's `label` is empty (the name is on the identity line), and the open header's is `userMessage.authorName ?? senderLabel`; its `summary` is `foldHeaderSummary` (`userMessage.preview ?? foldSummary`), empty while open when it is the body's first line (`foldSummary`), so an open message does not repeat it (#945). A Crew seat's brief keeps it, because its preview is the task and its body opens with the Crew's facts, and J5's prompts in the Automation row keep theirs (a playbook step's title, a question's situation), which the body does not open with. Without a summary the label takes the row's width and the summary span is not rendered. That is the shape of pingdotgg/t3code#29373, open on 2026-11-06, which drops the summary for upstream's own open rows; when it lands, take its lines and keep J5's label and `foldHeaderSummary`. Classification and every envelope parser are J5-owned `packages/client-runtime/src/j5/userMessagePresentation.ts` and `crewNotices.ts`, with the wording of J5's notices and prompts read in `platformMessages.ts`, so web and mobile share one parser, reached through the `./j5/user-message` and `./j5/crew-notices` exports this case appends to upstream-owned `packages/client-runtime/package.json`; `userMessagePresentation.test.ts` is the proof. Upstream's `MessagesTimeline.browser.test.tsx` mocks `useJ5UserMessagePresentation` with upstream's own presentation, because its tests cover upstream's row. Upstream's own thread sends, which carry no J5 envelope, are group 3 too: on the left, named from the sender thread's title. On a pin advance: if upstream reshapes the user row or its fold, keep the presentation swap, the context swap, the author slot, the side and the preview; if it splits the row again, keep J5's early return in the component below any wrapper that calls hooks, so hook order stays legal; if it reshapes the Automation row, keep it drawing J5's prompts, on the left without a fill. @@ -234,11 +234,11 @@ storage and names `j5_list_participants` and `schedule_task` as the shipped alte and the one replay-stable spawn turn carries committed `participant_id` plus project facts in platform context beside the byte-preserved spawner brief. -Agents stop an agent with upstream's `t3_thread_interrupt`, re-declared by J5 with one rule (register D2, [#955](https://github.com/Jacksondr5/j5code/issues/955)). `apps/server/src/j5/a2a/mcp/threadInterrupt.ts` declares it with `eitherBy`: when the caller is the Captain of the live Crew seat the target holds, the call is `actsAsCaller` and stops or interrupts with no mode check and no `DispatchModeLimit`; every other caller, outside agents included, gets upstream's `writesThreads` declaration and `OrchestratorMcpService.interruptThread`, so the target may not run with broader modes than the caller and the orchestrator checks again under the target's lock. A Captain's `stop: true` is upstream's `thread.stop`, sent through J5-owned `apps/server/src/j5/a2a/stopThread.ts` (Jackson's 2026-10-08 decision 11). It interrupts the running turn, holds the thread's queue and ends its pull request watches. Since the 2026-10-24 advance it also stops the thread's delegated tasks (pingdotgg/t3code#23886), but only when one of them has a thread here. So the Captain's path then calls `stopDelegatedTasks` with the same command, as upstream's handler does, which also ends delegates on a linked machine and lets a retry repeat a failed stop. Crew stop and Crew retirement call `stopThread` alone. Upstream's `stop: true` passes the caller's reason as given, so a Stop without one reads as the user's; J5 words every agent's Stop as upstream words an interrupt, with `agentStopReason` ("Stopped by an agent"), and a Captain's Crew stop passes `AGENT_STOP_REASON`; a person's Crew stop passes none. A held queue means an A2A delivery to a stopped agent waits until someone resumes the thread (case 26). Crew stop and Crew retirement stop each seat the same way. +Agents stop an agent with upstream's `t3_thread_interrupt`, re-declared by J5 with one rule (register D2, [#955](https://github.com/Jacksondr5/j5code/issues/955)). `apps/server/src/j5/a2a/mcp/threadInterrupt.ts` declares it with `eitherBy`: when the caller is the Captain of the live Crew seat the target holds, the call is `actsAsCaller` and stops or interrupts with no mode check and no `DispatchModeLimit`; every other caller, outside agents included, gets upstream's `writesThreads` declaration and `OrchestratorMcpService.interruptThread`, so the target may not run with broader modes than the caller and the orchestrator checks again under the target's lock. A Captain's `stop: true` is upstream's `thread.stop`, sent through J5-owned `apps/server/src/j5/a2a/stopThread.ts` (Jackson's 2026-10-08 decision 11). It interrupts the running turn, holds the thread's queue and ends its pull request watches. Since the 2026-10-24 advance it also stops the thread's delegated tasks (pingdotgg/t3code#23886), but only when one of them has a thread here. So `stopThread` then calls `stopDelegatedTasks` with the same command, as upstream's handler does, which also ends delegates on a linked machine and lets a retry repeat a failed stop ([#987](https://github.com/Jacksondr5/j5code/issues/987)). Upstream's `stop: true` passes the caller's reason as given, so a Stop without one reads as the user's; J5 words every agent's Stop as upstream words an interrupt, with `agentStopReason` ("Stopped by an agent"), and a Captain's Crew stop passes `AGENT_STOP_REASON`; a person's Crew stop passes none. A held queue means an A2A delivery to a stopped agent waits until someone resumes the thread (case 26). Crew stop and Crew retirement stop each seat the same way. `t3_thread_organize` replaces `archive_agent`. The J5 handler adds no archive authorization of its own: upstream's access check applies, which since the 2026-10-08 advance reaches any thread in the environment. Closure is performed once by the existing PR132 lifecycle reactor for every command door. The internal `ArchiveAgentService` remains for crew confirmation and interruption; only its MCP tool is retired. Crew-seat archive is refused by organize, and Captain archives retain the existing crew cascade. Ordinary non-crew agent archive adopts upstream self-archive and active-run semantics and has no token exchange. Human UI warnings remain. The obsolete standalone archive MCP handler and tool schemas are removed; archive/unarchive lifecycle, terminal notices and identity retention are covered through the replacement command path. -The composed HTTP registration test pins 99 tool names (case 4), rejects direct calls to the retired/raw tools and `t3_project_delete`, and keeps the original per-capability credential checks. The original J5 directory, spawn, stop and Exchange contracts remain in force. +The composed HTTP registration test pins the exact tool inventory (case 4), rejects direct calls to the retired/raw tools and `t3_project_delete`, and keeps the original per-capability credential checks. The original J5 directory, spawn, stop and Exchange contracts remain in force. These are per-instance Director/Jackson-authorized exceptions, not standing category permission. The earlier fork rebrand is separately complete at `0c0de1acefea00a34f9529bb97be32ff5056cfcc`; its rebase-critical boundary is recorded in `BRANDING.md:1-5,24-35`. The supporting fork setup plan (`artifacts/fork-setup-plan/index.md:8-12`) and its six T1-T6 ticket artifacts are internal project records and are not present in this repository. diff --git a/apps/server/src/j5/a2a/ArchiveAgentService.test.ts b/apps/server/src/j5/a2a/ArchiveAgentService.test.ts index 7dd0a633d8c0..07de1d7e93fe 100644 --- a/apps/server/src/j5/a2a/ArchiveAgentService.test.ts +++ b/apps/server/src/j5/a2a/ArchiveAgentService.test.ts @@ -14,7 +14,10 @@ import * as Layer from "effect/Layer"; import { ServerSecretStore } from "../../auth/ServerSecretStore.ts"; import { base64UrlEncode, signPayload } from "../../auth/utils.ts"; -import { OrchestratorProjectionError } from "../../orchestration-v2/Orchestrator.ts"; +import { + OrchestratorDispatchError, + OrchestratorProjectionError, +} from "../../orchestration-v2/Orchestrator.ts"; import { ProjectionStoreReadError, ProjectionStoreThreadNotFoundError, @@ -74,6 +77,7 @@ interface HarnessOptions { readonly runStatus?: OrchestrationV2RunStatus; readonly mismatchParticipantId?: ParticipantId; readonly failLifecycleOnce?: boolean; + readonly failDelegateStopOnce?: boolean; } const makeHarness = (options: HarnessOptions = {}) => { @@ -84,6 +88,7 @@ const makeHarness = (options: HarnessOptions = {}) => { let lifecycleCalls = 0; let archiveCalls = 0; let factReads = 0; + let delegateStops = 0; const owningExchangeProjectId = options.exchangeProjectId ?? ledgerProjectId; const order: Array = []; const events: Array = []; @@ -236,7 +241,18 @@ const makeHarness = (options: HarnessOptions = {}) => { } return Effect.succeed({ sequence: 1, storedEvents: [] }); }, - stopDelegatedTasks: () => Effect.void, + stopDelegatedTasks: (input) => { + delegateStops += 1; + if (options.failDelegateStopOnce === true && delegateStops === 1) + return Effect.fail( + new OrchestratorDispatchError({ + commandId: input.commandId, + commandType: "delegated_task.remote.complete", + }), + ); + order.push("delegates_stopped"); + return Effect.void; + }, }), Layer.mock(A2ALifecycleService)({ archiveParticipant: () => { @@ -321,6 +337,7 @@ it.effect("closes cross-project consequences before returning archived", () => { const state = harness.snapshot(); assert.deepStrictEqual(state.order, [ "interrupt_requested", + "delegates_stopped", "thread_archive_committed", "lifecycle_obligations_committed", ]); @@ -339,6 +356,29 @@ it.effect("closes cross-project consequences before returning archived", () => { }).pipe(Effect.provide(harness.layer)); }); +it.effect("stops the delegates of a seat its first stop left idle before archiving it", () => { + const harness = makeHarness({ runStatus: "running", failDelegateStopOnce: true }); + return Effect.gen(function* () { + const service = yield* ArchiveAgentService; + const refusal = yield* Effect.flip(service.archive(archiveInput())); + assert.instanceOf(refusal, ArchiveAgentConfirmationRequiredError); + if (!(refusal instanceof ArchiveAgentConfirmationRequiredError)) return; + // The Stop commits and ends the turn, then stopping the seat's delegates fails. + yield* Effect.flip(service.archive(archiveInput(refusal.confirmationToken))); + harness.settleRun(); + assert.isFalse(harness.snapshot().archived); + // The retry finds the seat idle, so it needs no token, and still stops its delegates first. + assert.equal(yield* service.archive(archiveInput()), "archived"); + assert.deepStrictEqual(harness.snapshot().order, [ + "interrupt_requested", + "interrupt_requested", + "delegates_stopped", + "thread_archive_committed", + "lifecycle_obligations_committed", + ]); + }).pipe(Effect.provide(harness.layer)); +}); + it.effect("rejects malformed and unknown-version tokens before reading target facts", () => { const malformedHarness = makeHarness({ openExchange: true }); const unknownHarness = makeHarness({ openExchange: true }); diff --git a/apps/server/src/j5/a2a/ArchiveAgentService.ts b/apps/server/src/j5/a2a/ArchiveAgentService.ts index 2e297a999267..da50e1a7f62c 100644 --- a/apps/server/src/j5/a2a/ArchiveAgentService.ts +++ b/apps/server/src/j5/a2a/ArchiveAgentService.ts @@ -590,14 +590,15 @@ export const layer = Layer.effect( } const expectedExchangeIds = before.facts.openExchanges.map((fact) => fact.exchangeId); - let interruptRequested = false; - if (before.facts.runningTurn !== null) { + const interruptRequested = before.facts.runningTurn !== null; + // Idle seats too: a retry after a failed delegate stop finds the seat idle, and its + // delegates on a linked machine still need stopping before it is archived. + if (before.projection.thread.archivedAt === null) { yield* stopThread(threadManagement, { commandId: input.interruptCommandId, threadId: input.target.threadId, reason: "Peer Agent archived as part of Crew retirement", }).pipe(Effect.mapError(operationError("requesting interruption of the active run"))); - interruptRequested = true; } if (before.projection.thread.archivedAt === null) { diff --git a/apps/server/src/j5/a2a/CrewProposalService.test.ts b/apps/server/src/j5/a2a/CrewProposalService.test.ts index caa594a7d767..7b02ffaf50d3 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.test.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.test.ts @@ -1947,6 +1947,7 @@ const playbookFixtureWithSettings = ( Effect.andThen(Ref.update(commands, (items) => [...items, command])), Effect.as({ events: [], effects: [] } as never), ), + stopDelegatedTasks: () => Effect.void, }), ), Layer.provideMerge( diff --git a/apps/server/src/j5/a2a/CrewStopService.test.ts b/apps/server/src/j5/a2a/CrewStopService.test.ts index 78b0426f882c..b99f5d1b1a4e 100644 --- a/apps/server/src/j5/a2a/CrewStopService.test.ts +++ b/apps/server/src/j5/a2a/CrewStopService.test.ts @@ -11,7 +11,10 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; -import { OrchestratorProjectionError } from "../../orchestration-v2/Orchestrator.ts"; +import { + OrchestratorDispatchError, + OrchestratorProjectionError, +} from "../../orchestration-v2/Orchestrator.ts"; import { ProjectionStoreReadError, ProjectionStoreThreadNotFoundError, @@ -93,6 +96,7 @@ it.effect("stops every live seat, for the Captain or a person, and nobody else", ], }); const interrupts = yield* Ref.make>([]); + const delegatedStopFails = yield* Ref.make(false); const layer = crewStopLayer.pipe( Layer.provideMerge( Layer.mock(ThreadManagementService)({ @@ -104,7 +108,21 @@ it.effect("stops every live seat, for the Captain or a person, and nobody else", ? `${command.type}:${command.threadId}:${command.commandId}:${command.reason ?? "no reason"}` : command.type, ]).pipe(Effect.as({ sequence: 1, storedEvents: [] })), - stopDelegatedTasks: () => Effect.void, + // A delegate on a linked machine has no thread here, so thread.stop leaves it to this. + stopDelegatedTasks: (input) => + Effect.flatMap(Ref.getAndSet(delegatedStopFails, false), (fails) => + fails + ? Effect.fail( + new OrchestratorDispatchError({ + commandId: input.commandId, + commandType: "delegated_task.remote.complete", + }), + ) + : Ref.update(interrupts, (items) => [ + ...items, + `delegates:${input.threadId}:${input.commandId}`, + ]), + ), }), ), // Every seat here has a thread, so no home is read. @@ -136,7 +154,9 @@ it.effect("stops every live seat, for the Captain or a person, and nobody else", // The Captain's Stop reads as an agent's; without a reason the timeline says "Stopped by user". assert.deepStrictEqual(yield* Ref.get(interrupts), [ `thread.stop:${builderThread}:stop:builder:Stopped by an agent`, + `delegates:${builderThread}:stop:builder`, `thread.stop:${criticThread}:stop:critic:Stopped by an agent`, + `delegates:${criticThread}:stop:critic`, ]); // A person stops the same Crew without a participant id, and the Stop stays theirs. @@ -147,9 +167,36 @@ it.effect("stops every live seat, for the Captain or a person, and nobody else", commandIds, }); assert.lengthOf(byHuman.members, 3); - assert.deepStrictEqual((yield* Ref.get(interrupts)).slice(2), [ + assert.deepStrictEqual((yield* Ref.get(interrupts)).slice(4), [ `thread.stop:${builderThread}:stop:builder:no reason`, + `delegates:${builderThread}:stop:builder`, `thread.stop:${criticThread}:stop:critic:no reason`, + `delegates:${criticThread}:stop:critic`, + ]); + + // A delegate stop that fails fails the Crew stop, and a retry under the same ids repeats it. + yield* Ref.set(delegatedStopFails, true); + const failed = yield* Effect.result( + service.stop({ + callerParticipantId: captain, + projectId, + crewInstanceId: "crew:stop", + commandIds, + }), + ); + assert.isTrue(failed._tag === "Failure"); + yield* service.stop({ + callerParticipantId: captain, + projectId, + crewInstanceId: "crew:stop", + commandIds, + }); + assert.deepStrictEqual((yield* Ref.get(interrupts)).slice(8), [ + `thread.stop:${builderThread}:stop:builder:Stopped by an agent`, + `thread.stop:${builderThread}:stop:builder:Stopped by an agent`, + `delegates:${builderThread}:stop:builder`, + `thread.stop:${criticThread}:stop:critic:Stopped by an agent`, + `delegates:${criticThread}:stop:critic`, ]); // A member, or any other agent, is refused and pointed at the Captain. diff --git a/apps/server/src/j5/a2a/mcp/threadInterrupt.ts b/apps/server/src/j5/a2a/mcp/threadInterrupt.ts index c2f3296dfb6e..6ce3c76d383f 100644 --- a/apps/server/src/j5/a2a/mcp/threadInterrupt.ts +++ b/apps/server/src/j5/a2a/mcp/threadInterrupt.ts @@ -59,17 +59,11 @@ const captainInterrupt = Effect.fn("j5.mcp.captainInterrupt")(function* ( }); const reason = agentStopReason(input.reason); if (input.stop === true) { - const stopCommandId = commandId("thread-stop"); const stopped = yield* stopThread(threads, { - commandId: stopCommandId, + commandId: commandId("thread-stop"), threadId: input.threadId, reason, }).pipe(Effect.mapError(failed)); - // As upstream does: thread.stop queues this only for delegates with a thread here, and a - // retry with the same clientRequestId repeats only the stops that failed. - yield* threads - .stopDelegatedTasks({ threadId: input.threadId, commandId: stopCommandId, reason }) - .pipe(Effect.mapError(failed)); // As upstream reads it: the run this Stop interrupted, from its own events. const interrupted = stopped.storedEvents.find( ({ event }) => diff --git a/apps/server/src/j5/a2a/stopThread.ts b/apps/server/src/j5/a2a/stopThread.ts index 34e7014c768b..29d81badc50c 100644 --- a/apps/server/src/j5/a2a/stopThread.ts +++ b/apps/server/src/j5/a2a/stopThread.ts @@ -16,13 +16,12 @@ export const agentStopReason = (reason: string | undefined) => reason === undefined ? AGENT_STOP_REASON : `${AGENT_STOP_REASON}: ${reason}`; /** - * Upstream's Stop for one thread, as its own senders issue it: `thread.stop` interrupts the - * running turn, holds the queue, ends pull request watches, and stops the thread's delegated - * tasks. Nothing to stop is an accepted no-op, and a retry with the same `commandId` repeats - * nothing. A Captain's `t3_thread_interrupt`, Crew stop and Crew retirement stop a thread this way. + * Upstream's Stop for one thread, as its MCP handler sends it. `thread.stop` stops delegated tasks + * only when one has a thread here; `stopDelegatedTasks` also ends those on a linked machine. A + * retry with the same `commandId` repeats only the stops that failed. */ -export const stopThread = ( - threads: Pick, +export const stopThread = Effect.fn("j5.a2a.stopThread")(function* ( + threads: Pick, input: { readonly commandId: CommandId; readonly threadId: ThreadId; @@ -31,10 +30,13 @@ export const stopThread = ( /** * The broadest modes the stopper may touch, for upstream to check under the thread's lock when * it applies the Stop. Absent for a person, and for a Captain stopping its own Crew's seat. - * It gates the thread named here and not its delegated tasks, which upstream stops after it. + * It gates the thread named here and not its delegated tasks. */ limit?: DispatchModes, -) => - threads +) { + const stopped = yield* threads .dispatch({ type: "thread.stop", ...input }) .pipe(Effect.provideService(DispatchModeLimit, limit)); + yield* threads.stopDelegatedTasks(input); + return stopped; +});