From 5cbe1db81c1c45e228c1236805925209e20a39f1 Mon Sep 17 00:00:00 2001 From: Bastian Huppertz <29781772+BastiHu@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:08:34 +0000 Subject: [PATCH 1/9] fix(j5): reject changed spawn replay requests Co-Authored-By: GPT-6.1-Sol Co-Authored-By: Claude Opus 5.5 --- FORK.md | 2 +- apps/server/src/j5/a2a/Migrations.test.ts | 4 +- apps/server/src/j5/a2a/Migrations.ts | 2 + .../src/j5/a2a/RequestReplayService.test.ts | 62 ++++ .../server/src/j5/a2a/RequestReplayService.ts | 95 ++++++ apps/server/src/j5/a2a/mcp/handlers.test.ts | 15 +- apps/server/src/j5/a2a/mcp/handlers.ts | 142 +++++--- apps/server/src/j5/a2a/mcp/tools.ts | 2 + .../j5/a2a/migrations/039_RequestReplay.ts | 14 + apps/server/src/j5/a2a/runtimeLayer.ts | 2 + apps/server/src/j5/a2a/spawnWorkspace.test.ts | 307 +++++++++++++++++- .../a2a/test-support/spawnWorkspaceFakes.ts | 4 + .../toolkits/worktree/registration.test.ts | 2 + 13 files changed, 595 insertions(+), 58 deletions(-) create mode 100644 apps/server/src/j5/a2a/RequestReplayService.test.ts create mode 100644 apps/server/src/j5/a2a/RequestReplayService.ts create mode 100644 apps/server/src/j5/a2a/migrations/039_RequestReplay.ts diff --git a/FORK.md b/FORK.md index 910ec17211fc6..bc936f105586a 100644 --- a/FORK.md +++ b/FORK.md @@ -327,7 +327,7 @@ migrations after upstream migrations. 47. Crew seats ask their Captain, not the person (#325, Jackson's 2026-09-26 decision). `packages/provider-core/src/server/ProviderAdapter.ts` (upstream moved the file into the package; case 60) appends an optional `crewSeat` to `ProviderAdapterV2RuntimePolicy` beside `agentPersonaInstructions`. J5-owned `makeAgentPersonaRuntimePolicyResolver` (`j5/agents/agentPersonaRuntime.ts`), the only resolver behind upstream `RuntimePolicy.ts`, asks J5-owned `makeCrewSeatLookup` (`j5/a2a/crewSeatRuntime.ts`) whether an `agent`/`mcp` thread holds a seat in a live Crew, through the Crew store built over the ambient SQL client. Without a SQL client nothing is a seat, and an unreadable store logs and answers no. `RuntimePolicy.ts` clamps the resolver's runtime mode with upstream's `providerRuntimeMode`, so a persona or seat never asks a provider for a mode it does not support. A seat's policy gets `crewSeat: true` and the ask-your-Captain rule appended to `agentPersonaInstructions`. On Claude that text follows the system prompt. On Codex it now travels as `j5_agent_persona` application context keys (Role library table), and whether Codex reads it after its Default-mode "ask the user directly" text was not verified at the 2026-10-08 advance. Two adapter appends consume the flag through J5-owned leaf `j5/a2a/crewSeatQuestions.ts`: `makeClaudeAdapterV2`'s `openQuery` spreads `j5ClaudeCrewSeatQueryOverrides(turnInput.runtimePolicy)` into `makeClaudeQueryOptions` (`disallowedTools: ["AskUserQuestion"]`, the SDK option that already existed but was never set), and `codexThreadRuntimeParams` spreads `j5CodexCrewSeatConfig(input.runtimePolicy)` into the thread `config` beside `mcp_servers` (dotted session overrides `features.default_mode_request_user_input = false` and `tools.experimental_request_user_input.enabled = false`, sent on thread start, resume, and fork only when the t3-code MCP session is attached). Cursor, Grok, OpenCode, Pi, ACP registry agents, Antigravity and Muse are not supported on seats: they get only the seat brief's instruction (`spawnFirstTurnText` in `j5/a2a/spawnIds.ts`). Captains and every other thread keep their native question tools. Tests: `j5/a2a/crewSeatRuntime.test.ts` (seat, Captain, person thread, persona seat, archived Crew, no SQL client), `j5/a2a/crewSeatQuestions.test.ts` (Codex config and developer-text order), and one `ClaudeAdapterV2.test.ts` case, "withholds AskUserQuestion only from a Crew seat", on the existing wake harness. On every rebase, verify both spreads survive and that upstream has not renamed the Codex switches or added another native question tool. -48. Cross-server peering's scope (Jackson's 2026-09-16 ruling: agents never address an environment; since 2026-10-02 agents see which server a participant lives on, by the server's own name, and still never manage one. Since the ledger re-keyed to projects, the wire names a project, not a Squadron). `packages/contracts/src/auth.ts` appends the `a2a:peer` literal as `AuthA2APeerScope` to `AuthEnvironmentScope`, outside `AuthStandardClientScopes` and `AuthGrantScope`, exactly as case 35 did for `a2a:send`: no pairing link, default session or grant carries it. Only J5-owned `PeerAdminService.issueCredential` mints it, bound by the session subject to one `peer:`; a caller reaches it with `access:write`, the `j5` CLI through the credential route in `apps/server/src/j5/a2a/PeerHttp.ts` and a client through the RPC `j5.peers.issueCredential` (case 64). The peer routes authorize on that scope plus a registered peer. `packages/contracts/src/environment.ts` adds one optional capability key, `j5PeerPoll`, beside case 34's two, and `apps/server/src/environment/ServerEnvironment.ts` (with its test) reports it as true; it says a server has peering poll mode and the reachability checks, and the peering dialog offers a setup only when both servers publish it. Everything else is add-beside: migrations 23–27 (26 indexes the peer route probes; 27 indexes received sender labels by receipt time for the client identity read) 30 (poll mode: the peer table rebuilt with its link mode, the store grants, and the delivery rows' hand-out stamp) and 32 (a stored roster snapshot's fields renamed for peer protocol 2, where the wire names a project and no longer a Squadron), `PeerRegistryService.ts`, `PeerInboundService.ts`, `PeerDirectory.ts`, `PeerStoreService.ts` (the poll route's long poll), `PeerPoller.ts` (one loop per peer this server polls, started with the A2A runtime), `peerDeliveryBody.ts`, `peerRoster.ts`, `peerReachability.ts` (the origins the `j5.peers.addresses` RPC offers; it imports upstream's host helpers from `startupAccess.ts` without changing them), `peerProtocol.ts` (the one peer protocol version compare, used in both directions; the version is 2 since the wire fields were renamed, so two peered servers update together and an older one is named as the one to update), `PeerHttp.ts` entering through the case 9 aggregate (the J5 route files share `httpSupport.ts` for authentication and error shapes), the `peer` group in J5-owned `apps/server/src/j5/cli/a2a.ts`, and the wire contracts in `packages/contracts/src/j5.ts`. The peer layers are wired once in J5-owned `runtimeLayer.ts`, which gives them their own `FetchHttpClient` and takes `EnvironmentAuth` and `ServerEnvironment` from the server context, so the shared A2A runtime's requirements grow by those two upstream services; `ServerEnvironment`'s descriptor label is the name a server reports to its peers. One upstream-adjacent test moves with it: `apps/server/src/mcp/toolkits/worktree/registration.test.ts` (already J5-modified for `j5_list_participants`) provides the empty `PeerDirectory` and a ledger stub for project titles, and expects `unread_peer_count` and `project_title`. The web side is one mount: `apps/web/src/components/settings/ConnectionsSettings.tsx` renders the J5-owned `PeerServersSettings` (from `apps/web/src/j5/peering/`) after the remote-environments section, gated by the page's `canWriteAccess` (`access:write`), and imports nothing else from J5. Upstream redefined `canManageLocalBackend` to its maintain scope, which is not what peering requires, so the mount moved to `canWriteAccess` (the implementer's call at the 2026-10-08 advance); the client's peer-list read lives in `packages/client-runtime/src/j5/http.ts`, its peering commands in `state.ts`, and the setup logic in the `peering.ts` subpath export, which adds one `./j5/peering` entry to that package's exports map beside the existing J5 subpaths. On every rebase, verify the literal is still outside the bundle, `AUTH_SCOPE_OPTIONS` is still typed `AuthGrantScope` (case 35), `runtimeLayer.ts` still provides the peer layers to the aggregate and the send service, and the single `PeerServersSettings` mount survives. `docs/README.md` links the peering guide, `docs/user/j5-peering.md`, beside the other J5 user guides. Development databases that ran an earlier cut of this stack, where these migrations carried ids 14–16 and later 18–21, are disposable test state with no upgrade path: recreate them with `pr-env.sh --fresh`. +48. Cross-server peering's scope (Jackson's 2026-09-16 ruling: agents never address an environment; since 2026-10-02 agents see which server a participant lives on, by the server's own name, and still never manage one. Since the ledger re-keyed to projects, the wire names a project, not a Squadron). `packages/contracts/src/auth.ts` appends the `a2a:peer` literal as `AuthA2APeerScope` to `AuthEnvironmentScope`, outside `AuthStandardClientScopes` and `AuthGrantScope`, exactly as case 35 did for `a2a:send`: no pairing link, default session or grant carries it. Only J5-owned `PeerAdminService.issueCredential` mints it, bound by the session subject to one `peer:`; a caller reaches it with `access:write`, the `j5` CLI through the credential route in `apps/server/src/j5/a2a/PeerHttp.ts` and a client through the RPC `j5.peers.issueCredential` (case 64). The peer routes authorize on that scope plus a registered peer. `packages/contracts/src/environment.ts` adds one optional capability key, `j5PeerPoll`, beside case 34's two, and `apps/server/src/environment/ServerEnvironment.ts` (with its test) reports it as true; it says a server has peering poll mode and the reachability checks, and the peering dialog offers a setup only when both servers publish it. Everything else is add-beside: migrations 23–27 (26 indexes the peer route probes; 27 indexes received sender labels by receipt time for the client identity read) 30 (poll mode: the peer table rebuilt with its link mode, the store grants, and the delivery rows' hand-out stamp) and 32 (a stored roster snapshot's fields renamed for peer protocol 2, where the wire names a project and no longer a Squadron), `PeerRegistryService.ts`, `PeerInboundService.ts`, `PeerDirectory.ts`, `PeerStoreService.ts` (the poll route's long poll), `PeerPoller.ts` (one loop per peer this server polls, started with the A2A runtime), `peerDeliveryBody.ts`, `peerRoster.ts`, `peerReachability.ts` (the origins the `j5.peers.addresses` RPC offers; it imports upstream's host helpers from `startupAccess.ts` without changing them), `peerProtocol.ts` (the one peer protocol version compare, used in both directions; the version is 2 since the wire fields were renamed, so two peered servers update together and an older one is named as the one to update), `PeerHttp.ts` entering through the case 9 aggregate (the J5 route files share `httpSupport.ts` for authentication and error shapes), the `peer` group in J5-owned `apps/server/src/j5/cli/a2a.ts`, and the wire contracts in `packages/contracts/src/j5.ts`. The peer layers are wired once in J5-owned `runtimeLayer.ts`, which gives them their own `FetchHttpClient` and takes `EnvironmentAuth` and `ServerEnvironment` from the server context, so the shared A2A runtime's requirements grow by those two upstream services; `ServerEnvironment`'s descriptor label is the name a server reports to its peers. One upstream-adjacent test moves with it: `apps/server/src/mcp/toolkits/worktree/registration.test.ts` (already J5-modified for `j5_list_participants`) provides the empty `PeerDirectory` and a ledger stub for project titles (and declares the `RequestReplayService` stub required by spawn replay checking), and expects `unread_peer_count` and `project_title`. The web side is one mount: `apps/web/src/components/settings/ConnectionsSettings.tsx` renders the J5-owned `PeerServersSettings` (from `apps/web/src/j5/peering/`) after the remote-environments section, gated by the page's `canWriteAccess` (`access:write`), and imports nothing else from J5. Upstream redefined `canManageLocalBackend` to its maintain scope, which is not what peering requires, so the mount moved to `canWriteAccess` (the implementer's call at the 2026-10-08 advance); the client's peer-list read lives in `packages/client-runtime/src/j5/http.ts`, its peering commands in `state.ts`, and the setup logic in the `peering.ts` subpath export, which adds one `./j5/peering` entry to that package's exports map beside the existing J5 subpaths. On every rebase, verify the literal is still outside the bundle, `AUTH_SCOPE_OPTIONS` is still typed `AuthGrantScope` (case 35), `runtimeLayer.ts` still provides the peer layers to the aggregate and the send service, and the single `PeerServersSettings` mount survives. `docs/README.md` links the peering guide, `docs/user/j5-peering.md`, beside the other J5 user guides. Development databases that ran an earlier cut of this stack, where these migrations carried ids 14–16 and later 18–21, are disposable test state with no upgrade path: recreate them with `pr-env.sh --fresh`. 49. Composer playbook picker (#314, #320). `/playbook ` (at message start) and `@playbook:` (anywhere) open one playbook picker fed by the J5 library route. These are client-side discovery and text-insertion seams; execution follows case 45's ordinary message expansion. - Detection: shared `composerTrigger.ts` and web `composer-logic.ts` append the `"slash-playbook"` kind and delegate line-start `/playbook ` detection to J5-owned `packages/shared/src/j5/playbookTrigger.ts`, exported through `packages/shared/package.json`; it matches the kebab-case name at the start of the message and stops before following text (#314). Upstream detects `/` per token since the 2026-10-17 advance, so a slash command can start mid-message; `/playbook ` spans a space, so J5 keeps a line-start check for it alone, ahead of upstream's token detection. The J5 `detectAgentMention` hook, already called at token level from both, returns the same kind for `@playbook:` tokens with the raw token after the prefix as the query (`packages/shared/src/j5/playbookMention.ts`; no upstream line). diff --git a/apps/server/src/j5/a2a/Migrations.test.ts b/apps/server/src/j5/a2a/Migrations.test.ts index 5700352e0bc00..56afec37b94ce 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -92,6 +92,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () { migration_id: 36, name: "OpenLinks" }, { migration_id: 37, name: "PersonNames" }, { migration_id: 38, name: "OpenLinkJoins" }, + { migration_id: 39, name: "RequestReplay" }, ]); assert.deepStrictEqual( migrationEntries.map(([id, name]) => [id, name]), @@ -134,6 +135,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () [36, "OpenLinks"], [37, "PersonNames"], [38, "OpenLinkJoins"], + [39, "RequestReplay"], ], ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), @@ -1382,7 +1384,7 @@ it.effect("recreates earlier-shaped crews tables when 14 runs over them", () => applied.map((row) => row.migration_id), [ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, + 36, 37, 38, 39, ], ); const memberColumns = yield* sql<{ readonly name: string }>` diff --git a/apps/server/src/j5/a2a/Migrations.ts b/apps/server/src/j5/a2a/Migrations.ts index c5c8b631aa6ad..ddcd01547b06e 100644 --- a/apps/server/src/j5/a2a/Migrations.ts +++ b/apps/server/src/j5/a2a/Migrations.ts @@ -39,6 +39,7 @@ import Migration0035 from "./migrations/035_GuestLinks.ts"; import Migration0036 from "./migrations/036_OpenLinks.ts"; import Migration0037 from "./migrations/037_PersonNames.ts"; import Migration0038 from "./migrations/038_OpenLinkJoins.ts"; +import Migration0039 from "./migrations/039_RequestReplay.ts"; export const J5_A2A_MIGRATIONS_TABLE = "j5_a2a_migrations"; @@ -88,6 +89,7 @@ export const migrationEntries = [ // 37 sits in the layer below 36 in the stack that introduced both; ids are never renumbered. [37, "PersonNames", Migration0037], [38, "OpenLinkJoins", Migration0038], + [39, "RequestReplay", Migration0039], ] as const; const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/j5/a2a/RequestReplayService.test.ts b/apps/server/src/j5/a2a/RequestReplayService.test.ts new file mode 100644 index 0000000000000..18ddf5fd1910c --- /dev/null +++ b/apps/server/src/j5/a2a/RequestReplayService.test.ts @@ -0,0 +1,62 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Result from "effect/Result"; +import * as SqlClient from "effect/sql/SqlClient"; +import migration from "./migrations/039_RequestReplay.ts"; +import { RequestReplayService, layer } from "./RequestReplayService.ts"; + +it.effect("persists the original request across database reopen and refuses changed reuse", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const filename = path.join(yield* fs.makeTempDirectoryScoped(), "replay.sqlite"); + const first = { + id: "spawn:1", + target: "agent:original", + request: { brief: "first", workspace: { type: "shared" }, omitted: undefined }, + legacy: false, + }; + yield* Effect.scoped( + Effect.gen(function* () { + yield* migration; + yield* (yield* RequestReplayService).bind(first); + }).pipe(Effect.provide(layer.pipe(Layer.provideMerge(NodeSqliteClient.layer({ filename }))))), + ); + yield* Effect.scoped( + Effect.gen(function* () { + const replay = yield* RequestReplayService; + yield* replay.bind({ + ...first, + legacy: true, + request: { workspace: { type: "shared" }, brief: "first" }, + }); + const changed = yield* replay + .bind({ ...first, target: "agent:changed", request: { brief: "different" } }) + .pipe(Effect.result); + assert.isTrue(Result.isFailure(changed)); + if (Result.isFailure(changed)) { + assert.equal(changed.failure._tag, "RequestReplayConflictError"); + assert.include(changed.failure.message, "agent:original"); + assert.include(changed.failure.message, "fresh client_request_id"); + } + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql<{ + readonly count: number; + }>`SELECT COUNT(*) AS count FROM j5_a2a_request_replay`; + assert.equal(rows[0]?.count, 1); + assert.isFalse(yield* replay.check("new-key", {})); + const legacy = yield* replay + .bind({ ...first, id: "legacy", legacy: true }) + .pipe(Effect.result); + assert.isTrue(Result.isFailure(legacy)); + if (Result.isFailure(legacy)) + assert.include(legacy.failure.message, "predates replay verification"); + }).pipe(Effect.provide(layer.pipe(Layer.provideMerge(NodeSqliteClient.layer({ filename }))))), + ); + }).pipe(Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/j5/a2a/RequestReplayService.ts b/apps/server/src/j5/a2a/RequestReplayService.ts new file mode 100644 index 0000000000000..d7f0a2608e5fd --- /dev/null +++ b/apps/server/src/j5/a2a/RequestReplayService.ts @@ -0,0 +1,95 @@ +// @effect-diagnostics nodeBuiltinImport:off - synchronous hashing keeps request comparison deterministic. +// @effect-diagnostics preferSchemaOverJson:off - canonical JSON is a digest input, not a persisted payload codec. +import * as NodeCrypto from "node:crypto"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import type { SqlError } from "effect/sql/SqlError"; + +export class RequestReplayConflictError extends Schema.TaggedError()( + "RequestReplayConflictError", + { target: Schema.String, legacy: Schema.Boolean }, +) { + override get message() { + return this.legacy + ? `The original request for ${this.target} predates replay verification and cannot be compared. Inspect that target and use a fresh client_request_id for new work.` + : `client_request_id is already bound to a different request for ${this.target}. Retry the original request, or use a fresh client_request_id for new work.`; + } +} + +const canonical = (value: unknown): unknown => { + if (Array.isArray(value)) return value.map(canonical); + if (value === null || typeof value !== "object") return value; + return Object.fromEntries( + Object.entries(value) + .filter(([, entry]) => entry !== undefined) + .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) + .map(([key, entry]) => [key, canonical(entry)]), + ); +}; + +export interface RequestReplayServiceShape { + readonly check: ( + id: string, + request: unknown, + ) => Effect.Effect; + /** Binds before side effects; an existing target without a binding cannot prove its intent. */ + readonly bind: (input: { + readonly id: string; + readonly target: string; + readonly request: unknown; + readonly legacy: boolean; + }) => Effect.Effect; +} + +export class RequestReplayService extends Context.Service< + RequestReplayService, + RequestReplayServiceShape +>()("t3/j5/a2a/RequestReplayService") {} + +export const layer = Layer.effect( + RequestReplayService, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const digestOf = (request: unknown) => + NodeCrypto.createHash("sha256") + .update(JSON.stringify(canonical(request))) + .digest("hex"); + const check: RequestReplayServiceShape["check"] = Effect.fn("j5.requestReplay.check")( + function* (id, request) { + const rows = yield* sql<{ readonly target: string; readonly request_digest: string }>` + SELECT target, request_digest FROM j5_a2a_request_replay WHERE id = ${id} + `; + const original = rows[0]; + if (original === undefined) return false; + if (original.request_digest !== digestOf(request)) + return yield* new RequestReplayConflictError({ target: original.target, legacy: false }); + return true; + }, + ); + const bind: RequestReplayServiceShape["bind"] = Effect.fn("j5.requestReplay.bind")(function* ( + input, + ) { + const digest = digestOf(input.request); + if (!input.legacy) { + yield* sql` + INSERT INTO j5_a2a_request_replay (id, target, request_digest) + VALUES (${input.id}, ${input.target}, ${digest}) + ON CONFLICT (id) DO NOTHING + `; + } + const rows = yield* sql<{ readonly target: string; readonly request_digest: string }>` + SELECT target, request_digest FROM j5_a2a_request_replay WHERE id = ${input.id} + `; + const original = rows[0]; + if (original === undefined || original.request_digest !== digest) + return yield* new RequestReplayConflictError({ + target: original?.target ?? input.target, + legacy: original === undefined, + }); + }, sql.withTransaction); + return RequestReplayService.of({ bind, check }); + }), +); diff --git a/apps/server/src/j5/a2a/mcp/handlers.test.ts b/apps/server/src/j5/a2a/mcp/handlers.test.ts index 4c8413100967b..d8d76c8487f5e 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.test.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.test.ts @@ -1606,7 +1606,20 @@ it.effect("spawns a saved agent as a Peer Agent only within its declared routes" }), }), threadManagementMock({ - getThreadProjection: (threadId) => Effect.succeed(projection(threadId)), + getThreadProjection: (threadId) => + Ref.get(commands).pipe( + Effect.map((all) => { + const create = all.find( + (command) => command.type === "thread.create" && command.threadId === threadId, + ); + return create?.type === "thread.create" + ? { + ...projection(threadId), + thread: { ...projection(threadId).thread, ...create, id: threadId }, + } + : projection(threadId); + }), + ), getThreadShell: (threadId) => Ref.get(personaCallerRuntimeMode).pipe( Effect.map((runtimeMode) => diff --git a/apps/server/src/j5/a2a/mcp/handlers.ts b/apps/server/src/j5/a2a/mcp/handlers.ts index 3819576edfbaa..c652dac9594f7 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -76,6 +76,7 @@ import { actsAsThreadCaller, } from "./outsideAgent.ts"; import { SpawnCompositionService } from "../SpawnCompositionService.ts"; +import { RequestReplayService } from "../RequestReplayService.ts"; import { SpawnWorkspaceService, namedBaseRefs, @@ -1002,35 +1003,73 @@ const handlers = { outside, }; const { home } = spawner; - const selected = yield* selectSpawnModel(scope, input); + const requestKey = + input.client_request_id ?? (yield* crypto.randomUUIDv4().pipe(Effect.orDie)); + const stableInput = { providerSessionId: spawner.requestNamespace, requestKey }; + const threadId = spawnThreadId(stableInput); const threadManagement = yield* ThreadManagementService; + const existing = yield* threadManagement + .getThreadShell(threadId) + .pipe( + Effect.mapError((error) => + stateError( + `Peer Agent thread ${threadId} could not be read: ${error.message}`, + "Retry j5_spawn_agent with the same client_request_id once it is readable.", + ), + ), + ); + const workspaceRequest = + input.workspace.type === "worktree" + ? { ...input.workspace, start_from_origin: input.workspace.start_from_origin ?? false } + : input.workspace.type === "existing_worktree" + ? { + ...input.workspace, + worktree_path: input.workspace.worktree_path.replace(/[\\/]+$/, ""), + } + : input.workspace; + const request = { + ...input, + client_request_id: undefined, + title: input.title ?? null, + scratch: input.scratch ?? false, + workspace: workspaceRequest, + }; + const replayService = yield* RequestReplayService; + const replayFailure = (error: { readonly message: string }) => + stateError(error.message, "Inspect the original target before starting new work."); + yield* replayService.check(threadId, request).pipe(Effect.mapError(replayFailure)); + const selected = existing?.modelSelection ?? (yield* selectSpawnModel(scope, input)); const personaId = input.persona; const persona = - personaId === undefined + personaId === undefined || existing !== null ? undefined : yield* prepareSpawnPersona({ ...input, persona: personaId }, selected); - const modelSelection = persona?.modelSelection ?? selected; + const modelSelection = existing?.modelSelection ?? persona?.modelSelection ?? selected; // A persona's policy sets its permissions. Without one the agent gets the caller's modes, // or the ones the caller chose, which upstream's rule keeps within the caller's own. - if (persona !== undefined && input.runtime_mode !== undefined) { + if (personaId !== undefined && input.runtime_mode !== undefined) { return yield* stateError( `Persona ${personaId} sets its own permission mode, so runtime_mode cannot be chosen for it.`, "Retry j5_spawn_agent without runtime_mode, or without persona.", ); } const { limits } = yield* loadCaller(); - // An outside agent's persona is held to its approved level, which a thread caller's is not. + // An outside persona's replay is capped against the existing thread's modes below. if (persona !== undefined && personaId !== undefined && outside !== undefined) { yield* assertPersonaWithinApprovedLevel(outside, personaId, persona.runtimeMode); } // With no mode chosen the agent gets the caller's: its thread's, or its approved level. const runtimeMode = + existing?.runtimeMode ?? input.runtime_mode ?? persona?.runtimeMode ?? home?.thread.runtimeMode ?? limits.runtimeMode; const interactionMode = - input.interaction_mode ?? home?.thread.interactionMode ?? limits.interactionMode; + existing?.interactionMode ?? + input.interaction_mode ?? + home?.thread.interactionMode ?? + limits.interactionMode; { // Each mode is held to the caller's own only where the caller chose it, so choosing an // interaction mode does not put a persona's permission mode under the ceiling. @@ -1045,22 +1084,12 @@ const handlers = { ); } } - const requestKey = - input.client_request_id ?? (yield* crypto.randomUUIDv4().pipe(Effect.orDie)); - const stableInput = { - providerSessionId: spawner.requestNamespace, - requestKey, - }; - const threadId = spawnThreadId(stableInput); - const existing = yield* threadManagement - .getThreadShell(threadId) - .pipe(Effect.orElseSucceed(() => null)); const firstAttempt = existing === null; // A retry finishes the agent its first attempt created, in the modes it was created with. // A caller's modes can be narrowed within one provider session, so those are checked // against what the caller may touch now. A persona's agent runs under its own policy, // except for an outside agent, whose approved level caps every agent it starts. - if (existing !== null && (persona === undefined || outside !== undefined)) { + if (existing !== null && (personaId === undefined || outside !== undefined)) { const exceeded = exceededDispatchModeLimit(limits, existing); if (exceeded !== undefined) { return yield* stateError( @@ -1166,6 +1195,14 @@ const handlers = { stateError(`Peer Agent was not created: ${error.detail}`, error.nextStep), ), ); + yield* replayService + .bind({ + id: threadId, + target: `Peer Agent ${participantIdForThread(threadId)} on thread ${threadId}`, + request, + legacy: existing !== null, + }) + .pipe(Effect.mapError(replayFailure)); return yield* spawnWorkspace .withSpawnStart( { stableInput, threadId, workspace }, @@ -1176,31 +1213,29 @@ const handlers = { // that only one call at a time may run, and only before the thread exists; a replay // replays its create. The thread is looked for again now that this call holds the // start: an earlier attempt may have created it since the read above. - const created = - input.workspace.type === "root" && - (yield* threadManagement - .getThreadShell(threadId) - .pipe(Effect.orElseSucceed(() => null))) !== null; + const current = yield* threadManagement + .getThreadShell(threadId) + .pipe(Effect.mapError(replayFailure)); const sharedCheckout = - input.workspace.type !== "root" && home !== undefined - ? home.thread - : { - branch: null, - worktreePath: created - ? null - : Option.getOrNull( - yield* (yield* ManagedProjectFolders) - .folderForThread({ projectId: target, threadId, text: input.brief }) - .pipe( - Effect.mapError((error) => - stateError( - `A folder for the agent could not be made: ${error.message}`, - "Retry j5_spawn_agent with the same client_request_id.", - ), + current !== null + ? current + : input.workspace.type !== "root" && home !== undefined + ? home.thread + : { + branch: null, + worktreePath: Option.getOrNull( + yield* (yield* ManagedProjectFolders) + .folderForThread({ projectId: target, threadId, text: input.brief }) + .pipe( + Effect.mapError((error) => + stateError( + `A folder for the agent could not be made: ${error.message}`, + "Retry j5_spawn_agent with the same client_request_id.", ), ), - ), - }; + ), + ), + }; yield* threadManagement .dispatch({ type: "thread.create", @@ -1210,11 +1245,13 @@ const handlers = { threadId, projectId: target, title: spawnTitle(input.brief, input.title), - modelSelection, - runtimeMode, - interactionMode, + modelSelection: current?.modelSelection ?? modelSelection, + runtimeMode: current?.runtimeMode ?? runtimeMode, + interactionMode: current?.interactionMode ?? interactionMode, ...(persona === undefined ? {} : { agentPersonaAssignment: persona.assignment }), - ...spawnThreadCheckout(workspace, sharedCheckout), + ...(current === null + ? spawnThreadCheckout(workspace, sharedCheckout) + : { branch: current.branch, worktreePath: current.worktreePath }), }) .pipe( Effect.mapError((error) => @@ -1236,6 +1273,17 @@ const handlers = { ), ), ); + if (personaId === undefined || outside !== undefined) { + const exceeded = exceededDispatchModeLimit( + (yield* loadCaller()).limits, + child.thread, + ); + if (exceeded !== undefined) + return yield* stateError( + `Peer Agent ${participantIdForThread(threadId)} has modes broader than yours is now.`, + "Ask the user to start that agent, or use a fresh client_request_id.", + ); + } const facts = yield* (yield* SpawnCompositionService) .recordFacts({ homeCommandId: spawnHomeCommandId(stableInput), @@ -1281,7 +1329,7 @@ const handlers = { Effect.mapError((error) => stateError( `Peer Agent ${facts.home.participantId} is registered and addressable, but its brief's attachments could not be claimed: ${error.message}`, - "Retry j5_spawn_agent with the same client_request_id and attachments that are pending uploads.", + "Retry j5_spawn_agent with the same client_request_id and the original attachment ids after repairing the upload; use a fresh client_request_id for a changed brief.", ), ), )).attachments; @@ -1304,9 +1352,9 @@ const handlers = { ? { spawnerThreadId: scope.thread?.threadId } : { outsideAgentName: outside.client.label }), }), - modelSelection, - runtimeMode, - interactionMode, + modelSelection: child.thread.modelSelection, + runtimeMode: child.thread.runtimeMode, + interactionMode: child.thread.interactionMode, attachments, }) .pipe( diff --git a/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index 9e3b8203462e4..367449522d221 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -1,3 +1,4 @@ +import { RequestReplayService } from "../RequestReplayService.ts"; import { Tool, Toolkit } from "effect/ai"; import { playbookTools } from "../../playbooks/mcp.ts"; import * as Schema from "effect/Schema"; @@ -620,6 +621,7 @@ const spawnDependencies = [ ThreadRegistration, A2ALedger, SpawnCompositionService, + RequestReplayService, // Resolves the workspace, binds the request key to it, and starts the brief. SpawnWorkspaceService, ThreadManagementService, diff --git a/apps/server/src/j5/a2a/migrations/039_RequestReplay.ts b/apps/server/src/j5/a2a/migrations/039_RequestReplay.ts new file mode 100644 index 0000000000000..f81e50d6118e6 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/039_RequestReplay.ts @@ -0,0 +1,14 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + // No target foreign key: deleting an operation must not free its retry key for other work. + yield* sql` + CREATE TABLE j5_a2a_request_replay ( + id TEXT PRIMARY KEY NOT NULL, + target TEXT NOT NULL, + request_digest TEXT NOT NULL + ) + `; +}); diff --git a/apps/server/src/j5/a2a/runtimeLayer.ts b/apps/server/src/j5/a2a/runtimeLayer.ts index 6285d3c1c2c89..00139be861ab7 100644 --- a/apps/server/src/j5/a2a/runtimeLayer.ts +++ b/apps/server/src/j5/a2a/runtimeLayer.ts @@ -48,6 +48,7 @@ import { layer as peerAdminLayer } from "./PeerAdminService.ts"; import { layer as threadRegistrationLayer } from "./ThreadRegistration.ts"; import { layer as spawnCompositionLayer } from "./SpawnCompositionService.ts"; import { layer as spawnWorkspaceLayer } from "./spawnWorkspace.ts"; +import { layer as requestReplayLayer } from "./RequestReplayService.ts"; import { layer as agentHandoffArtifactDeleteLayer } from "../agents/agentHandoffArtifactDelete.ts"; import { layer as agentHandoffNudgeQueueLayer } from "../agents/agentHandoffNudgeQueue.ts"; import { layer as agentHandoffNudgeWorkerLayer } from "../agents/agentHandoffNudgeWorker.ts"; @@ -227,6 +228,7 @@ export const makeJ5A2AAuxiliaryLayer = ( lifecycleServiceProvided, archiveFactsProvided, spawnWorkspaceProvided, + requestReplayLayer, agentCrewInstanceLayer, archiveCrewProvided, crewProposalProvided, diff --git a/apps/server/src/j5/a2a/spawnWorkspace.test.ts b/apps/server/src/j5/a2a/spawnWorkspace.test.ts index fa379375dab75..ac9cfd52916d5 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.test.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.test.ts @@ -12,6 +12,9 @@ import { type OrchestrationV2ThreadProjection, type RuntimeMode, } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import { layerMemory } from "../../persistence/Sqlite.ts"; +import { RequestReplayService, layer as requestReplayLayer } from "./RequestReplayService.ts"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -30,6 +33,7 @@ import { McpInvocationContext, type McpInvocationScope } from "../../mcp/McpInvo import { OrchestratorMcpService } from "../../mcp/OrchestratorMcpService.ts"; import type { ThreadLaunchInput } from "../../orchestration-v2/ThreadLaunchService.ts"; import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; +import { OrchestratorDispatchError } from "../../orchestration-v2/Orchestrator.ts"; import { createPendingAttachmentId, resolveAttachmentPath } from "../../attachmentStore.ts"; import { ServerConfig } from "../../config.ts"; import { ManagedProjectFolders } from "../../project/ManagedProjectFolders.ts"; @@ -163,6 +167,7 @@ const callerThread = (threadId: ThreadId, runtimeMode: RuntimeMode = "full-acces const spawnHarness = (input: { readonly checkout: FakeCheckout; + readonly replay?: Layer.Layer; /** Git as an agent's shell leaves it, served through upstream-style cached refs. */ readonly liveCheckout?: Ref.Ref; /** The durable command log; pass one from an earlier harness to model a restart. */ @@ -171,6 +176,7 @@ const spawnHarness = (input: { readonly beforeCreate?: Effect.Effect; /** The caller's own permission mode; full access unless a test narrows it. */ readonly callerRuntimeMode?: RuntimeMode; + readonly liveCaller?: Ref.Ref; /** The agent an earlier attempt of the same request already created, in this mode. */ readonly existingChildRuntimeMode?: RuntimeMode; /** Runs inside each read of the target project, so a test can hold a call before its start. */ @@ -184,6 +190,8 @@ const spawnHarness = (input: { input.commands ?? (yield* Ref.make>([])); const launches = yield* Ref.make>([]); const failFacts = yield* Ref.make(false); + const failCreate = yield* Ref.make(false); + const failBrief = yield* Ref.make(false); const factProjects = yield* Ref.make>([]); const folderClaims = yield* Ref.make(0); const recorded = yield* Ref.make>([]); @@ -241,7 +249,21 @@ const spawnHarness = (input: { }), Layer.mock(ThreadManagementService)({ getThreadProjection: (threadId) => - Effect.succeed(callerThread(threadId, input.callerRuntimeMode)), + input.liveCaller !== undefined && threadId === invocation.thread.threadId + ? Ref.get(input.liveCaller) + : Ref.get(commands).pipe( + Effect.map((all) => { + const create = all.find( + (command) => command.type === "thread.create" && command.threadId === threadId, + ); + return create?.type === "thread.create" + ? { + ...callerThread(threadId), + thread: { ...callerThread(threadId).thread, ...create, id: threadId }, + } + : callerThread(threadId, input.callerRuntimeMode); + }), + ), // The caller is mid-run, as upstream's tool access check requires; the child does not // exist yet. getThreadShell: (threadId) => @@ -262,6 +284,19 @@ const spawnHarness = (input: { deletedAt: null, } as never), ).pipe( + Effect.flatMap((shell) => + input.liveCaller !== undefined && threadId === invocation.thread.threadId + ? Ref.get(input.liveCaller).pipe( + Effect.map( + (projection) => + ({ + ...projection.thread, + activeRunId: "run:caller", + }) as never, + ), + ) + : Effect.succeed(shell), + ), // A thread this harness has created exists from then on, as a real one does. Effect.flatMap((shell) => shell !== null @@ -275,6 +310,10 @@ const spawnHarness = (input: { return create?.type === "thread.create" ? ({ ...callerThread(threadId, create.runtimeMode).thread, + modelSelection: create.modelSelection, + interactionMode: create.interactionMode, + branch: create.branch, + worktreePath: create.worktreePath, archivedAt: null, deletedAt: null, } as never) @@ -285,6 +324,14 @@ const spawnHarness = (input: { ), dispatch: (command) => Effect.gen(function* () { + if ( + (command.type === "thread.create" && (yield* Ref.get(failCreate))) || + (command.type === "message.dispatch" && (yield* Ref.get(failBrief))) + ) + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + }); if (command.type === "thread.create" && input.beforeCreate) yield* input.beforeCreate; yield* Ref.update(commands, (items) => [...items, command]); yield* Ref.update(log, (items) => [...items, command.type]); @@ -380,6 +427,7 @@ const spawnHarness = (input: { Layer.provideMerge( fakeSpawnWorkspaceLayer({ checkout: input.checkout, + ...(input.replay === undefined ? {} : { replay: input.replay }), ...(input.liveCheckout === undefined ? {} : { liveCheckout: input.liveCheckout }), launches, launch: () => Ref.update(log, (items) => [...items, "launch"]), @@ -414,6 +462,8 @@ const spawnHarness = (input: { commands, launches, failFacts, + failCreate, + failBrief, factProjects, folderClaims, recorded, @@ -961,7 +1011,12 @@ it.effect("an explicit shared workspace keeps the caller's checkout and starts t it.effect("binds a client_request_id to its first workspace type, across a restart", () => Effect.gen(function* () { - const first = yield* spawnHarness({ checkout: { isRepo: true, refName: "j5/main" } }); + const replayContext = yield* Layer.build(requestReplayLayer.pipe(Layer.provide(layerMemory))); + const replay = Layer.succeed( + RequestReplayService, + Context.get(replayContext, RequestReplayService), + ); + const first = yield* spawnHarness({ checkout: { isRepo: true, refName: "j5/main" }, replay }); yield* Effect.gen(function* () { // The worktree create is accepted, then the spawn stops before its home is recorded. yield* Ref.set(first.failFacts, true); @@ -978,6 +1033,7 @@ it.effect("binds a client_request_id to its first workspace type, across a resta const restarted = yield* spawnHarness({ checkout: { isRepo: true, refName: "j5/main" }, commands: first.commands, + replay, }); yield* Effect.gen(function* () { const switched = yield* restarted.call({ @@ -988,16 +1044,23 @@ it.effect("binds a client_request_id to its first workspace type, across a resta assert.isTrue(switched.isFailure); assert.include( (switched.result as { readonly message: string }).message, - 'already bound to workspace {"type":"worktree"}', + "already bound to a different request", ); assert.lengthOf(yield* Ref.get(restarted.commands), 1); - // Options are not bound: nothing was provisioned yet, so the retry's base takes effect. - const resumed = yield* restarted.call({ + // A changed base is a different request, even before workspace preparation. + const changed = yield* restarted.call({ ...spawnArgs, workspace: { type: "worktree", base_ref: "release" }, client_request_id: "bound", }); + assert.isTrue(changed.isFailure); + assert.include(message(changed), "different request"); + const resumed = yield* restarted.call({ + ...spawnArgs, + workspace: { type: "worktree", base_ref: "j5/main" }, + client_request_id: "bound", + }); assert.isFalse(resumed.isFailure); const [original, replay] = yield* Ref.get(restarted.commands); assert.equal(replay?.commandId, original?.commandId); @@ -1005,7 +1068,7 @@ it.effect("binds a client_request_id to its first workspace type, across a resta assert.lengthOf(launches, 1); assert.equal( launches[0]?.workspaceStrategy.type === "worktree" && launches[0].workspaceStrategy.baseRef, - "release", + "j5/main", ); }).pipe(Effect.provide(restarted.layer)); }), @@ -1052,7 +1115,7 @@ it.effect("a second start on one key while the first is in flight is refused, no assert.isTrue(second.result.isFailure); assert.include( (second.result.result as { readonly message: string }).message, - "already in progress", + "different request", ); } @@ -1181,7 +1244,7 @@ it.effect("spawns into an existing worktree on its branch, with no preparation", assert.isTrue(switched.isFailure); assert.include( (switched.result as { readonly message: string }).message, - 'already bound to workspace {"type":"existing_worktree"}', + "already bound to a different request", ); const elsewhere = yield* call({ ...spawnArgs, @@ -1235,3 +1298,231 @@ it.effect("reads git fresh for each spawn that binds a worktree", () => }).pipe(Effect.provide(layer)); }), ); + +it.effect( + "retries failures before creation, after creation and after registration without changing the request", + () => + Effect.gen(function* () { + for (const phase of ["failCreate", "failFacts", "failBrief"] as const) { + const harness = yield* spawnHarness({ checkout: { isRepo: false, refName: null } }); + yield* Effect.gen(function* () { + const args = { + ...spawnArgs, + workspace: { type: "shared" as const }, + client_request_id: phase, + }; + yield* Ref.set(harness[phase], true); + assert.isTrue((yield* harness.call(args)).isFailure); + const before = yield* Ref.get(harness.commands); + for (const change of [ + { brief: "changed" }, + { title: "changed" }, + { persona: "other" }, + { model: "changed" }, + { reasoning: "medium" }, + { runtime_mode: "approval-required" as const }, + { interaction_mode: "plan" as const }, + { project_id: LedgerProjectId.make("other") }, + { workspace: { type: "root" as const } }, + ]) { + const mismatch = yield* harness.call({ ...args, ...change }); + assert.isTrue(mismatch.isFailure); + assert.include(message(mismatch), "different request"); + assert.include(message(mismatch), "agent:j5:a2a:"); + assert.include(message(mismatch), "fresh client_request_id"); + } + assert.deepStrictEqual(yield* Ref.get(harness.commands), before); + yield* Ref.set(harness[phase], false); + assert.isFalse((yield* harness.call(args)).isFailure); + const commands = yield* Ref.get(harness.commands); + assert.equal( + new Set( + commands + .filter((command) => command.type === "thread.create") + .map((command) => command.threadId), + ).size, + 1, + ); + assert.equal( + new Set( + commands + .filter((command) => command.type === "message.dispatch") + .map((command) => command.messageId), + ).size, + 1, + ); + }).pipe(Effect.provide(harness.layer)); + } + }), +); + +it.effect( + "normalizes workspace defaults and resumes the child's persisted modes and checkout", + () => + Effect.gen(function* () { + const liveCaller = yield* Ref.make( + callerThread(invocation.thread.threadId, "approval-required"), + ); + const harness = yield* spawnHarness({ + checkout: { isRepo: true, refName: "j5/main" }, + liveCaller, + }); + yield* Effect.gen(function* () { + const args = { + ...spawnArgs, + workspace: { type: "worktree" as const, base_ref: "j5/main" }, + client_request_id: "same-defaults", + }; + yield* Ref.set(harness.failFacts, true); + assert.isTrue((yield* harness.call(args)).isFailure); + yield* Ref.set(harness.failFacts, false); + yield* Ref.set(liveCaller, { + ...callerThread(invocation.thread.threadId), + thread: { + ...callerThread(invocation.thread.threadId).thread, + branch: "new-branch", + worktreePath: "/new-checkout", + }, + }); + assert.isFalse( + (yield* harness.call({ + ...args, + workspace: { ...args.workspace, start_from_origin: false }, + })).isFailure, + ); + const launch = (yield* Ref.get(harness.launches))[0]; + assert.equal(launch?.runtimeMode, "approval-required"); + const creates = (yield* Ref.get(harness.commands)).filter( + (command) => command.type === "thread.create", + ); + assert.equal(creates[0]?.worktreePath, creates[1]?.worktreePath); + }).pipe(Effect.provide(harness.layer)); + }), +); + +it("optional spawn fields reject null rather than treating it as an omitted choice", () => { + for (const key of [ + "persona", + "title", + "runtime_mode", + "interaction_mode", + "project_id", + "scratch", + "attachments", + ]) + assert.isTrue(Exit.isFailure(decodeSpawnInput({ ...spawnArgs, [key]: null }))); +}); + +it.effect( + "a delayed retry re-reads persisted child modes under the start guard and checks its authorization", + () => + Effect.gen(function* () { + for (const childMode of ["approval-required", "full-access"] as const) { + const originalMode = childMode === "full-access" ? "approval-required" : "full-access"; + const liveCaller = yield* Ref.make(callerThread(invocation.thread.threadId, originalMode)); + const reads = yield* Ref.make(0); + const held = yield* Deferred.make(); + const release = yield* Deferred.make(); + const harness = yield* spawnHarness({ + checkout: { isRepo: true, refName: "j5/main" }, + liveCaller, + beforeProjectRead: Ref.getAndUpdate(reads, (count) => count + 1).pipe( + Effect.flatMap((count) => + count === 0 + ? Deferred.succeed(held, undefined).pipe(Effect.andThen(Deferred.await(release))) + : Effect.void, + ), + ), + }); + yield* Effect.gen(function* () { + const args = { + ...spawnArgs, + scratch: true, + workspace: { type: "root" as const }, + client_request_id: childMode, + }; + const delayed = yield* harness + .call(args) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(held); + yield* Ref.set(liveCaller, callerThread(invocation.thread.threadId, childMode)); + yield* Ref.set(harness.failBrief, true); + assert.isTrue((yield* harness.call(args)).isFailure); + yield* Ref.set(harness.failBrief, false); + yield* Ref.set(liveCaller, callerThread(invocation.thread.threadId, originalMode)); + yield* Deferred.succeed(release, undefined); + const result = yield* Fiber.join(delayed); + assert.equal(result.isFailure, childMode === "full-access"); + if (result.isFailure) assert.include(message(result), "broader than yours is now"); + const creates = (yield* Ref.get(harness.commands)).filter( + (command) => command.type === "thread.create", + ); + assert.deepStrictEqual( + creates.map((command) => command.runtimeMode), + [childMode, childMode], + ); + assert.deepStrictEqual( + creates.map((command) => command.worktreePath), + [scratchFolder, scratchFolder], + ); + assert.equal(yield* Ref.get(harness.folderClaims), 1); + }).pipe(Effect.provide(harness.layer)); + } + }), +); + +it.effect("an outside agent's narrowed approved level still caps an identical replay", () => + Effect.gen(function* () { + let access: AuthMcpClientAccess = "full-access"; + const scope = { + ...outsideScope(access), + client: { + sessionId: "session-1", + label: "Outside", + get access() { + return access; + }, + }, + }; + const harness = yield* spawnHarness({ checkout: { isRepo: false, refName: null }, scope }); + yield* Effect.gen(function* () { + const args = { + ...spawnArgs, + project_id: LedgerProjectId.make(otherProjectId), + workspace: { type: "root" as const }, + client_request_id: "outside-narrowed", + }; + yield* Ref.set(harness.failBrief, true); + assert.isTrue((yield* harness.call(args)).isFailure); + yield* Ref.set(harness.failBrief, false); + access = "approval-required"; + const replay = yield* harness.call(args); + assert.isTrue(replay.isFailure); + assert.include(message(replay), "broader than yours is now"); + assert.lengthOf( + (yield* Ref.get(harness.commands)).filter((command) => command.type === "message.dispatch"), + 0, + ); + }).pipe(Effect.provide(harness.layer)); + }), +); + +it.effect("refuses an unbound legacy spawn without blessing the current request", () => + Effect.gen(function* () { + const harness = yield* spawnHarness({ + checkout: { isRepo: false, refName: null }, + existingChildRuntimeMode: "full-access", + }); + yield* Effect.gen(function* () { + const result = yield* harness.call({ + ...spawnArgs, + workspace: { type: "shared" }, + client_request_id: "legacy", + }); + assert.isTrue(result.isFailure); + assert.include(message(result), "predates replay verification"); + assert.include(message(result), "fresh client_request_id"); + assert.lengthOf(yield* Ref.get(harness.commands), 0); + }).pipe(Effect.provide(harness.layer)); + }), +); diff --git a/apps/server/src/j5/a2a/test-support/spawnWorkspaceFakes.ts b/apps/server/src/j5/a2a/test-support/spawnWorkspaceFakes.ts index 73e5c97937df7..3c16a039ee416 100644 --- a/apps/server/src/j5/a2a/test-support/spawnWorkspaceFakes.ts +++ b/apps/server/src/j5/a2a/test-support/spawnWorkspaceFakes.ts @@ -13,6 +13,8 @@ import { } from "../../../orchestration-v2/ThreadLaunchService.ts"; import { ProjectService } from "../../../project/ProjectService.ts"; import { layerFromReceiptStore } from "../spawnWorkspace.ts"; +import { layerMemory } from "../../../persistence/Sqlite.ts"; +import { RequestReplayService, layer as requestReplayLayer } from "../RequestReplayService.ts"; export interface FakeCheckout { readonly isRepo: boolean; @@ -55,6 +57,7 @@ const fakeRefs = (checkout: FakeCheckout, workspaceRoot: string) => { */ export const fakeSpawnWorkspaceLayer = (options: { readonly checkout: FakeCheckout; + readonly replay?: Layer.Layer; /** * When given, git reads this instead, as an agent's shell leaves it. The direct reads see it as * it is now, and a checkout's status does once invalidated; `listRefs` keeps serving the @@ -152,5 +155,6 @@ export const fakeSpawnWorkspaceLayer = (options: { }), ), ), + Layer.merge(options.replay ?? requestReplayLayer.pipe(Layer.provide(layerMemory))), ); }; diff --git a/apps/server/src/mcp/toolkits/worktree/registration.test.ts b/apps/server/src/mcp/toolkits/worktree/registration.test.ts index 4cce446f43462..cdae317077514 100644 --- a/apps/server/src/mcp/toolkits/worktree/registration.test.ts +++ b/apps/server/src/mcp/toolkits/worktree/registration.test.ts @@ -1,3 +1,4 @@ +import { RequestReplayService } from "../../../j5/a2a/RequestReplayService.ts"; import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts"; import * as ProjectionStore from "../../../orchestration-v2/ProjectionStore.ts"; import * as DeviceService from "../../../device/DeviceService.ts"; @@ -99,6 +100,7 @@ const layerStubServices = Layer.mergeAll( Layer.mock(PlaybookCrewRelay)({}), Layer.mock(PlaybookStore)({}), Layer.mock(SpawnCompositionService)({}), + Layer.mock(RequestReplayService)({}), Layer.mock(SpawnWorkspaceService)({}), Layer.mock(ThreadRegistration)({}), ); From 839b7b04763490bd85f69c6579a97a9f3cdb1668 Mon Sep 17 00:00:00 2001 From: Bastian Huppertz <29781772+BastiHu@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:18:31 +0000 Subject: [PATCH 2/9] test(j5): verify spawn replay failures and concurrent retries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Restore complete live-caller shell fixtures and assert injected failure causes. Keep identical and mismatched concurrent retries as distinct cases, and authorize persisted children before replaying create. Integration note: RequestReplay migration 039 conflicts with pending #638 migrations 039–042; reconcile numbering against main before publication. Co-Authored-By: GPT-6.1-Sol Co-Authored-By: Claude Opus 5.5 --- apps/server/src/j5/a2a/mcp/handlers.ts | 35 +++++----- apps/server/src/j5/a2a/spawnWorkspace.test.ts | 65 ++++++++++++++++--- 2 files changed, 70 insertions(+), 30 deletions(-) diff --git a/apps/server/src/j5/a2a/mcp/handlers.ts b/apps/server/src/j5/a2a/mcp/handlers.ts index c652dac9594f7..fee11c266d67b 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -1008,16 +1008,14 @@ const handlers = { const stableInput = { providerSessionId: spawner.requestNamespace, requestKey }; const threadId = spawnThreadId(stableInput); const threadManagement = yield* ThreadManagementService; + const spawnReadFailure = (error: { readonly message: string }) => + stateError( + `Peer Agent thread ${threadId} could not be read: ${error.message}`, + "Retry j5_spawn_agent with the same client_request_id once it is readable.", + ); const existing = yield* threadManagement .getThreadShell(threadId) - .pipe( - Effect.mapError((error) => - stateError( - `Peer Agent thread ${threadId} could not be read: ${error.message}`, - "Retry j5_spawn_agent with the same client_request_id once it is readable.", - ), - ), - ); + .pipe(Effect.mapError(spawnReadFailure)); const workspaceRequest = input.workspace.type === "worktree" ? { ...input.workspace, start_from_origin: input.workspace.start_from_origin ?? false } @@ -1215,7 +1213,15 @@ const handlers = { // start: an earlier attempt may have created it since the read above. const current = yield* threadManagement .getThreadShell(threadId) - .pipe(Effect.mapError(replayFailure)); + .pipe(Effect.mapError(spawnReadFailure)); + if (current !== null && (personaId === undefined || outside !== undefined)) { + const exceeded = exceededDispatchModeLimit((yield* loadCaller()).limits, current); + if (exceeded !== undefined) + return yield* stateError( + `Peer Agent ${participantIdForThread(threadId)} has modes broader than yours is now.`, + "Ask the user to start that agent, or use a fresh client_request_id.", + ); + } const sharedCheckout = current !== null ? current @@ -1273,17 +1279,6 @@ const handlers = { ), ), ); - if (personaId === undefined || outside !== undefined) { - const exceeded = exceededDispatchModeLimit( - (yield* loadCaller()).limits, - child.thread, - ); - if (exceeded !== undefined) - return yield* stateError( - `Peer Agent ${participantIdForThread(threadId)} has modes broader than yours is now.`, - "Ask the user to start that agent, or use a fresh client_request_id.", - ); - } const facts = yield* (yield* SpawnCompositionService) .recordFacts({ homeCommandId: spawnHomeCommandId(stableInput), diff --git a/apps/server/src/j5/a2a/spawnWorkspace.test.ts b/apps/server/src/j5/a2a/spawnWorkspace.test.ts index ac9cfd52916d5..90d056ce48aa6 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.test.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.test.ts @@ -291,6 +291,9 @@ const spawnHarness = (input: { (projection) => ({ ...projection.thread, + providerInstanceId: invocation.thread.providerInstanceId, + archivedAt: null, + deletedAt: null, activeRunId: "run:caller", }) as never, ), @@ -1026,6 +1029,7 @@ it.effect("binds a client_request_id to its first workspace type, across a resta client_request_id: "bound", }); assert.isTrue(halfDone.isFailure); + assert.include(message(halfDone), "visible orphan"); assert.lengthOf(yield* Ref.get(first.commands), 1); }).pipe(Effect.provide(first.layer)); @@ -1074,7 +1078,16 @@ it.effect("binds a client_request_id to its first workspace type, across a resta }), ); -it.effect("a second start on one key while the first is in flight is refused, not queued", () => +it.effect.each([ + { + mismatched: false, + name: "concurrent identical requests retain the in-flight guard and create only one agent", + }, + { + mismatched: true, + name: "concurrent different requests on one key refuse the loser and create only the winner", + }, +])("$name", ({ mismatched }) => Effect.gen(function* () { const createsEntered = yield* Ref.make(0); const createEntered = yield* Deferred.make(); @@ -1101,7 +1114,11 @@ it.effect("a second start on one key while the first is in flight is refused, no // The first start is in flight, stopped inside its create. yield* Deferred.await(createEntered); const loser = yield* harness - .call({ ...spawnArgs, workspace: { type: "shared" }, client_request_id: "raced" }) + .call({ + ...spawnArgs, + workspace: mismatched ? { type: "shared" } : { type: "worktree", base_ref: "j5/main" }, + client_request_id: "raced", + }) .pipe(Effect.forkChild); // The second start returns while the first still holds its create; without the guard it // would reach a create of its own instead, which ends this race the other way. @@ -1115,7 +1132,7 @@ it.effect("a second start on one key while the first is in flight is refused, no assert.isTrue(second.result.isFailure); assert.include( (second.result.result as { readonly message: string }).message, - "different request", + mismatched ? "different request" : "already in progress", ); } @@ -1312,8 +1329,18 @@ it.effect( client_request_id: phase, }; yield* Ref.set(harness[phase], true); - assert.isTrue((yield* harness.call(args)).isFailure); + const failed = yield* harness.call(args); + assert.isTrue(failed.isFailure); + assert.include( + message(failed), + phase === "failCreate" + ? "could not be created" + : phase === "failFacts" + ? "visible orphan" + : "brief did not start", + ); const before = yield* Ref.get(harness.commands); + assert.lengthOf(before, phase === "failCreate" ? 0 : 1); for (const change of [ { brief: "changed" }, { title: "changed" }, @@ -1374,7 +1401,10 @@ it.effect( client_request_id: "same-defaults", }; yield* Ref.set(harness.failFacts, true); - assert.isTrue((yield* harness.call(args)).isFailure); + const failed = yield* harness.call(args); + assert.isTrue(failed.isFailure); + assert.include(message(failed), "visible orphan"); + assert.lengthOf(yield* Ref.get(harness.commands), 1); yield* Ref.set(harness.failFacts, false); yield* Ref.set(liveCaller, { ...callerThread(invocation.thread.threadId), @@ -1444,10 +1474,22 @@ it.effect( const delayed = yield* harness .call(args) .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(held); + yield* Effect.raceFirst( + Deferred.await(held), + Fiber.join(delayed).pipe( + Effect.flatMap((result) => + Effect.die( + new Error(`Delayed call returned before reaching the gate: ${message(result)}`), + ), + ), + ), + ); yield* Ref.set(liveCaller, callerThread(invocation.thread.threadId, childMode)); yield* Ref.set(harness.failBrief, true); - assert.isTrue((yield* harness.call(args)).isFailure); + const failed = yield* harness.call(args); + assert.isTrue(failed.isFailure); + assert.include(message(failed), "brief did not start"); + assert.lengthOf(yield* Ref.get(harness.commands), 1); yield* Ref.set(harness.failBrief, false); yield* Ref.set(liveCaller, callerThread(invocation.thread.threadId, originalMode)); yield* Deferred.succeed(release, undefined); @@ -1459,11 +1501,11 @@ it.effect( ); assert.deepStrictEqual( creates.map((command) => command.runtimeMode), - [childMode, childMode], + childMode === "full-access" ? [childMode] : [childMode, childMode], ); assert.deepStrictEqual( creates.map((command) => command.worktreePath), - [scratchFolder, scratchFolder], + childMode === "full-access" ? [scratchFolder] : [scratchFolder, scratchFolder], ); assert.equal(yield* Ref.get(harness.folderClaims), 1); }).pipe(Effect.provide(harness.layer)); @@ -1493,7 +1535,10 @@ it.effect("an outside agent's narrowed approved level still caps an identical re client_request_id: "outside-narrowed", }; yield* Ref.set(harness.failBrief, true); - assert.isTrue((yield* harness.call(args)).isFailure); + const failed = yield* harness.call(args); + assert.isTrue(failed.isFailure); + assert.include(message(failed), "brief did not start"); + assert.lengthOf(yield* Ref.get(harness.commands), 1); yield* Ref.set(harness.failBrief, false); access = "approval-required"; const replay = yield* harness.call(args); From 5a9ceafcf8b03edac31f8f88e2b6de0d497f5a83 Mon Sep 17 00:00:00 2001 From: Bastian Huppertz Date: Tue, 20 Oct 2026 15:06:09 +0200 Subject: [PATCH 3/9] fix(j5): address spawn replay review comments Keyless spawns no longer write replay rows nobody can retry. The replay service declares its interface inline, and check no longer returns an unused boolean. Both replay mode checks share one message; the early one stays because it is the only check an unbound legacy agent reaches. Replay rows record created_at, and the spawn tool description says that any change under a reused client_request_id is refused. --- .../src/j5/a2a/RequestReplayService.test.ts | 3 +- .../server/src/j5/a2a/RequestReplayService.ts | 65 +++++++++---------- apps/server/src/j5/a2a/mcp/handlers.ts | 62 ++++++++++-------- apps/server/src/j5/a2a/mcp/tools.ts | 2 +- .../j5/a2a/migrations/039_RequestReplay.ts | 3 +- apps/server/src/j5/a2a/spawnWorkspace.test.ts | 18 +++++ 6 files changed, 88 insertions(+), 65 deletions(-) diff --git a/apps/server/src/j5/a2a/RequestReplayService.test.ts b/apps/server/src/j5/a2a/RequestReplayService.test.ts index 18ddf5fd1910c..e6fa42616d387 100644 --- a/apps/server/src/j5/a2a/RequestReplayService.test.ts +++ b/apps/server/src/j5/a2a/RequestReplayService.test.ts @@ -49,7 +49,8 @@ it.effect("persists the original request across database reopen and refuses chan readonly count: number; }>`SELECT COUNT(*) AS count FROM j5_a2a_request_replay`; assert.equal(rows[0]?.count, 1); - assert.isFalse(yield* replay.check("new-key", {})); + yield* replay.check("new-key", {}); + assert.isTrue(Result.isFailure(yield* replay.check(first.id, {}).pipe(Effect.result))); const legacy = yield* replay .bind({ ...first, id: "legacy", legacy: true }) .pipe(Effect.result); diff --git a/apps/server/src/j5/a2a/RequestReplayService.ts b/apps/server/src/j5/a2a/RequestReplayService.ts index d7f0a2608e5fd..4d7ca16127d5e 100644 --- a/apps/server/src/j5/a2a/RequestReplayService.ts +++ b/apps/server/src/j5/a2a/RequestReplayService.ts @@ -30,23 +30,21 @@ const canonical = (value: unknown): unknown => { ); }; -export interface RequestReplayServiceShape { - readonly check: ( - id: string, - request: unknown, - ) => Effect.Effect; - /** Binds before side effects; an existing target without a binding cannot prove its intent. */ - readonly bind: (input: { - readonly id: string; - readonly target: string; - readonly request: unknown; - readonly legacy: boolean; - }) => Effect.Effect; -} - export class RequestReplayService extends Context.Service< RequestReplayService, - RequestReplayServiceShape + { + readonly check: ( + id: string, + request: unknown, + ) => Effect.Effect; + /** Binds before side effects; an existing target without a binding cannot prove its intent. */ + readonly bind: (input: { + readonly id: string; + readonly target: string; + readonly request: unknown; + readonly legacy: boolean; + }) => Effect.Effect; + } >()("t3/j5/a2a/RequestReplayService") {} export const layer = Layer.effect( @@ -57,39 +55,38 @@ export const layer = Layer.effect( NodeCrypto.createHash("sha256") .update(JSON.stringify(canonical(request))) .digest("hex"); - const check: RequestReplayServiceShape["check"] = Effect.fn("j5.requestReplay.check")( + const check: RequestReplayService["Service"]["check"] = Effect.fn("j5.requestReplay.check")( function* (id, request) { const rows = yield* sql<{ readonly target: string; readonly request_digest: string }>` SELECT target, request_digest FROM j5_a2a_request_replay WHERE id = ${id} `; const original = rows[0]; - if (original === undefined) return false; - if (original.request_digest !== digestOf(request)) + if (original !== undefined && original.request_digest !== digestOf(request)) return yield* new RequestReplayConflictError({ target: original.target, legacy: false }); - return true; }, ); - const bind: RequestReplayServiceShape["bind"] = Effect.fn("j5.requestReplay.bind")(function* ( - input, - ) { - const digest = digestOf(input.request); - if (!input.legacy) { - yield* sql` + const bind: RequestReplayService["Service"]["bind"] = Effect.fn("j5.requestReplay.bind")( + function* (input) { + const digest = digestOf(input.request); + if (!input.legacy) { + yield* sql` INSERT INTO j5_a2a_request_replay (id, target, request_digest) VALUES (${input.id}, ${input.target}, ${digest}) ON CONFLICT (id) DO NOTHING `; - } - const rows = yield* sql<{ readonly target: string; readonly request_digest: string }>` + } + const rows = yield* sql<{ readonly target: string; readonly request_digest: string }>` SELECT target, request_digest FROM j5_a2a_request_replay WHERE id = ${input.id} `; - const original = rows[0]; - if (original === undefined || original.request_digest !== digest) - return yield* new RequestReplayConflictError({ - target: original?.target ?? input.target, - legacy: original === undefined, - }); - }, sql.withTransaction); + const original = rows[0]; + if (original === undefined || original.request_digest !== digest) + return yield* new RequestReplayConflictError({ + target: original?.target ?? input.target, + legacy: original === undefined, + }); + }, + sql.withTransaction, + ); return RequestReplayService.of({ bind, check }); }), ); diff --git a/apps/server/src/j5/a2a/mcp/handlers.ts b/apps/server/src/j5/a2a/mcp/handlers.ts index fee11c266d67b..9675c8f3cf86c 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -28,7 +28,10 @@ import { } from "../../../mcp/threadAccess.ts"; import { OrchestratorMcpService } from "../../../mcp/OrchestratorMcpService.ts"; import { claimPendingAttachments } from "../../../orchestration-v2/AttachmentClaims.ts"; -import { exceededDispatchModeLimit } from "../../../orchestration-v2/DispatchModeLimit.ts"; +import { + type DispatchModes, + exceededDispatchModeLimit, +} from "../../../orchestration-v2/DispatchModeLimit.ts"; import { OrchestratorV2 } from "../../../orchestration-v2/Orchestrator.ts"; import { ThreadManagementService, @@ -1035,7 +1038,10 @@ const handlers = { const replayService = yield* RequestReplayService; const replayFailure = (error: { readonly message: string }) => stateError(error.message, "Inspect the original target before starting new work."); - yield* replayService.check(threadId, request).pipe(Effect.mapError(replayFailure)); + // A generated key can never be retried, so it has nothing to bind. + const replayable = input.client_request_id !== undefined; + if (replayable) + yield* replayService.check(threadId, request).pipe(Effect.mapError(replayFailure)); const selected = existing?.modelSelection ?? (yield* selectSpawnModel(scope, input)); const personaId = input.persona; const persona = @@ -1086,16 +1092,22 @@ const handlers = { // A retry finishes the agent its first attempt created, in the modes it was created with. // A caller's modes can be narrowed within one provider session, so those are checked // against what the caller may touch now. A persona's agent runs under its own policy, - // except for an outside agent, whose approved level caps every agent it starts. - if (existing !== null && (personaId === undefined || outside !== undefined)) { - const exceeded = exceededDispatchModeLimit(limits, existing); - if (exceeded !== undefined) { - return yield* stateError( - `client_request_id ${requestKey} already created an agent whose ${exceeded === "runtime" ? "permission" : "interaction"} mode is broader than yours is now.`, - "Ask the user to start that agent, or spawn a new one with a fresh client_request_id.", - ); - } - } + // except for an outside agent, whose approved level caps every agent it starts. This early + // check is the only one an unbound legacy agent reaches, since bind refuses it before the + // start; the start checks again for an agent a concurrent attempt created since. + const replayExceedsCaller = (caller: DispatchModes, thread: DispatchModes) => { + if (personaId !== undefined && outside === undefined) return Effect.void; + const exceeded = exceededDispatchModeLimit(caller, thread); + return exceeded === undefined + ? Effect.void + : Effect.fail( + stateError( + `Peer Agent ${participantIdForThread(threadId)} already exists with a ${exceeded === "runtime" ? "permission" : "interaction"} mode broader than yours is now.`, + "Ask the user to start that agent, or spawn a new one with a fresh client_request_id.", + ), + ); + }; + if (existing !== null) yield* replayExceedsCaller(limits, existing); // The project the agent joins: the caller's, another one, or upstream's "No project". if (input.scratch === true && input.project_id !== undefined) { @@ -1193,14 +1205,15 @@ const handlers = { stateError(`Peer Agent was not created: ${error.detail}`, error.nextStep), ), ); - yield* replayService - .bind({ - id: threadId, - target: `Peer Agent ${participantIdForThread(threadId)} on thread ${threadId}`, - request, - legacy: existing !== null, - }) - .pipe(Effect.mapError(replayFailure)); + if (replayable) + yield* replayService + .bind({ + id: threadId, + target: `Peer Agent ${participantIdForThread(threadId)} on thread ${threadId}`, + request, + legacy: existing !== null, + }) + .pipe(Effect.mapError(replayFailure)); return yield* spawnWorkspace .withSpawnStart( { stableInput, threadId, workspace }, @@ -1214,14 +1227,7 @@ const handlers = { const current = yield* threadManagement .getThreadShell(threadId) .pipe(Effect.mapError(spawnReadFailure)); - if (current !== null && (personaId === undefined || outside !== undefined)) { - const exceeded = exceededDispatchModeLimit((yield* loadCaller()).limits, current); - if (exceeded !== undefined) - return yield* stateError( - `Peer Agent ${participantIdForThread(threadId)} has modes broader than yours is now.`, - "Ask the user to start that agent, or use a fresh client_request_id.", - ); - } + if (current !== null) yield* replayExceedsCaller((yield* loadCaller()).limits, current); const sharedCheckout = current !== null ? current diff --git a/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index 367449522d221..abc937c6a5901 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -564,7 +564,7 @@ export const J5ArchiveCrewFailure = Schema.Struct({ export type J5ArchiveCrewFailure = typeof J5ArchiveCrewFailure.Type; export const J5_SPAWN_AGENT_DESCRIPTION = - "Spawn a Peer Agent: a full-citizen teammate with its own top-level thread, starting on your brief as its first turn. It joins your project unless you name another with project_id or set scratch for none, and records you as its immutable spawner; in your own project it is placed under you. It is addressable the moment this returns. In your brief, tell the new agent what it should do first and whether it should reply to you. Choose provider, model, and reasoning for the work in the brief — see orchestrator_capabilities for what's available. To run a persona from j5_list_personas, set `persona` to its id: the spawn gets that persona's instructions and runtime policy, and provider, model, and reasoning must be one of that persona's declared routes. Without a persona it runs in your permission and interaction modes, or in narrower ones you set with runtime_mode and interaction_mode. Attach files to the brief with attachments. Choose its workspace every time (see the workspace field). A new worktree is prepared after this returns, and the agent begins once it is bound, possibly while the project's setup script is still running; if preparing it fails, the agent's thread shows why, and it is not retried. Reuse client_request_id to retry the same spawn safely; a retry replays the first spawn, so a different base_ref or worktree_path needs a fresh client_request_id."; + "Spawn a Peer Agent: a full-citizen teammate with its own top-level thread, starting on your brief as its first turn. It joins your project unless you name another with project_id or set scratch for none, and records you as its immutable spawner; in your own project it is placed under you. It is addressable the moment this returns. In your brief, tell the new agent what it should do first and whether it should reply to you. Choose provider, model, and reasoning for the work in the brief — see orchestrator_capabilities for what's available. To run a persona from j5_list_personas, set `persona` to its id: the spawn gets that persona's instructions and runtime policy, and provider, model, and reasoning must be one of that persona's declared routes. Without a persona it runs in your permission and interaction modes, or in narrower ones you set with runtime_mode and interaction_mode. Attach files to the brief with attachments. Choose its workspace every time (see the workspace field). A new worktree is prepared after this returns, and the agent begins once it is bound, possibly while the project's setup script is still running; if preparing it fails, the agent's thread shows why, and it is not retried. Reuse client_request_id to retry the same spawn safely; reusing it with any change to the request is refused, so use a fresh one for new work."; export const J5_LIST_AGENTS_DESCRIPTION = "List the personas in this environment: id, purpose, runtime policy, whether each can start now, and the provider, model, and reasoning it would run on. Read this before choosing a persona for j5_spawn_agent or a crew roster so the choice fits the task and the user's budget. Read-only."; diff --git a/apps/server/src/j5/a2a/migrations/039_RequestReplay.ts b/apps/server/src/j5/a2a/migrations/039_RequestReplay.ts index f81e50d6118e6..e96c8651094c6 100644 --- a/apps/server/src/j5/a2a/migrations/039_RequestReplay.ts +++ b/apps/server/src/j5/a2a/migrations/039_RequestReplay.ts @@ -8,7 +8,8 @@ export default Effect.gen(function* () { CREATE TABLE j5_a2a_request_replay ( id TEXT PRIMARY KEY NOT NULL, target TEXT NOT NULL, - request_digest TEXT NOT NULL + request_digest TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) ) `; }); diff --git a/apps/server/src/j5/a2a/spawnWorkspace.test.ts b/apps/server/src/j5/a2a/spawnWorkspace.test.ts index 90d056ce48aa6..04852a83c2de2 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.test.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.test.ts @@ -1012,6 +1012,24 @@ it.effect("an explicit shared workspace keeps the caller's checkout and starts t }), ); +it.effect("records no replay binding for a spawn without client_request_id", () => + Effect.gen(function* () { + const unused = Effect.die(new Error("a keyless spawn has no retry key to bind")); + const replay = Layer.succeed( + RequestReplayService, + RequestReplayService.of({ check: () => unused, bind: () => unused }), + ); + const { layer, call } = yield* spawnHarness({ + checkout: { isRepo: true, refName: "j5/main" }, + replay, + }); + const spawned = yield* call({ ...spawnArgs, workspace: { type: "shared" } }).pipe( + Effect.provide(layer), + ); + assert.isFalse(spawned.isFailure); + }), +); + it.effect("binds a client_request_id to its first workspace type, across a restart", () => Effect.gen(function* () { const replayContext = yield* Layer.build(requestReplayLayer.pipe(Layer.provide(layerMemory))); From 0fff0c5719ebc80d22ebf04830c0bf8945f66b92 Mon Sep 17 00:00:00 2001 From: Bastian Huppertz Date: Tue, 20 Oct 2026 15:15:54 +0200 Subject: [PATCH 4/9] fix(j5): refuse bad spawn attachments before binding the key Duplicate attachment ids, attachment limits and non-pending references are refused before the client_request_id is bound, so a corrected list can be retried under the same key instead of being refused as a changed request. A replay-store SQL failure now tells the caller to retry the same key, keeping the inspect-target guidance for real conflicts. The agent tools doc states the whole-request binding. --- apps/server/src/j5/a2a/mcp/handlers.ts | 37 +++++++++- apps/server/src/j5/a2a/spawnWorkspace.test.ts | 73 +++++++++++++++++++ docs/j5/product/a2a/agent-tools.md | 4 +- 3 files changed, 108 insertions(+), 6 deletions(-) diff --git a/apps/server/src/j5/a2a/mcp/handlers.ts b/apps/server/src/j5/a2a/mcp/handlers.ts index 9675c8f3cf86c..5c624a131931c 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -12,6 +12,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; +import type { SqlError } from "effect/sql/SqlError"; import { McpInvocationContext, @@ -27,7 +28,11 @@ import { loadCaller, } from "../../../mcp/threadAccess.ts"; import { OrchestratorMcpService } from "../../../mcp/OrchestratorMcpService.ts"; -import { claimPendingAttachments } from "../../../orchestration-v2/AttachmentClaims.ts"; +import { + AttachmentClaimError, + claimPendingAttachments, + validateAttachmentLimits, +} from "../../../orchestration-v2/AttachmentClaims.ts"; import { type DispatchModes, exceededDispatchModeLimit, @@ -79,7 +84,7 @@ import { actsAsThreadCaller, } from "./outsideAgent.ts"; import { SpawnCompositionService } from "../SpawnCompositionService.ts"; -import { RequestReplayService } from "../RequestReplayService.ts"; +import { type RequestReplayConflictError, RequestReplayService } from "../RequestReplayService.ts"; import { SpawnWorkspaceService, namedBaseRefs, @@ -1036,12 +1041,36 @@ const handlers = { workspace: workspaceRequest, }; const replayService = yield* RequestReplayService; - const replayFailure = (error: { readonly message: string }) => - stateError(error.message, "Inspect the original target before starting new work."); + const replayFailure = (error: SqlError | RequestReplayConflictError) => + error._tag === "RequestReplayConflictError" + ? stateError(error.message, "Inspect the original target before starting new work.") + : stateError( + `The spawn's client_request_id could not be checked: ${error.message}`, + "Retry j5_spawn_agent with the same client_request_id.", + ); // A generated key can never be retried, so it has nothing to bind. const replayable = input.client_request_id !== undefined; if (replayable) yield* replayService.check(threadId, request).pipe(Effect.mapError(replayFailure)); + // What the request alone decides about its attachments is refused before the key is bound, + // so a corrected list can be retried under the same client_request_id. + if (input.attachments !== undefined) { + const attachments = input.attachments; + yield* resolveAttachmentReferences(attachments, []).pipe( + Effect.flatMap(validateAttachmentLimits), + Effect.andThen( + new Set(attachments.map((attachment) => attachment.id)).size === attachments.length + ? Effect.void + : new AttachmentClaimError({ message: "Duplicate attachment ids are not allowed." }), + ), + Effect.mapError((error) => + stateError( + `Peer Agent was not created: ${error.message}`, + "Retry j5_spawn_agent with corrected attachments; the same client_request_id still works.", + ), + ), + ); + } const selected = existing?.modelSelection ?? (yield* selectSpawnModel(scope, input)); const personaId = input.persona; const persona = diff --git a/apps/server/src/j5/a2a/spawnWorkspace.test.ts b/apps/server/src/j5/a2a/spawnWorkspace.test.ts index 04852a83c2de2..700194db67d9b 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.test.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.test.ts @@ -27,6 +27,7 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Result from "effect/Result"; import * as Sink from "effect/Sink"; +import { SqlError, UnknownError } from "effect/sql/SqlError"; import * as Stream from "effect/Stream"; import { McpInvocationContext, type McpInvocationScope } from "../../mcp/McpInvocationContext.ts"; @@ -942,6 +943,78 @@ it.effect("claims the brief's attachments into the new agent's thread", () => }), ); +it.effect( + "refuses invalid attachments before binding, so the same key takes a corrected list", + () => + Effect.gen(function* () { + const { layer, call, commands } = yield* spawnHarness({ + checkout: { isRepo: true, refName: "j5/main" }, + }); + yield* Effect.gen(function* () { + const config = yield* ServerConfig; + const fs = yield* FileSystem.FileSystem; + const attachment = { + type: "image" as const, + id: ChatAttachmentId.make(createPendingAttachmentId()!), + name: "screen.png", + mimeType: "image/png", + sizeBytes: 3, + }; + yield* fs.writeFile( + resolveAttachmentPath({ attachmentsDir: config.attachmentsDir, attachment })!, + new Uint8Array([1, 2, 3]), + ); + const args = { + ...spawnArgs, + workspace: { type: "shared" as const }, + client_request_id: "duplicate-attachments", + }; + const duplicated = yield* call({ ...args, attachments: [attachment, attachment] }); + assert.isTrue(duplicated.isFailure); + assert.include(message(duplicated), "Duplicate attachment ids"); + assert.lengthOf(yield* Ref.get(commands), 0, "nothing is created"); + + const corrected = yield* call({ ...args, attachments: [attachment] }); + assert.isFalse(corrected.isFailure); + const brief = (yield* Ref.get(commands)).find( + (command) => command.type === "message.dispatch", + ); + assert.lengthOf(brief?.type === "message.dispatch" ? brief.attachments : [], 1); + + const changed = yield* call(args); + assert.isTrue(changed.isFailure); + assert.include(message(changed), "different request"); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("tells a caller to retry the same key when the replay store cannot be read", () => + Effect.gen(function* () { + const unreadable = Effect.fail( + new SqlError({ reason: new UnknownError({ cause: new Error("disk I/O error") }) }), + ); + const replay = Layer.succeed( + RequestReplayService, + RequestReplayService.of({ check: () => unreadable, bind: () => unreadable }), + ); + const { layer, call, commands } = yield* spawnHarness({ + checkout: { isRepo: true, refName: "j5/main" }, + replay, + }); + yield* Effect.gen(function* () { + const failed = yield* call({ + ...spawnArgs, + workspace: { type: "shared" }, + client_request_id: "storage-down", + }); + assert.isTrue(failed.isFailure); + assert.include(message(failed), "Retry j5_spawn_agent with the same client_request_id"); + assert.notInclude(message(failed), "Inspect the original target"); + assert.lengthOf(yield* Ref.get(commands), 0); + }).pipe(Effect.provide(layer)); + }), +); + it.effect("spawns into a new worktree from base_ref, keeping home, placement, and result", () => Effect.gen(function* () { const { layer, call, log, commands, launches } = yield* spawnHarness({ diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index 13ccf802f97a8..a96d4614f5aaa 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -117,11 +117,11 @@ fresh client_request_id." **Rules.** The new agent is an ordinary root-lineage thread created through upstream's creation seam, never through delegation. It is created in the caller's project unless the caller names another with `project_id` or sets `scratch`, and it joins that project's ledger. An [outside agent](index.md#participants) has no project, so it passes one of the two on every spawn. These are what upstream's own launch tool offers and J5's lacked (Jackson, 2026-10-11). In another project the caller is still recorded as the spawner, but the placement tree is one project's, so the agent is a root there and stays at the top level of the sidebar. An outside agent is in no project's tree, so every agent it starts is a root, with the outside agent's `outside:` id recorded as its spawner. Without a persona the agent runs in the caller's permission and interaction modes, or in ones the caller chose, which may be no broader than the caller's own. For an outside agent the caller's modes are the level its sign-in was approved at, and a read-only sign-in spawns nothing. A persona's policy sets its permissions. For a thread caller it has no ceiling (2026-09-16). For an outside agent it must be within the approved level, because that level is a promise the approval page makes about an agent the person does not watch. Either caller may still choose a narrower interaction mode for a persona. A retry finishes the agent its first attempt created, in the modes it was created with, so it is refused when those are now broader than the caller's own; a caller's modes can be narrowed between the two. An outside agent's retry keys belong to its sign-in, whose level never changes. `attachments` are pending uploads, claimed into the new thread once it exists and carried by the brief. Placement and provenance are recorded atomically with creation; then the brief starts as the first turn. The new agent's first turn also states its own participant id and project as platform-provided facts, beside the brief and never inside it. When an outside agent started it, those facts name the outside agent by its label and say that `j5_send_message` cannot reply to it. Provider, model and reasoning are required and explicit even when a Role is given: a Role's allowlist constrains the choice and an out-of-list pick is an error naming the Role, never a silent default. The brief carries the task and the reply expectation; the spawner does not follow a spawn with a reply-expected `j5_send_message` — that form is for later work owed by an existing participant. Selection guidance and brief-writing conventions live in the [Spawning Guide](../features/spawning-guide.md). -**Workspace.** The spawner chooses where a Peer Agent works every time; there is no default, because the spawner knows whether it is starting a reviewer that must see uncommitted work, a builder that must not collide, or a scout that can't collide at all (Jackson, 2026-10-03). `{type: "shared"}` is the caller's own checkout and branch, and asks nothing of git; it is refused for an agent that joins another project, and for an outside agent, which has no checkout. `{type: "root"}` is the project's main checkout, upstream's name for it, and the only choice with `scratch`. As upstream's launch does, a main-checkout thread in the "No project" project gets a fresh folder of its own, whether the caller set `scratch` or named that project by its id. `{type: "worktree"}` is a new worktree from `base_ref`, which is required and must resolve to a commit (with `start_from_origin`, its fetched origin copy counts); a `branch` that already exists is refused. `{type: "existing_worktree"}` is one of the project's git worktrees other than its main checkout, named by path; the agent works on the branch git has checked out there, and any other path is refused with the valid ones listed. A choice that needs git is refused when the repository can't be read, before anything is created. A new worktree's thread is created unbound, with its registration and placement committed, so `j5_spawn_agent` returns as soon as the agent is registered and its brief accepted, not once the worktree is ready. Upstream's ThreadLaunch then creates the worktree, names a temporary `j5code/` branch and renames it from the brief in the background, and holds the brief as a preparing run until the worktree is bound and the project's setup script has started. The setup script is awaited first only when it is set to finish before the agent starts (`async: false`); otherwise the agent may begin while it is still running. If preparation fails, the agent's thread shows the failed preparation, as any upstream launch does; it is not retried or retired, and the spawner is not told. The agent is then unbound, which upstream reads as the project's checkout, so a later message to it runs there, where every Peer Agent worked before workspaces existed. J5 doesn't guard this upstream behaviour: in Jackson's install, 3 of 61 preparations failed, all on the first day, and none was messaged again (Jackson, 2026-10-06). A shared checkout or an existing worktree binds at creation, so its brief starts at once. A `client_request_id` stays bound to the workspace type it was first accepted with: a retry that asks for another type is refused before anything is dispatched, even after a restart, since the type is encoded in the create command's durable receipt. `shared` and `root` are one type for this: neither binds anything through git, so a retry that switches between them is not refused, and replays the checkout its first attempt bound. A retry with the same type replays the first spawn, so a different `base_ref` or `worktree_path` has no effect, for an existing worktree too; changing them needs a fresh `client_request_id`. A second start for the same thread while one is in flight is refused with a retry instruction, so two concurrent retries cannot both create it. An existing worktree is looked up in upstream's ref listing, which refreshes every few seconds, so one created moments ago may be refused once; retry in a moment. Closing or archiving a Peer Agent never removes its worktree. +**Workspace.** The spawner chooses where a Peer Agent works every time; there is no default, because the spawner knows whether it is starting a reviewer that must see uncommitted work, a builder that must not collide, or a scout that can't collide at all (Jackson, 2026-10-03). `{type: "shared"}` is the caller's own checkout and branch, and asks nothing of git; it is refused for an agent that joins another project, and for an outside agent, which has no checkout. `{type: "root"}` is the project's main checkout, upstream's name for it, and the only choice with `scratch`. As upstream's launch does, a main-checkout thread in the "No project" project gets a fresh folder of its own, whether the caller set `scratch` or named that project by its id. `{type: "worktree"}` is a new worktree from `base_ref`, which is required and must resolve to a commit (with `start_from_origin`, its fetched origin copy counts); a `branch` that already exists is refused. `{type: "existing_worktree"}` is one of the project's git worktrees other than its main checkout, named by path; the agent works on the branch git has checked out there, and any other path is refused with the valid ones listed. A choice that needs git is refused when the repository can't be read, before anything is created. A new worktree's thread is created unbound, with its registration and placement committed, so `j5_spawn_agent` returns as soon as the agent is registered and its brief accepted, not once the worktree is ready. Upstream's ThreadLaunch then creates the worktree, names a temporary `j5code/` branch and renames it from the brief in the background, and holds the brief as a preparing run until the worktree is bound and the project's setup script has started. The setup script is awaited first only when it is set to finish before the agent starts (`async: false`); otherwise the agent may begin while it is still running. If preparation fails, the agent's thread shows the failed preparation, as any upstream launch does; it is not retried or retired, and the spawner is not told. The agent is then unbound, which upstream reads as the project's checkout, so a later message to it runs there, where every Peer Agent worked before workspaces existed. J5 doesn't guard this upstream behaviour: in Jackson's install, 3 of 61 preparations failed, all on the first day, and none was messaged again (Jackson, 2026-10-06). A shared checkout or an existing worktree binds at creation, so its brief starts at once. A `client_request_id` is bound to the whole request it was first accepted with, before anything is created, and the binding survives a restart. A retry with any change, including another workspace, `base_ref` or `worktree_path`, is refused, naming the agent the first attempt created; new work needs a fresh `client_request_id`. A request refused before it is accepted, such as one with duplicate attachment ids or an unusable workspace, binds nothing, so it can be corrected under the same key. An agent spawned before requests were bound cannot be compared, so a retry of it is refused too. A second start for the same thread while one is in flight is refused with a retry instruction, so two concurrent retries cannot both create it. An existing worktree is looked up in upstream's ref listing, which refreshes every few seconds, so one created moments ago may be refused once; retry in a moment. Closing or archiving a Peer Agent never removes its worktree. **Result:** the new agent's `participant_id` and `thread_id`, its `project_id` and `project_title`, and its placement with the caller recorded as spawner: under the caller in the caller's own project, and with no parent in another or when the caller is an outside agent. -**Errors**, each naming state and next command: the caller is a provider Subagent; the caller's membership is missing or ambiguous; the caller's project ledger cannot be read; the caller sits in a Crew (naming its Captain as the escalation and `delegate_task` for its own subagents; only a Captain grows a Crew, through the gate); the chosen workspace can't be used (a path that isn't one of the project's worktrees, a `base_ref` that doesn't resolve, a `branch` that exists, an unreadable repository); the `client_request_id` is bound to another workspace type, or a start for it is already in flight; creation failed. For an outside agent: no `project_id` and no `scratch` (naming `t3_project_list`); the `shared` workspace (naming the three it may choose); a persona whose policy is broader than the approved level (naming the level, and a persona within it or a new sign-in at a higher level). +**Errors**, each naming state and next command: the caller is a provider Subagent; the caller's membership is missing or ambiguous; the caller's project ledger cannot be read; the caller sits in a Crew (naming its Captain as the escalation and `delegate_task` for its own subagents; only a Captain grows a Crew, through the gate); the chosen workspace can't be used (a path that isn't one of the project's worktrees, a `base_ref` that doesn't resolve, a `branch` that exists, an unreadable repository); the `client_request_id` is bound to a different request, or a start for it is already in flight; creation failed. For an outside agent: no `project_id` and no `scratch` (naming `t3_project_list`); the `shared` workspace (naming the three it may choose); a persona whose policy is broader than the approved level (naming the level, and a persona within it or a new sign-in at a higher level). **Events:** participant joined, placement created. From 1a02387d2f8e49390638052f664530a53b443b8c Mon Sep 17 00:00:00 2001 From: Bastian Huppertz Date: Wed, 21 Oct 2026 17:43:51 +0200 Subject: [PATCH 5/9] fix(j5): reject changed Crew proposal replay requests (#661) * fix(j5): reject changed crew proposal replay requests Compare immutable original proposal fields before live validation and again after concurrent create/admit. Identical retries retain the original proposal after approval, decline, catalog changes and partial failures. Keep the existing stable ids and admission rules. Replay omits the optional live-validation playbook summary. Existing ambiguous or archived crew target selection still refuses visibly. Co-Authored-By: GPT-6.1-Sol Co-Authored-By: Claude Opus 5.5 * fix(server): replay crew proposals before playbook lookup * fix(j5): simplify crew proposal replay comparison * fix(j5): preserve replay workspace for playbook libraries * test(j5): verify crew replay against playbook libraries --------- Co-authored-by: GPT-6.1-Sol Co-authored-by: Claude Opus 5.5 --- .../j5/a2a/AgentCrewProposalService.test.ts | 37 + .../src/j5/a2a/AgentCrewProposalService.ts | 17 +- .../src/j5/a2a/CrewProposalService.test.ts | 669 +++++++++++++++++- apps/server/src/j5/a2a/CrewProposalService.ts | 190 +++-- apps/server/src/j5/a2a/Migrations.test.ts | 45 +- apps/server/src/j5/a2a/Migrations.ts | 2 + .../src/j5/a2a/RequestReplayService.test.ts | 6 +- .../server/src/j5/a2a/RequestReplayService.ts | 25 +- .../045_CrewPlaybookRequestWorkspace.ts | 7 + apps/server/src/j5/a2a/spawnWorkspace.ts | 2 +- 10 files changed, 917 insertions(+), 83 deletions(-) create mode 100644 apps/server/src/j5/a2a/migrations/045_CrewPlaybookRequestWorkspace.ts diff --git a/apps/server/src/j5/a2a/AgentCrewProposalService.test.ts b/apps/server/src/j5/a2a/AgentCrewProposalService.test.ts index 14995ab22f105..59f2d0792b58d 100644 --- a/apps/server/src/j5/a2a/AgentCrewProposalService.test.ts +++ b/apps/server/src/j5/a2a/AgentCrewProposalService.test.ts @@ -299,3 +299,40 @@ it.effect( ), ), ); + +it.effect("upgrades playbook proposals without inventing their request workspace", () => + Effect.gen(function* () { + yield* runJ5A2AMigrations({ toMigrationInclusive: 39 }); + yield* (yield* A2ALedger).ensureProject({ projectId, createdAt }); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO j5_agent_crew_proposal ( + id, project_id, captain_participant_id, captain_thread_id, kind, status, + brief, display_name, requested_seats, created_at, playbook_name, playbook_definition_path + ) VALUES ( + 'legacy', ${projectId}, ${captain}, ${captainThreadId}, 'roster', 'open', + 'Original', 'Legacy', '[]', ${createdAt}, 'release', '/repo/.j5/playbooks/release.yaml' + )`; + yield* runJ5A2AMigrations(); + const proposals = yield* AgentCrewProposalService; + const legacy = yield* proposals.read("legacy"); + assert.deepStrictEqual(legacy?.playbook, { + name: "release", + definitionPath: "/repo/.j5/playbooks/release.yaml", + }); + const current = yield* proposals.create({ + ...addition("current", "unused", []), + kind: "roster", + crewInstanceId: null, + playbook: { + name: "release", + definitionPath: "/library/release.yaml", + requestWorkspaceRoot: "/repo", + }, + }); + const reloaded = yield* proposals.read(current.id); + assert.deepStrictEqual(reloaded?.playbook, current.playbook); + assert.equal(reloaded?.playbook?.requestWorkspaceRoot, "/repo"); + yield* runJ5A2AMigrations(); + assert.deepStrictEqual(yield* proposals.read("legacy"), legacy); + }).pipe(Effect.provide(testLayer)), +); diff --git a/apps/server/src/j5/a2a/AgentCrewProposalService.ts b/apps/server/src/j5/a2a/AgentCrewProposalService.ts index 938cdc46010b7..a9a2234ece533 100644 --- a/apps/server/src/j5/a2a/AgentCrewProposalService.ts +++ b/apps/server/src/j5/a2a/AgentCrewProposalService.ts @@ -48,10 +48,12 @@ export const CrewProposalSeat = Schema.Struct({ }); export type CrewProposalSeat = typeof CrewProposalSeat.Type; -/** The playbook a Crew follows. The definition path is its identity; the name is for display. */ +/** The resolved playbook a Crew follows, with optional original request context for replay. */ export interface CrewPlaybookRef { readonly name: string; readonly definitionPath: string; + /** Normalized request workspace, independent of the live library selection. */ + readonly requestWorkspaceRoot?: string | undefined; } const Seats = Schema.Array(CrewProposalSeat); @@ -179,6 +181,7 @@ interface Row { readonly decided_by: string | null; readonly playbook_name: string | null; readonly playbook_definition_path: string | null; + readonly playbook_request_workspace_root: string | null; } const fromRow = (row: Row): CrewProposal => ({ @@ -200,7 +203,13 @@ const fromRow = (row: Row): CrewProposal => ({ playbook: row.playbook_name === null || row.playbook_definition_path === null ? null - : { name: row.playbook_name, definitionPath: row.playbook_definition_path }, + : { + name: row.playbook_name, + definitionPath: row.playbook_definition_path, + ...(row.playbook_request_workspace_root === null + ? {} + : { requestWorkspaceRoot: row.playbook_request_workspace_root }), + }, }); export const layer: Layer.Layer = @@ -223,13 +232,13 @@ export const layer: Layer.Layer; + readonly beforeAdmit?: Effect.Effect; + readonly afterCreate?: Effect.Effect; + readonly afterAdmit?: Effect.Effect; + } = {}, +) { + const database = NodeSqliteClient.layer({ filename }); const storage = Layer.mergeAll(crewInstanceLayer, proposalStoreLayer, ledgerLayer).pipe( Layer.provideMerge(database), ); @@ -331,6 +341,16 @@ const fixture = Effect.gen(function* () { const store = Context.get(context, AgentCrewProposalService); const flakyStore = Layer.succeed(AgentCrewProposalService, { ...store, + create: (input) => + (options.beforeCreate ?? Effect.void).pipe( + Effect.andThen(store.create(input)), + Effect.tap(() => options.afterCreate ?? Effect.void), + ), + admit: (input, limits) => + (options.beforeAdmit ?? Effect.void).pipe( + Effect.andThen(store.admit(input, limits)), + Effect.tap(() => options.afterAdmit ?? Effect.void), + ), resolve: (input) => Ref.get(resolveFailure).pipe( Effect.flatMap((failing) => (failing ? Effect.succeed(null) : store.resolve(input))), @@ -340,7 +360,9 @@ const fixture = Effect.gen(function* () { Effect.flatMap((failing) => failing ? Effect.fail( - new SqlError({ reason: new UnknownError({ cause: new Error("disk I/O error") }) }), + new SqlError({ + reason: new UnknownError({ cause: new Error("disk I/O error") }), + }), ) : store.attachInstance(id, crewInstanceId), ), @@ -420,6 +442,8 @@ const fixture = Effect.gen(function* () { }; }); +const fixture = fixtureWithDatabase(":memory:"); + it.effect("reports what the person decided about a roster, and what they changed first", () => Effect.gen(function* () { const { layer } = yield* fixture; @@ -1785,6 +1809,7 @@ it.effect( assert.deepStrictEqual(stored.playbook, { name: "release", definitionPath: `${workspaceRoot}/.j5/playbooks/release.yaml`, + requestWorkspaceRoot: workspaceRoot, }); assert.deepStrictEqual( stored.requestedSeats.map(({ seat, steps }) => [seat, steps]), @@ -1799,7 +1824,10 @@ it.effect( decision: "approve", }); const instance = (yield* crews.read(approved.instance!.id))!; - assert.deepStrictEqual(instance.playbook, stored.playbook); + assert.deepStrictEqual(instance.playbook, { + name: stored.playbook!.name, + definitionPath: stored.playbook!.definitionPath, + }); assert.deepStrictEqual( instance.members.map(({ seatName, playbookStepIds }) => [seatName, playbookStepIds]), [ @@ -2340,7 +2368,10 @@ it.effect( approvalToken: preview.approvalToken, }); const instance = (yield* (yield* AgentCrewInstanceService).read(approved.instance!.id))!; - assert.deepStrictEqual(instance.playbook, stored.playbook); + assert.deepStrictEqual(instance.playbook, { + name: stored.playbook!.name, + definitionPath: stored.playbook!.definitionPath, + }); assert.deepStrictEqual( instance.members.map(({ seatName, playbookStepIds }) => [seatName, playbookStepIds]), [ @@ -2412,3 +2443,631 @@ it.effect( }).pipe(Effect.provide(layer)); }).pipe(Effect.scoped), ); + +it.effect.each(["approve", "decline"] as const)( + "replays the requested roster after %s and human edits", + (decision) => + Effect.gen(function* () { + const { layer, notices } = yield* fixture; + yield* Effect.gen(function* () { + const gate = withPreview(yield* CrewProposalService); + const store = yield* AgentCrewProposalService; + const input = { + requestKey: "roster-replay", + captain, + displayName: "Replay Crew", + brief: "Original brief", + seats: [custom("writer")], + }; + const original = yield* gate.propose(input); + const replay = yield* gate.propose(input); + assert.equal(replay.proposal.id, original.proposal.id); + for (const change of [ + { displayName: "Changed" }, + { brief: "Changed" }, + { seats: [{ ...input.seats[0]!, reason: "Changed" }] }, + { seats: [{ ...input.seats[0]!, instructions: "Changed" }] }, + { + seats: [ + { + ...input.seats[0]!, + modelSelection: { instanceId: ProviderInstanceId.make("other"), model: "other" }, + }, + ], + }, + { + seats: [ + { ...input.seats[0]!, workspace: { type: "worktree" as const, baseRef: "main" } }, + ], + }, + ]) { + const refused = yield* gate.propose({ ...input, ...change }).pipe(Effect.flip); + assert.equal(refused._tag, "CrewProposalRequestError"); + assert.include(refused.message, original.proposal.id); + assert.include(refused.message, "fresh client_request_id"); + } + assert.lengthOf(yield* store.listForCaptain(captainId), 1); + assert.lengthOf(yield* Ref.get(notices), 0); + const resolved = yield* gate.resolve({ + proposalId: original.proposal.id, + decision, + ...(decision === "approve" ? { seats: [custom("editor")] } : {}), + }); + const noticesBefore = yield* Ref.get(notices); + const finalReplay = yield* gate.propose(input); + assert.equal(finalReplay.proposal.id, original.proposal.id); + assert.equal(finalReplay.proposal.status, resolved.proposal.status); + assert.equal(finalReplay.instance?.id ?? null, resolved.instance?.id ?? null); + assert.deepStrictEqual(yield* Ref.get(notices), noticesBefore); + if (decision === "approve") { + assert.equal(finalReplay.proposal.approvedSeats?.[0]?.seat, "editor"); + const changed = yield* gate + .propose({ ...input, seats: [custom("editor")] }) + .pipe(Effect.flip); + assert.include(changed.message, "different request"); + } + }).pipe(Effect.provide(layer)); + }), +); + +it.effect.each(["approve", "decline"] as const)( + "replays an addition after %s with the original crew and omitted brief", + (decision) => + Effect.gen(function* () { + const { layer, notices } = yield* fixture; + yield* Effect.gen(function* () { + const gate = withPreview(yield* CrewProposalService); + const firstCrew = yield* seedCrew(gate, "first-crew", 1); + const secondCrew = yield* seedCrew(gate, "second-crew", 1); + const input = { + requestKey: "addition-replay", + captain, + crewInstanceId: firstCrew.id, + brief: null, + seat: custom("writer"), + }; + const original = yield* gate.requestMember(input); + assert.equal(original.proposal.brief, firstCrew.brief); + for (const change of [ + { crewInstanceId: secondCrew.id }, + { brief: "Changed" }, + { seat: { ...input.seat, reason: "Changed" } }, + { seat: { ...input.seat, instructions: "Changed" } }, + { seat: { ...input.seat, workspace: { type: "worktree" as const, baseRef: "main" } } }, + ]) { + const refused = yield* gate.requestMember({ ...input, ...change }).pipe(Effect.flip); + assert.equal(refused._tag, "CrewProposalRequestError"); + assert.include(refused.message, original.proposal.id); + assert.include(refused.message, firstCrew.id); + assert.include(refused.message, "fresh client_request_id"); + } + const resolved = yield* gate.resolve({ + proposalId: original.proposal.id, + decision, + ...(decision === "approve" ? { seats: [custom("editor")] } : {}), + }); + const noticesBefore = yield* Ref.get(notices); + const replay = yield* gate.requestMember(input); + assert.equal(replay.proposal.id, original.proposal.id); + assert.equal(replay.proposal.status, resolved.proposal.status); + assert.equal(replay.instance?.id, firstCrew.id); + assert.deepStrictEqual(yield* Ref.get(notices), noticesBefore); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listForCaptain(captainId), 3); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect( + "an identical roster retry survives a disabled persona, while a fresh request is still validated", + () => + Effect.gen(function* () { + const { layer } = yield* fixture; + yield* Effect.gen(function* () { + const stateDir = yield* seedPersonas([{ id: "replay-persona", enabled: true }]); + const library = createAgentPersonaLibrary({ + fs: yield* FileSystem.FileSystem, + path: yield* Path.Path, + stateDir, + }); + const gate = yield* CrewProposalService; + const input = { + requestKey: "persona-replay", + captain, + displayName: "Persona Crew", + brief: "Original", + seats: [{ ...custom("writer"), agentId: "replay-persona" }], + }; + const original = yield* gate.propose(input); + yield* library.setEnabled("replay-persona", false); + assert.equal((yield* gate.propose(input)).proposal.id, original.proposal.id); + const fresh = yield* gate + .propose({ ...input, requestKey: "fresh-persona" }) + .pipe(Effect.flip); + assert.equal(fresh._tag, "CrewProposalRequestError"); + assert.include(fresh.message, "turned off"); + const corrected = yield* gate.propose({ + ...input, + requestKey: "fresh-persona", + seats: [custom("writer")], + }); + assert.notEqual(corrected.proposal.id, original.proposal.id); + const changed = yield* gate.propose({ ...input, brief: "Changed" }).pipe(Effect.flip); + assert.include(changed.message, "different request"); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect( + "replays a playbook proposal before live reads and treats its yaml suffix as equivalent", + () => + Effect.gen(function* () { + const { layer, workspaceRoot, writePlaybook } = yield* playbookFixture; + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const original = yield* proposeRelease(gate, workspaceRoot); + assert.isNotEmpty(original.proposal.requestedSeats[0]?.personaSwaps ?? []); + yield* writePlaybook("release", "title: ["); + const replay = yield* gate.propose({ + requestKey: "release", + captain, + displayName: "Release Crew", + brief: "Ship the change.", + playbook: { name: "release.yaml", workspaceRoot }, + seats: [custom("planner", ["plan"]), custom("builder", ["build"])], + }); + assert.equal(replay.proposal.id, original.proposal.id); + assert.deepStrictEqual(replay.proposal.requestedSeats, original.proposal.requestedSeats); + const fresh = yield* proposeRelease(gate, workspaceRoot, "fresh-release").pipe(Effect.flip); + assert.equal(fresh._tag, "CrewProposalRequestError"); + assert.include(fresh.message, "release"); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listForCaptain(captainId), 1); + yield* writePlaybook("release", stringify(release())); + const corrected = yield* proposeRelease(gate, workspaceRoot, "fresh-release"); + assert.notEqual(corrected.proposal.id, original.proposal.id); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listForCaptain(captainId), 2); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect.each([ + { kind: "roster", different: false }, + { kind: "roster", different: true }, + { kind: "addition", different: false }, + { kind: "addition", different: true }, +] as const)( + "concurrent $kind requests (different=$different) retain one proposal and compare the winning row", + ({ kind, different }) => + Effect.gen(function* () { + const entered = yield* Ref.make(0); + const both = yield* Deferred.make(); + const release = yield* Deferred.make(); + const barrier = Ref.updateAndGet(entered, (count) => count + 1).pipe( + Effect.tap((count) => (count === 2 ? Deferred.succeed(both, undefined) : Effect.void)), + Effect.andThen(Deferred.await(release)), + ); + const { layer } = yield* fixtureWithDatabase( + ":memory:", + kind === "roster" ? { beforeCreate: barrier } : { beforeAdmit: barrier }, + ); + yield* Effect.gen(function* () { + const gate = withPreview(yield* CrewProposalService); + const crew = kind === "addition" ? yield* seedCrew(gate, "nearly-full", 11) : null; + const call = (brief: string) => + kind === "roster" + ? gate.propose({ + requestKey: "same-key", + captain, + displayName: "Concurrent Crew", + brief, + seats: [custom("writer")], + }) + : gate.requestMember({ + requestKey: "same-key", + captain, + crewInstanceId: crew!.id, + brief, + seat: custom("writer"), + }); + const calls = yield* Effect.all( + [ + call("Original").pipe(Effect.result), + call(different ? "Changed" : "Original").pipe(Effect.result), + ], + { concurrency: "unbounded" }, + ).pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.raceFirst( + Deferred.await(both), + Fiber.join(calls).pipe( + Effect.flatMap(() => + Effect.die(new Error("Requests completed before reaching both writes")), + ), + ), + ); + yield* Deferred.succeed(release, undefined); + const results = yield* Fiber.join(calls); + const successes = results.filter(Result.isSuccess); + const failures = results.filter(Result.isFailure); + assert.lengthOf(successes, different ? 1 : 2); + assert.lengthOf(failures, different ? 1 : 0); + const original = successes[0]!.success.proposal; + if (different) { + assert.equal(failures[0]?.failure._tag, "CrewProposalRequestError"); + assert.include(failures[0]!.failure.message, original.id); + assert.include(failures[0]!.failure.message, "fresh client_request_id"); + if (crew !== null) assert.include(failures[0]!.failure.message, crew.id); + } + const proposals = yield* (yield* AgentCrewProposalService).listForCaptain(captainId); + assert.lengthOf(proposals, kind === "addition" ? 2 : 1); + assert.lengthOf( + proposals.filter((proposal) => proposal.id === original.id), + 1, + ); + const replay = + original.kind === "roster" + ? yield* gate.propose({ + requestKey: "same-key", + captain, + displayName: "Concurrent Crew", + brief: original.brief, + seats: [custom("writer")], + }) + : yield* gate.requestMember({ + requestKey: "same-key", + captain, + crewInstanceId: crew!.id, + brief: original.brief, + seat: custom("writer"), + }); + assert.equal(replay.proposal.id, original.id); + if (crew !== null) + assert.lengthOf((yield* (yield* AgentCrewInstanceService).read(crew.id))!.members, 11); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect.each(["roster", "addition"] as const)( + "replays a committed %s after a lost response and database reopen", + (kind) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const filename = path.join(yield* fs.makeTempDirectoryScoped(), "crew-replay.sqlite"); + const failResponse = yield* Ref.make(false); + const loseResponse = Ref.get(failResponse).pipe( + Effect.flatMap((fail) => + fail + ? Effect.fail( + new SqlError({ + reason: new UnknownError({ cause: new Error("response lost after commit") }), + }), + ) + : Effect.void, + ), + ); + const saved = yield* Effect.scoped( + Effect.gen(function* () { + const { layer } = yield* fixtureWithDatabase(filename, { + afterCreate: loseResponse, + afterAdmit: loseResponse, + }); + return yield* Effect.gen(function* () { + const gate = withPreview(yield* CrewProposalService); + const crew = kind === "addition" ? yield* seedCrew(gate, "persisted-crew", 1) : null; + const request = { + requestKey: "persisted-request", + captain, + displayName: "Persisted Crew", + brief: "Original persisted brief", + seats: [custom("writer")], + }; + const memberRequest = { + requestKey: request.requestKey, + captain, + crewInstanceId: crew?.id ?? null, + brief: null, + seat: custom("writer"), + }; + yield* Ref.set(failResponse, true); + const failure = yield* ( + kind === "roster" ? gate.propose(request) : gate.requestMember(memberRequest) + ).pipe(Effect.flip); + assert.equal(failure._tag, "CrewProposalOperationError"); + assert.include(failure.message, "recording the proposal"); + const rows = yield* (yield* AgentCrewProposalService).listForCaptain(captainId); + const original = rows.find((proposal) => proposal.kind === kind)!; + assert.isDefined(original); + assert.equal(original.status, "open"); + assert.lengthOf(rows, kind === "roster" ? 1 : 2); + return { original, request, memberRequest }; + }).pipe(Effect.provide(layer)); + }), + ); + yield* Effect.scoped( + Effect.gen(function* () { + const { layer, notices } = yield* fixtureWithDatabase(filename, { + beforeCreate: Effect.die( + new Error("A persisted retry must read the original instead of creating again"), + ), + beforeAdmit: Effect.die( + new Error("A persisted retry must read the original instead of admitting again"), + ), + }); + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const replay = + kind === "roster" + ? yield* gate.propose(saved.request) + : yield* gate.requestMember(saved.memberRequest); + assert.equal(replay.proposal.id, saved.original.id); + assert.equal(replay.proposal.brief, saved.original.brief); + const changed = yield* ( + kind === "roster" + ? gate.propose({ ...saved.request, brief: "Changed" }) + : gate.requestMember({ ...saved.memberRequest, brief: "Changed" }) + ).pipe(Effect.flip); + assert.equal(changed._tag, "CrewProposalRequestError"); + assert.include(changed.message, saved.original.id); + assert.include(changed.message, "fresh client_request_id"); + assert.lengthOf(yield* Ref.get(notices), 0); + assert.lengthOf( + yield* (yield* AgentCrewProposalService).listForCaptain(captainId), + kind === "roster" ? 1 : 2, + ); + }).pipe(Effect.provide(layer)); + }), + ); + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.effect("validation refusals leave proposal retry keys available for a corrected request", () => + Effect.gen(function* () { + const { layer } = yield* fixture; + yield* Effect.gen(function* () { + const gate = withPreview(yield* CrewProposalService); + const roster = { + requestKey: "corrected-roster", + captain, + displayName: "Corrected Crew", + brief: "Original", + seats: [{ ...custom("writer"), instructions: undefined }], + }; + const refused = yield* gate.propose(roster).pipe(Effect.flip); + assert.equal(refused._tag, "CrewProposalRequestError"); + assert.include(refused.message, "instructions"); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listForCaptain(captainId), 0); + const opened = yield* gate.propose({ ...roster, seats: [custom("writer")] }); + const approved = yield* gate.resolve({ proposalId: opened.proposal.id, decision: "approve" }); + const addition = { + requestKey: "corrected-addition", + captain, + crewInstanceId: approved.instance!.id, + brief: null, + seat: custom("writer"), + }; + const duplicate = yield* gate.requestMember(addition).pipe(Effect.flip); + assert.equal(duplicate._tag, "CrewProposalRequestError"); + assert.include(duplicate.message, "already has a seat"); + const corrected = yield* gate.requestMember({ ...addition, seat: custom("editor") }); + assert.equal(corrected.proposal.requestedSeats[0]?.seat, "editor"); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listForCaptain(captainId), 2); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("compares normalized workspace defaults while preserving requested roster order", () => + Effect.gen(function* () { + const { layer } = yield* fixture; + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const input = { + requestKey: "normalized-roster", + captain, + displayName: "Workspace Crew", + brief: "Original", + seats: [ + { ...custom("writer"), workspace: { type: "worktree" as const, baseRef: "main" } }, + { + ...custom("editor"), + workspace: { + type: "existing_worktree" as const, + worktreePath: "/repo-worktrees/editor/", + }, + }, + ], + }; + const original = yield* gate.propose(input); + const replay = yield* gate.propose({ + ...input, + seats: [ + { + ...input.seats[0]!, + workspace: { type: "worktree", baseRef: "main", startFromOrigin: false }, + }, + { + ...input.seats[1]!, + workspace: { type: "existing_worktree", worktreePath: "/repo-worktrees/editor" }, + }, + ], + }); + assert.equal(replay.proposal.id, original.proposal.id); + const reordered = yield* gate + .propose({ ...input, seats: input.seats.toReversed() }) + .pipe(Effect.flip); + assert.equal(reordered._tag, "CrewProposalRequestError"); + assert.include(reordered.message, original.proposal.id); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listForCaptain(captainId), 1); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("identical richly populated custom seats replay after their stored JSON round trip", () => + Effect.gen(function* () { + const { layer, workspaceRoot } = yield* playbookFixture; + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const input = yield* decodeProposeCrew({ + name: "Rich Replay", + brief: "Preserve every seat choice", + playbook: "release", + seats: [ + { + seat: "writer", + reason: "Write the implementation", + instructions: "Keep the launch choices exactly as requested.", + model_selection: { + instanceId: "codex", + model: "gpt-5.6-sol", + options: [{ id: "reasoningEffort", value: "high" }], + }, + runtime_mode: "approval-required", + steps: ["build"], + workspace: { + type: "worktree", + base_ref: "main", + branch: "feature/replay", + start_from_origin: false, + }, + }, + ], + }); + const request = { + requestKey: "rich-replay", + captain, + displayName: input.name, + brief: input.brief, + playbook: { name: input.playbook!, workspaceRoot }, + seats: input.seats.map(crewSeatFromInput), + }; + const original = yield* gate.propose(request); + const stored = yield* (yield* AgentCrewProposalService).read(original.proposal.id); + assert.deepStrictEqual(stored?.requestedSeats[0]?.modelSelection?.options, [ + { id: "reasoningEffort", value: "high" }, + ]); + const replay = yield* gate.propose(request); + assert.deepStrictEqual(replay.proposal, original.proposal); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listForCaptain(captainId), 1); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect.each(["delete", "rename"] as const)( + "replays a proposal after its playbook changes by %s", + (change) => + Effect.gen(function* () { + const { layer, workspaceRoot } = yield* playbookFixture; + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const original = yield* proposeRelease(gate, workspaceRoot); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const filename = path.join(workspaceRoot, ".j5/playbooks/release.yaml"); + if (change === "delete") yield* fs.remove(filename); + else yield* fs.rename(filename, path.join(workspaceRoot, ".j5/playbooks/renamed.yaml")); + const replay = yield* proposeRelease(gate, workspaceRoot); + assert.deepStrictEqual(replay.proposal, original.proposal); + const fresh = yield* proposeRelease(gate, workspaceRoot, "fresh").pipe(Effect.flip); + assert.equal(fresh._tag, "CrewProposalRequestError"); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listForCaptain(captainId), 1); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("replays a folder-library proposal after local overrides and source removal", () => + Effect.gen(function* () { + const { layer, workspaceRoot } = yield* playbookFixture; + yield* Effect.gen(function* () { + const store = yield* PlaybookStore; + const gate = yield* CrewProposalService; + const path = yield* Path.Path; + const fs = yield* FileSystem.FileSystem; + const library = yield* fs.makeTempDirectoryScoped(); + const libraryFile = path.join(library, "release.yaml"); + const localFile = path.join(workspaceRoot, ".j5/playbooks/release.yaml"); + const yaml = yield* fs.readFileString(localFile); + yield* fs.writeFileString(libraryFile, yaml); + yield* store.setFolders({ folders: [library] }); + yield* fs.remove(localFile); + + const original = yield* proposeRelease(gate, workspaceRoot); + assert.equal(original.proposal.playbook?.definitionPath, libraryFile); + assert.equal(original.proposal.playbook?.requestWorkspaceRoot, path.resolve(workspaceRoot)); + assert.equal( + (yield* store.definitionPathFor(`${workspaceRoot}/other`, "release")).definitionPath, + libraryFile, + ); + const changed = yield* proposeRelease(gate, `${workspaceRoot}/other`).pipe(Effect.flip); + assert.equal(changed._tag, "CrewProposalRequestError"); + assert.include(changed.message, "different request"); + + yield* fs.writeFileString(localFile, yaml); + const replay = yield* proposeRelease(gate, workspaceRoot); + assert.deepStrictEqual(replay.proposal, original.proposal); + const fresh = yield* proposeRelease(gate, workspaceRoot, "fresh"); + assert.equal(fresh.proposal.playbook?.definitionPath, localFile); + + yield* store.setFolders({ folders: [] }); + yield* fs.remove(libraryFile); + const afterRemoval = yield* proposeRelease(gate, workspaceRoot); + assert.deepStrictEqual(afterRemoval.proposal, original.proposal); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listForCaptain(captainId), 2); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("refuses changed playbook names, workspaces and authority before catalog lookup", () => + Effect.gen(function* () { + const { layer, workspaceRoot } = yield* playbookFixture; + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const original = yield* proposeRelease(gate, workspaceRoot); + const input = { + requestKey: "release", + captain, + displayName: "Release Crew", + brief: "Ship the change.", + playbook: { name: "release", workspaceRoot }, + seats: [custom("planner", ["plan"]), custom("builder", ["build"])], + }; + for (const changed of [ + { ...input, playbook: { ...input.playbook, name: "missing" } }, + { ...input, playbook: { ...input.playbook, workspaceRoot: `${workspaceRoot}/other` } }, + { ...input, playbook: undefined }, + { ...input, captain: { ...captain, participantId: ParticipantId.make("other-captain") } }, + ]) { + const refusal = yield* gate.propose(changed).pipe(Effect.flip); + assert.equal(refusal._tag, "CrewProposalRequestError"); + assert.equal( + refusal.message, + `client_request_id is already bound to a different request for proposal ${original.proposal.id}. Retry the original request, or use a fresh client_request_id for new work.`, + ); + } + const replay = yield* gate.propose({ + ...input, + playbook: { name: "release.yaml", workspaceRoot: `${workspaceRoot}/.` }, + }); + assert.deepStrictEqual(replay.proposal, original.proposal); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listForCaptain(captainId), 1); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("replays legacy local playbook proposals without consulting the live catalog", () => + Effect.gen(function* () { + const { layer, workspaceRoot } = yield* playbookFixture; + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const original = yield* proposeRelease(gate, workspaceRoot); + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE j5_agent_crew_proposal SET playbook_request_workspace_root = NULL WHERE id = ${original.proposal.id}`; + const legacy = yield* (yield* AgentCrewProposalService).read(original.proposal.id); + yield* (yield* FileSystem.FileSystem).remove( + (yield* Path.Path).join(workspaceRoot, ".j5/playbooks/release.yaml"), + ); + const replay = yield* proposeRelease(gate, workspaceRoot); + assert.deepStrictEqual(replay.proposal, legacy); + const changed = yield* proposeRelease(gate, `${workspaceRoot}/other`).pipe(Effect.flip); + assert.equal(changed._tag, "CrewProposalRequestError"); + assert.include(changed.message, "different request"); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/j5/a2a/CrewProposalService.ts b/apps/server/src/j5/a2a/CrewProposalService.ts index 80f466713a6c4..678bbd1b20c1d 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.ts @@ -12,6 +12,7 @@ import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; @@ -23,6 +24,7 @@ import { type CrewPlaybookRef, type CrewProposal, type CrewProposalSeat, + type CreateCrewProposalInput, } from "./AgentCrewProposalService.ts"; import { CREW_SEAT_CAP, @@ -42,6 +44,8 @@ import { crewSeatShapeProblem } from "./crewLimits.ts"; import { CREW_PROPOSAL_SESSION } from "./crewSeatIds.ts"; import { A2ALedger } from "./LedgerService.ts"; import { lifecycleCommandId, lifecycleId } from "./spawnIds.ts"; +import { requestDigest, requestReplayConflict } from "./RequestReplayService.ts"; +import { worktreePathKey } from "./spawnWorkspace.ts"; import { getThreadProjectionIfPresent } from "./threadProjectionReads.ts"; /** Hard cap on seats per Crew, initial roster and additions together. */ @@ -233,6 +237,30 @@ const memberSteps = (instance: AgentCrewInstance | null) => playbookStepIds: member.playbookStepIds ?? [], })); +// Proposal rows preserve original intent across upgrades; human edits go to approvedSeats. +const proposalRequest = (proposal: CreateCrewProposalInput | CrewProposal) => ({ + projectId: proposal.projectId, + captainParticipantId: proposal.captainParticipantId, + captainThreadId: proposal.captainThreadId, + kind: proposal.kind, + crewInstanceId: proposal.kind === "addition" ? proposal.crewInstanceId : null, + brief: proposal.brief, + displayName: proposal.displayName, + playbook: + proposal.playbook?.requestWorkspaceRoot === undefined + ? { path: proposal.playbook?.definitionPath ?? null } + : { name: proposal.playbook.name, workspaceRoot: proposal.playbook.requestWorkspaceRoot }, + seats: proposal.requestedSeats.map(({ personaSwaps: _swaps, workspace, ...seat }) => ({ + ...seat, + workspace: + workspace?.type === "worktree" + ? { ...workspace, startFromOrigin: workspace.startFromOrigin ?? false } + : workspace?.type === "existing_worktree" + ? { ...workspace, worktreePath: worktreePathKey(workspace.worktreePath) } + : workspace, + })), +}); + export const layer = Layer.effect( CrewProposalService, Effect.gen(function* () { @@ -270,6 +298,7 @@ export const layer = Layer.effect( const ledger = yield* A2ALedger; const agents = yield* makeAgentPersonaLibrary; const playbooks = yield* PlaybookStore; + const path = yield* Path.Path; // One resolution of a proposal at a time on this server, so an approval and a decline from // two devices cannot interleave; the store's compare-and-set from open decides the winner. const gates = yield* KeyedLock.make(); @@ -587,53 +616,100 @@ export const layer = Layer.effect( }); }); + const replayProposal = Effect.fn("j5.a2a.crewProposal.replay")(function* ( + original: CrewProposal, + request: CreateCrewProposalInput, + ) { + if (requestDigest(proposalRequest(original)) !== requestDigest(proposalRequest(request))) + return yield* new CrewProposalRequestError( + requestReplayConflict( + `proposal ${original.id}${original.crewInstanceId === null ? "" : ` and crew ${original.crewInstanceId}`}`, + ), + ); + const instance = + original.crewInstanceId === null + ? null + : yield* crews + .read(original.crewInstanceId) + .pipe(Effect.mapError(operationError("reading the crew"))); + return { proposal: original, instance }; + }); + const propose: CrewProposalServiceShape["propose"] = (input) => Effect.gen(function* () { - let playbook: { ref: CrewPlaybookRef; definition: PlaybookReadResponse } | null = null; + const id = lifecycleId({ + kind: "crew", + operation: "proposal", + providerSessionId: PROPOSAL_SESSION, + requestKey: input.requestKey, + }); + const original = yield* proposals + .read(id) + .pipe(Effect.mapError(operationError("reading the proposal"))); + let playbookRef: CrewPlaybookRef | null = null; if (input.playbook !== undefined) { - const { definitionPath } = yield* playbooks - .definitionPathFor(input.playbook.workspaceRoot, input.playbook.name) - .pipe(Effect.mapError(playbookRefusal(input.playbook.name, "propose"))); - const definition = yield* readPlaybook( - { name: input.playbook.name, definitionPath }, - "propose", - ); - playbook = { ref: { name: definition.name, definitionPath }, definition }; + const { name, workspaceRoot } = input.playbook; + const requestWorkspaceRoot = path.resolve(workspaceRoot); + if (original === null) { + playbookRef = yield* playbooks.definitionPathFor(workspaceRoot, name).pipe( + Effect.map(({ stem, definitionPath }) => ({ + name: stem, + definitionPath, + requestWorkspaceRoot, + })), + Effect.mapError(playbookRefusal(name, "propose")), + ); + } else { + const stem = name.endsWith(".yaml") ? name.slice(0, -5) : name; + // Library paths do not identify the caller workspace; old rows can only prove local intent. + playbookRef = + original.playbook?.requestWorkspaceRoot === undefined + ? { + name: stem, + definitionPath: path.resolve( + requestWorkspaceRoot, + ".j5/playbooks", + `${stem}.yaml`, + ), + } + : { + name: stem, + definitionPath: original.playbook.definitionPath, + requestWorkspaceRoot, + }; + } } + const request = { + id, + projectId: input.captain.projectId, + captainParticipantId: input.captain.participantId, + captainThreadId: input.captain.thread.id, + crewInstanceId: null, + kind: "roster", + brief: input.brief, + displayName: input.displayName, + requestedSeats: input.seats, + createdAt: DateTime.formatIso(yield* DateTime.now), + playbook: playbookRef, + } satisfies CreateCrewProposalInput; + // The optional playbook summary describes fresh validation; replay never reads a changed definition. + if (original !== null) return yield* replayProposal(original, request); + const definition = + playbookRef === null ? null : yield* readPlaybook(playbookRef, "propose"); const plan = yield* validateSeats( input.seats, null, false, - playbook === null ? null : { definition: playbook.definition, existingMembers: [] }, + definition === null ? null : { definition, existingMembers: [] }, ); const proposal = yield* proposals .create({ - id: lifecycleId({ - kind: "crew", - operation: "proposal", - providerSessionId: PROPOSAL_SESSION, - requestKey: input.requestKey, - }), - projectId: input.captain.projectId, - captainParticipantId: input.captain.participantId, - captainThreadId: input.captain.thread.id, - crewInstanceId: null, - kind: "roster", - brief: input.brief, - displayName: input.displayName, + ...request, requestedSeats: withPersonaSwaps(input.seats, plan.swapsBySeat), - createdAt: DateTime.formatIso(yield* DateTime.now), - playbook: playbook?.ref ?? null, }) .pipe(Effect.mapError(operationError("recording the proposal"))); - if (proposal.status !== "open") { - const instance = - proposal.crewInstanceId === null - ? null - : yield* crews.read(proposal.crewInstanceId).pipe(Effect.orDie); - return { proposal, instance, playbook: playbookOutcome(plan) }; - } - return { proposal, instance: null, playbook: playbookOutcome(plan) }; + // Concurrent first attempts can both miss the read; the stored row decides which won. + return { ...(yield* replayProposal(proposal, request)), playbook: playbookOutcome(plan) }; }); const requestMember: CrewProposalServiceShape["requestMember"] = (input) => @@ -672,15 +748,24 @@ export const layer = Layer.effect( providerSessionId: PROPOSAL_SESSION, requestKey: input.requestKey, }); - // A replayed request finds its proposal before anything is checked or counted: once its - // seat has launched, the name clash and the cap would both refuse the retry otherwise. + const request = { + id: proposalId, + projectId: input.captain.projectId, + captainParticipantId: input.captain.participantId, + captainThreadId: input.captain.thread.id, + crewInstanceId: instance.id, + kind: "addition", + brief: input.brief ?? instance.brief, + displayName: instance.displayName, + requestedSeats: [input.seat], + createdAt: DateTime.formatIso(yield* DateTime.now), + playbook: instance.playbook ?? null, + } satisfies CreateCrewProposalInput; + // Replays precede mutable catalog, playbook, seat-name and capacity validation. const replayed = yield* proposals .read(proposalId) .pipe(Effect.mapError(operationError("reading the proposal"))); - if (replayed !== null) { - const current = yield* crews.read(instance.id).pipe(Effect.orDie); - return { proposal: replayed, instance: current }; - } + if (replayed !== null) return yield* replayProposal(replayed, request); const definition = yield* readFollowed(instance.playbook, [input.seat], "crew"); const plan = yield* validateSeats( [input.seat], @@ -690,19 +775,7 @@ export const layer = Layer.effect( ); const admitted = yield* proposals .admit( - { - id: proposalId, - projectId: input.captain.projectId, - captainParticipantId: input.captain.participantId, - captainThreadId: input.captain.thread.id, - crewInstanceId: instance.id, - kind: "addition", - brief: input.brief ?? instance.brief, - displayName: instance.displayName, - requestedSeats: withPersonaSwaps([input.seat], plan.swapsBySeat), - createdAt: DateTime.formatIso(yield* DateTime.now), - playbook: instance.playbook ?? null, - }, + { ...request, requestedSeats: withPersonaSwaps([input.seat], plan.swapsBySeat) }, { maxSeats: CREW_SEAT_CAP }, ) .pipe(Effect.mapError(operationError("recording the proposal"))); @@ -713,15 +786,10 @@ export const layer = Layer.effect( admitted.adding, "request", ); - if (admitted.proposal.status !== "open") { - const current = yield* crews.read(instance.id).pipe(Effect.orDie); - return { - proposal: admitted.proposal, - instance: current, - playbook: playbookOutcome(plan), - }; - } - return { proposal: admitted.proposal, instance, playbook: playbookOutcome(plan) }; + return { + ...(yield* replayProposal(admitted.proposal, request)), + playbook: playbookOutcome(plan), + }; }); /** diff --git a/apps/server/src/j5/a2a/Migrations.test.ts b/apps/server/src/j5/a2a/Migrations.test.ts index 43e6eacd91b0d..1accdc655914c 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -33,6 +33,47 @@ const enableAndAssertForeignKeys = Effect.gen(function* () { assert.deepStrictEqual(rows, [{ foreign_keys: 1 }]); }); +it.effect("upgrades the merged People schema with both replay migrations", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations(); + yield* runJ5A2AMigrations({ toMigrationInclusive: 43 }); + const before = yield* sql<{ readonly name: string }>` + PRAGMA table_info(j5_agent_crew_proposal) + `; + assert.notInclude( + before.map((column) => column.name), + "playbook_request_workspace_root", + ); + + yield* runJ5A2AMigrations(); + yield* sql` + INSERT INTO j5_a2a_request_replay (id, target, request_digest) + VALUES ('upgrade-key', 'Peer Agent upgrade', 'digest') + `; + const rows = yield* sql<{ readonly created_at: string }>` + SELECT created_at FROM j5_a2a_request_replay WHERE id = 'upgrade-key' + `; + assert.isString(rows[0]?.created_at); + const after = yield* sql<{ readonly name: string }>` + PRAGMA table_info(j5_agent_crew_proposal) + `; + assert.include( + after.map((column) => column.name), + "playbook_request_workspace_root", + ); + yield* runJ5A2AMigrations(); + const applied = yield* sql<{ readonly migration_id: number; readonly name: string }>` + SELECT migration_id, name FROM j5_a2a_migrations + WHERE migration_id >= 44 ORDER BY migration_id + `; + assert.deepStrictEqual(applied, [ + { migration_id: 44, name: "RequestReplay" }, + { migration_id: 45, name: "CrewPlaybookRequestWorkspace" }, + ]); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); + it.effect("tracks J5 A2A migrations independently from upstream migrations", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; @@ -98,6 +139,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () { migration_id: 42, name: "EveryoneHereAsks" }, { migration_id: 43, name: "TaskSchedulers" }, { migration_id: 44, name: "RequestReplay" }, + { migration_id: 45, name: "CrewPlaybookRequestWorkspace" }, ]); assert.deepStrictEqual( migrationEntries.map(([id, name]) => [id, name]), @@ -146,6 +188,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () [42, "EveryoneHereAsks"], [43, "TaskSchedulers"], [44, "RequestReplay"], + [45, "CrewPlaybookRequestWorkspace"], ], ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), @@ -1394,7 +1437,7 @@ it.effect("recreates earlier-shaped crews tables when 14 runs over them", () => applied.map((row) => row.migration_id), [ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, 43, 44, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, ], ); const memberColumns = yield* sql<{ readonly name: string }>` diff --git a/apps/server/src/j5/a2a/Migrations.ts b/apps/server/src/j5/a2a/Migrations.ts index 9d45add21a8d2..44677ad7d52a0 100644 --- a/apps/server/src/j5/a2a/Migrations.ts +++ b/apps/server/src/j5/a2a/Migrations.ts @@ -45,6 +45,7 @@ import Migration0041 from "./migrations/041_SharedConversation.ts"; import Migration0042 from "./migrations/042_EveryoneHereAsks.ts"; import Migration0043 from "./migrations/043_TaskSchedulers.ts"; import Migration0044 from "./migrations/044_RequestReplay.ts"; +import Migration0045 from "./migrations/045_CrewPlaybookRequestWorkspace.ts"; export const J5_A2A_MIGRATIONS_TABLE = "j5_a2a_migrations"; @@ -100,6 +101,7 @@ export const migrationEntries = [ [42, "EveryoneHereAsks", Migration0042], [43, "TaskSchedulers", Migration0043], [44, "RequestReplay", Migration0044], + [45, "CrewPlaybookRequestWorkspace", Migration0045], ] as const; const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/j5/a2a/RequestReplayService.test.ts b/apps/server/src/j5/a2a/RequestReplayService.test.ts index 03e52b99e93d7..77ac4dc18970c 100644 --- a/apps/server/src/j5/a2a/RequestReplayService.test.ts +++ b/apps/server/src/j5/a2a/RequestReplayService.test.ts @@ -41,8 +41,10 @@ it.effect("persists the original request across database reopen and refuses chan assert.isTrue(Result.isFailure(changed)); if (Result.isFailure(changed)) { assert.equal(changed.failure._tag, "RequestReplayConflictError"); - assert.include(changed.failure.message, "agent:original"); - assert.include(changed.failure.message, "fresh client_request_id"); + assert.equal( + changed.failure.message, + "client_request_id is already bound to a different request for agent:original. Retry the original request, or use a fresh client_request_id for new work.", + ); } const sql = yield* SqlClient.SqlClient; const rows = yield* sql<{ diff --git a/apps/server/src/j5/a2a/RequestReplayService.ts b/apps/server/src/j5/a2a/RequestReplayService.ts index 4d7ca16127d5e..f9cae1d1df23e 100644 --- a/apps/server/src/j5/a2a/RequestReplayService.ts +++ b/apps/server/src/j5/a2a/RequestReplayService.ts @@ -8,14 +8,20 @@ import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import type { SqlError } from "effect/sql/SqlError"; +export const requestReplayConflict = (target: string) => ({ + detail: `client_request_id is already bound to a different request for ${target}.`, + nextStep: "Retry the original request, or use a fresh client_request_id for new work.", +}); + export class RequestReplayConflictError extends Schema.TaggedError()( "RequestReplayConflictError", { target: Schema.String, legacy: Schema.Boolean }, ) { override get message() { - return this.legacy - ? `The original request for ${this.target} predates replay verification and cannot be compared. Inspect that target and use a fresh client_request_id for new work.` - : `client_request_id is already bound to a different request for ${this.target}. Retry the original request, or use a fresh client_request_id for new work.`; + if (this.legacy) + return `The original request for ${this.target} predates replay verification and cannot be compared. Inspect that target and use a fresh client_request_id for new work.`; + const { detail, nextStep } = requestReplayConflict(this.target); + return `${detail} ${nextStep}`; } } @@ -30,6 +36,11 @@ const canonical = (value: unknown): unknown => { ); }; +export const requestDigest = (request: unknown) => + NodeCrypto.createHash("sha256") + .update(JSON.stringify(canonical(request))) + .digest("hex"); + export class RequestReplayService extends Context.Service< RequestReplayService, { @@ -51,23 +62,19 @@ export const layer = Layer.effect( RequestReplayService, Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; - const digestOf = (request: unknown) => - NodeCrypto.createHash("sha256") - .update(JSON.stringify(canonical(request))) - .digest("hex"); const check: RequestReplayService["Service"]["check"] = Effect.fn("j5.requestReplay.check")( function* (id, request) { const rows = yield* sql<{ readonly target: string; readonly request_digest: string }>` SELECT target, request_digest FROM j5_a2a_request_replay WHERE id = ${id} `; const original = rows[0]; - if (original !== undefined && original.request_digest !== digestOf(request)) + if (original !== undefined && original.request_digest !== requestDigest(request)) return yield* new RequestReplayConflictError({ target: original.target, legacy: false }); }, ); const bind: RequestReplayService["Service"]["bind"] = Effect.fn("j5.requestReplay.bind")( function* (input) { - const digest = digestOf(input.request); + const digest = requestDigest(input.request); if (!input.legacy) { yield* sql` INSERT INTO j5_a2a_request_replay (id, target, request_digest) diff --git a/apps/server/src/j5/a2a/migrations/045_CrewPlaybookRequestWorkspace.ts b/apps/server/src/j5/a2a/migrations/045_CrewPlaybookRequestWorkspace.ts new file mode 100644 index 0000000000000..3ebab8fc775e0 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/045_CrewPlaybookRequestWorkspace.ts @@ -0,0 +1,7 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`ALTER TABLE j5_agent_crew_proposal ADD COLUMN playbook_request_workspace_root TEXT`; +}); diff --git a/apps/server/src/j5/a2a/spawnWorkspace.ts b/apps/server/src/j5/a2a/spawnWorkspace.ts index 42d0cdc73789d..927e0c97ac7a7 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.ts @@ -49,7 +49,7 @@ export const GitRefName = Schema.String.check( ); /** A worktree path with its trailing separators dropped, so `/repo/wt/` matches git's `/repo/wt`. */ -const worktreePathKey = (path: string) => path.replace(/[\\/]+$/, ""); +export const worktreePathKey = (path: string) => path.replace(/[\\/]+$/, ""); /** An absolute path a caller names for an existing worktree. */ export const WorktreePath = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(4096)); From 6a0874ee43fe15b3c68a08b77ae5d17e3e2d77f1 Mon Sep 17 00:00:00 2001 From: Bastian Huppertz Date: Thu, 22 Oct 2026 14:50:31 +0200 Subject: [PATCH 6/9] fix(j5): validate upload metadata before accepting spawns --- apps/server/src/j5/a2a/mcp/attachments.ts | 59 ++++++++++++++++++- apps/server/src/j5/a2a/mcp/handlers.ts | 9 ++- apps/server/src/j5/a2a/spawnWorkspace.test.ts | 51 ++++++++++++++++ 3 files changed, 115 insertions(+), 4 deletions(-) diff --git a/apps/server/src/j5/a2a/mcp/attachments.ts b/apps/server/src/j5/a2a/mcp/attachments.ts index 53281351ac0d2..02d925c3c3d0d 100644 --- a/apps/server/src/j5/a2a/mcp/attachments.ts +++ b/apps/server/src/j5/a2a/mcp/attachments.ts @@ -1,9 +1,15 @@ -import { type ChatAttachment, OrchestratorMcpFailure, type ThreadId } from "@t3tools/contracts"; +import { + ChatAttachmentId, + type ChatAttachment, + OrchestratorMcpFailure, + type ThreadId, +} from "@t3tools/contracts"; import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import { Tool, Toolkit } from "effect/ai"; +import { planAttachmentClaim, resolveAttachmentPath } from "../../../attachmentStore.ts"; import { ServerSecretStore } from "../../../auth/ServerSecretStore.ts"; import { ServerConfig } from "../../../config.ts"; import { McpInvocationContext } from "../../../mcp/McpInvocationContext.ts"; @@ -12,6 +18,7 @@ import { resolveAttachmentReferences } from "../../../mcp/toolkits/attachment/ha import type { McpAttachmentInput } from "../../../mcp/toolkits/attachment/input.ts"; import { AttachmentToolkit } from "../../../mcp/toolkits/attachment/tools.ts"; import { + AttachmentClaimError, claimPendingAttachments, releaseClaimedAttachments, } from "../../../orchestration-v2/AttachmentClaims.ts"; @@ -44,6 +51,56 @@ export const J5AttachmentUploadToolkit = Toolkit.make( AttachmentToolkit.tools.t3_attachment_discard, ); +/** Read-only preflight; claiming repeats the checks because uploads can change before dispatch. */ +export const preflightSpawnUploads = Effect.fn("j5.a2a.mcp.preflightSpawnUploads")(function* ( + threadId: ThreadId, + attachments: ReadonlyArray, +) { + const config = yield* ServerConfig; + const fs = yield* FileSystem.FileSystem; + yield* Effect.forEach( + attachments, + (attachment) => + Effect.gen(function* () { + const claim = planAttachmentClaim({ + attachmentsDir: config.attachmentsDir, + threadId, + attachmentId: attachment.id, + }); + if (!claim.ok) + return yield* new AttachmentClaimError({ + message: `Attachment '${attachment.name}' cannot be sent: ${claim.reason}.`, + }); + const info = yield* fs.stat(claim.currentPath).pipe( + Effect.mapError( + (cause) => + new AttachmentClaimError({ + message: `Attachment '${attachment.name}' cannot be sent: attachment not found.`, + cause, + }), + ), + ); + if (Number(info.size) !== attachment.sizeBytes) + return yield* new AttachmentClaimError({ + message: `Attachment '${attachment.name}' cannot be sent: stored size does not match.`, + }); + const expectedPath = resolveAttachmentPath({ + attachmentsDir: config.attachmentsDir, + attachment: { + ...attachment, + id: ChatAttachmentId.make(claim.finalId), + mimeType: attachment.mimeType.toLowerCase(), + }, + }); + if (expectedPath !== claim.finalPath) + return yield* new AttachmentClaimError({ + message: `Attachment '${attachment.name}' cannot be sent: attachment type does not match the upload.`, + }); + }), + { concurrency: 1, discard: true }, + ); +}); + /** * Sends a message with files for an agent on this server. Each attachment is a pending upload, * or one the receiver's thread already holds, and is claimed into that thread before `send` diff --git a/apps/server/src/j5/a2a/mcp/handlers.ts b/apps/server/src/j5/a2a/mcp/handlers.ts index 5c624a131931c..1bb7c7197e630 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -73,7 +73,7 @@ import { ParticipantPlacementService } from "../PlacementService.ts"; import { withDeliveryNotice } from "../receiverBacklog.ts"; import { A2ASendService } from "../SendService.ts"; import { stopThread } from "../stopThread.ts"; -import { sendClaimingAttachments } from "./attachments.ts"; +import { preflightSpawnUploads, sendClaimingAttachments } from "./attachments.ts"; import { assertPersonaWithinApprovedLevel, outsideAgentCaller, @@ -1052,8 +1052,7 @@ const handlers = { const replayable = input.client_request_id !== undefined; if (replayable) yield* replayService.check(threadId, request).pipe(Effect.mapError(replayFailure)); - // What the request alone decides about its attachments is refused before the key is bound, - // so a corrected list can be retried under the same client_request_id. + // Refuse invalid uploads before acceptance so corrected metadata can reuse the key. if (input.attachments !== undefined) { const attachments = input.attachments; yield* resolveAttachmentReferences(attachments, []).pipe( @@ -1063,6 +1062,10 @@ const handlers = { ? Effect.void : new AttachmentClaimError({ message: "Duplicate attachment ids are not allowed." }), ), + // Accepted retries may outlive their pending upload; only a new child needs preflight. + Effect.andThen( + existing === null ? preflightSpawnUploads(threadId, attachments) : Effect.void, + ), Effect.mapError((error) => stateError( `Peer Agent was not created: ${error.message}`, diff --git a/apps/server/src/j5/a2a/spawnWorkspace.test.ts b/apps/server/src/j5/a2a/spawnWorkspace.test.ts index 700194db67d9b..c7f440b207a5e 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.test.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.test.ts @@ -988,6 +988,57 @@ it.effect( }), ); +it.effect.each(["size", "type"] as const)( + "refuses incorrect upload %s before binding and accepts a corrected same-key retry", + (mismatch) => + Effect.gen(function* () { + const { layer, call, commands } = yield* spawnHarness({ + checkout: { isRepo: true, refName: "j5/main" }, + }); + yield* Effect.gen(function* () { + const config = yield* ServerConfig; + const fs = yield* FileSystem.FileSystem; + const attachment = { + type: "image" as const, + id: ChatAttachmentId.make(createPendingAttachmentId()!), + name: "screen.png", + mimeType: "image/png", + sizeBytes: 3, + }; + yield* fs.writeFile( + resolveAttachmentPath({ attachmentsDir: config.attachmentsDir, attachment })!, + new Uint8Array([1, 2, 3]), + ); + const args = { + ...spawnArgs, + workspace: { type: "shared" as const }, + client_request_id: `incorrect-upload-${mismatch}`, + }; + const incorrect = + mismatch === "size" + ? { ...attachment, sizeBytes: 2 } + : { ...attachment, mimeType: "image/jpeg" }; + const refused = yield* call({ ...args, attachments: [incorrect] }); + assert.isTrue(refused.isFailure); + assert.include( + message(refused), + mismatch === "size" ? "stored size does not match" : "type does not match", + ); + assert.lengthOf(yield* Ref.get(commands), 0, "nothing is created"); + + const corrected = yield* call({ ...args, attachments: [attachment] }); + assert.isFalse(corrected.isFailure); + const brief = (yield* Ref.get(commands)).find( + (command) => command.type === "message.dispatch", + ); + assert.lengthOf(brief?.type === "message.dispatch" ? brief.attachments : [], 1); + const changed = yield* call({ ...args, attachments: [incorrect] }); + assert.isTrue(changed.isFailure); + assert.include(message(changed), "different request"); + }).pipe(Effect.provide(layer)); + }), +); + it.effect("tells a caller to retry the same key when the replay store cannot be read", () => Effect.gen(function* () { const unreadable = Effect.fail( From fad12adbe45422961c830c07a955c678520a13d7 Mon Sep 17 00:00:00 2001 From: Bastian Huppertz Date: Thu, 22 Oct 2026 18:32:01 +0200 Subject: [PATCH 7/9] refactor(j5): own direct spawn acceptance in domain service --- FORK.md | 2 +- apps/server/src/j5/a2a/AgentCaller.ts | 96 +++ apps/server/src/j5/a2a/SpawnAgentService.ts | 717 +++++++++++++++++ apps/server/src/j5/a2a/mcp/attachments.ts | 59 +- apps/server/src/j5/a2a/mcp/handlers.ts | 739 +----------------- apps/server/src/j5/a2a/mcp/tools.ts | 17 +- apps/server/src/j5/a2a/runtimeLayer.ts | 2 + apps/server/src/j5/a2a/spawnWorkspace.test.ts | 36 + apps/server/src/j5/a2a/spawnWorkspace.ts | 16 + .../toolkits/worktree/registration.test.ts | 2 + 10 files changed, 891 insertions(+), 795 deletions(-) create mode 100644 apps/server/src/j5/a2a/AgentCaller.ts create mode 100644 apps/server/src/j5/a2a/SpawnAgentService.ts diff --git a/FORK.md b/FORK.md index 7e44d40e6a903..e106743bc8b0c 100644 --- a/FORK.md +++ b/FORK.md @@ -330,7 +330,7 @@ migrations after upstream migrations. 47. Crew seats ask their Captain, not the person (#325, Jackson's 2026-09-26 decision). `packages/provider-core/src/server/ProviderAdapter.ts` (upstream moved the file into the package; case 60) appends an optional `crewSeat` to `ProviderAdapterV2RuntimePolicy` beside `agentPersonaInstructions`. J5-owned `makeAgentPersonaRuntimePolicyResolver` (`j5/agents/agentPersonaRuntime.ts`), the only resolver behind upstream `RuntimePolicy.ts`, asks J5-owned `makeCrewSeatLookup` (`j5/a2a/crewSeatRuntime.ts`) whether an `agent`/`mcp` thread holds a seat in a live Crew, through the Crew store built over the ambient SQL client. Without a SQL client nothing is a seat, and an unreadable store logs and answers no. `RuntimePolicy.ts` clamps the resolver's runtime mode with upstream's `providerRuntimeMode`, so a persona or seat never asks a provider for a mode it does not support. A seat's policy gets `crewSeat: true` and the ask-your-Captain rule appended to `agentPersonaInstructions`. On Claude that text follows the system prompt. On Codex it now travels as `j5_agent_persona` application context keys (Role library table), and whether Codex reads it after its Default-mode "ask the user directly" text was not verified at the 2026-10-08 advance. Two adapter appends consume the flag through J5-owned leaf `j5/a2a/crewSeatQuestions.ts`: `makeClaudeAdapterV2`'s `openQuery` spreads `j5ClaudeCrewSeatQueryOverrides(turnInput.runtimePolicy)` into `makeClaudeQueryOptions` (`disallowedTools: ["AskUserQuestion"]`, the SDK option that already existed but was never set), and `codexThreadRuntimeParams` spreads `j5CodexCrewSeatConfig(input.runtimePolicy)` into the thread `config` beside `mcp_servers` (dotted session overrides `features.default_mode_request_user_input = false` and `tools.experimental_request_user_input.enabled = false`, sent on thread start, resume, and fork only when the t3-code MCP session is attached). Cursor, Grok, OpenCode, Pi, ACP registry agents, Antigravity and Muse are not supported on seats: they get only the seat brief's instruction (`spawnFirstTurnText` in `j5/a2a/spawnIds.ts`). Captains and every other thread keep their native question tools. Tests: `j5/a2a/crewSeatRuntime.test.ts` (seat, Captain, person thread, persona seat, archived Crew, no SQL client), `j5/a2a/crewSeatQuestions.test.ts` (Codex config and developer-text order), and one `ClaudeAdapterV2.test.ts` case, "withholds AskUserQuestion only from a Crew seat", on the existing wake harness. On every rebase, verify both spreads survive and that upstream has not renamed the Codex switches or added another native question tool. -48. Cross-server peering's scope (Jackson's 2026-09-16 ruling: agents never address an environment; since 2026-10-02 agents see which server a participant lives on, by the server's own name, and still never manage one. Since the ledger re-keyed to projects, the wire names a project, not a Squadron). `packages/contracts/src/auth.ts` appends the `a2a:peer` literal as `AuthA2APeerScope` to `AuthEnvironmentScope`, outside `AuthStandardClientScopes` and `AuthGrantScope`, exactly as case 35 did for `a2a:send`: no pairing link, default session or grant carries it. Only J5-owned `PeerAdminService.issueCredential` mints it, bound by the session subject to one `peer:`; a caller reaches it with `access:write`, the `j5` CLI through the credential route in `apps/server/src/j5/a2a/PeerHttp.ts` and a client through the RPC `j5.peers.issueCredential` (case 64). The peer routes authorize on that scope plus a registered peer. `packages/contracts/src/environment.ts` adds one optional capability key, `j5PeerPoll`, beside case 34's two, and `apps/server/src/environment/ServerEnvironment.ts` (with its test) reports it as true; it says a server has peering poll mode and the reachability checks, and the peering dialog offers a setup only when both servers publish it. Everything else is add-beside: migrations 23–27 (26 indexes the peer route probes; 27 indexes received sender labels by receipt time for the client identity read) 30 (poll mode: the peer table rebuilt with its link mode, the store grants, and the delivery rows' hand-out stamp) and 32 (a stored roster snapshot's fields renamed for peer protocol 2, where the wire names a project and no longer a Squadron), `PeerRegistryService.ts`, `PeerInboundService.ts`, `PeerDirectory.ts`, `PeerStoreService.ts` (the poll route's long poll), `PeerPoller.ts` (one loop per peer this server polls, started with the A2A runtime), `peerDeliveryBody.ts`, `peerRoster.ts`, `peerReachability.ts` (the origins the `j5.peers.addresses` RPC offers; it imports upstream's host helpers from `startupAccess.ts` without changing them), `peerProtocol.ts` (the one peer protocol version compare, used in both directions; the version is 2 since the wire fields were renamed, so two peered servers update together and an older one is named as the one to update), `PeerHttp.ts` entering through the case 9 aggregate (the J5 route files share `httpSupport.ts` for authentication and error shapes), the `peer` group in J5-owned `apps/server/src/j5/cli/a2a.ts`, and the wire contracts in `packages/contracts/src/j5.ts`. The peer layers are wired once in J5-owned `runtimeLayer.ts`, which gives them their own `FetchHttpClient` and takes `EnvironmentAuth` and `ServerEnvironment` from the server context, so the shared A2A runtime's requirements grow by those two upstream services; `ServerEnvironment`'s descriptor label is the name a server reports to its peers. One upstream-adjacent test moves with it: `apps/server/src/mcp/toolkits/worktree/registration.test.ts` (already J5-modified for `j5_list_participants`) provides the empty `PeerDirectory` and a ledger stub for project titles (and declares the `RequestReplayService` stub required by spawn replay checking), and expects `unread_peer_count` and `project_title`. The web side is one mount: `apps/web/src/components/settings/ConnectionsSettings.tsx` renders the J5-owned `PeerServersSettings` (from `apps/web/src/j5/peering/`) after the remote-environments section, passing only the page's primary environment id, and imports nothing else from J5. The section gates itself: it reads the peers of every connected environment where this client holds `access:write`, lists each pairing among them once, and peers any of them, defaulting to the primary one, so the mount no longer reads `canWriteAccess` or the local-environment switch ([#611](https://github.com/Jacksondr5/j5code/issues/611)); the client's peer-list read lives in `packages/client-runtime/src/j5/http.ts`, its peering commands in `state.ts`, and the setup logic in the `peering.ts` subpath export, which adds one `./j5/peering` entry to that package's exports map beside the existing J5 subpaths. On every rebase, verify the literal is still outside the bundle, `AUTH_SCOPE_OPTIONS` is still typed `AuthGrantScope` (case 35), `runtimeLayer.ts` still provides the peer layers to the aggregate and the send service, and the single `PeerServersSettings` mount survives. `docs/README.md` links the peering guide, `docs/j5/user/j5-peering.md`, beside the other J5 user guides. Development databases that ran an earlier cut of this stack, where these migrations carried ids 14–16 and later 18–21, are disposable test state with no upgrade path: recreate them with `pr-env.sh --fresh`. +48. Cross-server peering's scope (Jackson's 2026-09-16 ruling: agents never address an environment; since 2026-10-02 agents see which server a participant lives on, by the server's own name, and still never manage one. Since the ledger re-keyed to projects, the wire names a project, not a Squadron). `packages/contracts/src/auth.ts` appends the `a2a:peer` literal as `AuthA2APeerScope` to `AuthEnvironmentScope`, outside `AuthStandardClientScopes` and `AuthGrantScope`, exactly as case 35 did for `a2a:send`: no pairing link, default session or grant carries it. Only J5-owned `PeerAdminService.issueCredential` mints it, bound by the session subject to one `peer:`; a caller reaches it with `access:write`, the `j5` CLI through the credential route in `apps/server/src/j5/a2a/PeerHttp.ts` and a client through the RPC `j5.peers.issueCredential` (case 64). The peer routes authorize on that scope plus a registered peer. `packages/contracts/src/environment.ts` adds one optional capability key, `j5PeerPoll`, beside case 34's two, and `apps/server/src/environment/ServerEnvironment.ts` (with its test) reports it as true; it says a server has peering poll mode and the reachability checks, and the peering dialog offers a setup only when both servers publish it. Everything else is add-beside: migrations 23–27 (26 indexes the peer route probes; 27 indexes received sender labels by receipt time for the client identity read) 30 (poll mode: the peer table rebuilt with its link mode, the store grants, and the delivery rows' hand-out stamp) and 32 (a stored roster snapshot's fields renamed for peer protocol 2, where the wire names a project and no longer a Squadron), `PeerRegistryService.ts`, `PeerInboundService.ts`, `PeerDirectory.ts`, `PeerStoreService.ts` (the poll route's long poll), `PeerPoller.ts` (one loop per peer this server polls, started with the A2A runtime), `peerDeliveryBody.ts`, `peerRoster.ts`, `peerReachability.ts` (the origins the `j5.peers.addresses` RPC offers; it imports upstream's host helpers from `startupAccess.ts` without changing them), `peerProtocol.ts` (the one peer protocol version compare, used in both directions; the version is 2 since the wire fields were renamed, so two peered servers update together and an older one is named as the one to update), `PeerHttp.ts` entering through the case 9 aggregate (the J5 route files share `httpSupport.ts` for authentication and error shapes), the `peer` group in J5-owned `apps/server/src/j5/cli/a2a.ts`, and the wire contracts in `packages/contracts/src/j5.ts`. The peer layers are wired once in J5-owned `runtimeLayer.ts`, which gives them their own `FetchHttpClient` and takes `EnvironmentAuth` and `ServerEnvironment` from the server context, so the shared A2A runtime's requirements grow by those two upstream services; `ServerEnvironment`'s descriptor label is the name a server reports to its peers. One upstream-adjacent test moves with it: `apps/server/src/mcp/toolkits/worktree/registration.test.ts` (already J5-modified for `j5_list_participants`) provides the empty `PeerDirectory` and a ledger stub for project titles (and declares the `RequestReplayService` stub and stateless `SpawnAgentService` layer required by spawn replay checking), and expects `unread_peer_count` and `project_title`. The web side is one mount: `apps/web/src/components/settings/ConnectionsSettings.tsx` renders the J5-owned `PeerServersSettings` (from `apps/web/src/j5/peering/`) after the remote-environments section, passing only the page's primary environment id, and imports nothing else from J5. The section gates itself: it reads the peers of every connected environment where this client holds `access:write`, lists each pairing among them once, and peers any of them, defaulting to the primary one, so the mount no longer reads `canWriteAccess` or the local-environment switch ([#611](https://github.com/Jacksondr5/j5code/issues/611)); the client's peer-list read lives in `packages/client-runtime/src/j5/http.ts`, its peering commands in `state.ts`, and the setup logic in the `peering.ts` subpath export, which adds one `./j5/peering` entry to that package's exports map beside the existing J5 subpaths. On every rebase, verify the literal is still outside the bundle, `AUTH_SCOPE_OPTIONS` is still typed `AuthGrantScope` (case 35), `runtimeLayer.ts` still provides the peer layers to the aggregate and the send service, and the single `PeerServersSettings` mount survives. `docs/README.md` links the peering guide, `docs/j5/user/j5-peering.md`, beside the other J5 user guides. Development databases that ran an earlier cut of this stack, where these migrations carried ids 14–16 and later 18–21, are disposable test state with no upgrade path: recreate them with `pr-env.sh --fresh`. 49. Composer playbook picker (#314, #320). `/playbook ` (at message start) and `@playbook:` (anywhere) open one playbook picker fed by the J5 library route. These are client-side discovery and text-insertion seams; execution follows case 45's ordinary message expansion. - Detection: shared `composerTrigger.ts` and web `composer-logic.ts` append the `"slash-playbook"` kind and delegate line-start `/playbook ` detection to J5-owned `packages/shared/src/j5/playbookTrigger.ts`, exported through `packages/shared/package.json`; it matches the kebab-case name at the start of the message and stops before following text (#314). Upstream detects `/` per token since the 2026-10-17 advance, so a slash command can start mid-message; `/playbook ` spans a space, so J5 keeps a line-start check for it alone, ahead of upstream's token detection. The J5 `detectAgentMention` hook, already called at token level from both, returns the same kind for `@playbook:` tokens with the raw token after the prefix as the query (`packages/shared/src/j5/playbookMention.ts`; no upstream line). diff --git a/apps/server/src/j5/a2a/AgentCaller.ts b/apps/server/src/j5/a2a/AgentCaller.ts new file mode 100644 index 0000000000000..af379ea45e6dc --- /dev/null +++ b/apps/server/src/j5/a2a/AgentCaller.ts @@ -0,0 +1,96 @@ +import * as ThreadRegistration from "./ThreadRegistration.ts"; +import * as A2ALedger from "./LedgerService.ts"; +import * as A2ASendService from "./SendService.ts"; +import type { McpThreadInvocationScope } from "../../mcp/McpInvocationContext.ts"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; + +import type { ParticipantDirectoryRow } from "./contracts.ts"; +class J5AgentToolStateError extends Data.TaggedError("J5AgentToolStateError")<{ + readonly state: string; + readonly nextCommand: string; +}> { + override get message(): string { + return `${this.state} ${this.nextCommand}`; + } +} + +export const stateError = (state: string, nextCommand: string) => + new J5AgentToolStateError({ state, nextCommand }); + +type AgentDirectoryRow = ParticipantDirectoryRow & { + readonly participant: Extract; +}; + +export const resolveCallerMembership = Effect.fn("j5.a2a.mcp.resolveCallerMembership")(function* ( + scope: McpThreadInvocationScope, +) { + const directory = yield* (yield* A2ASendService.A2ASendService) + .listParticipants(scope.thread.threadId) + .pipe( + Effect.mapError((error) => + stateError( + `Caller thread ${scope.thread.threadId} has no usable membership in its project: ${error instanceof Error ? error.message : String(error)}.`, + "Call j5_list_participants to inspect current membership before retrying.", + ), + ), + ); + const memberships = directory.filter( + (row): row is AgentDirectoryRow => + row.participant.kind === "agent" && row.participant.threadId === scope.thread.threadId, + ); + if (memberships.length === 0) { + return yield* stateError( + `Caller membership is missing for thread ${scope.thread.threadId}.`, + "Call j5_list_participants to inspect current membership before retrying.", + ); + } + if (memberships.length !== 1) { + return yield* stateError( + `Caller membership for thread ${scope.thread.threadId} is ambiguous across projects ${memberships.map((row) => row.projectId).join(", ")}.`, + "Call j5_list_participants to inspect current membership before retrying.", + ); + } + return memberships[0]!; +}); + +export const preflightSpawnCaller = Effect.fn("j5.a2a.mcp.preflightSpawnCaller")(function* ( + scope: McpThreadInvocationScope, +) { + const ledger = yield* A2ALedger.A2ALedger; + // A thread from before every thread registered at creation registers here, on its first call. + const home = yield* (yield* ThreadRegistration.ThreadRegistration) + .ensureRegistered(scope.thread.threadId) + .pipe( + Effect.mapError((error) => + stateError( + `Caller thread ${scope.thread.threadId} could not be registered in its project: ${error instanceof Error ? error.message : String(error)}.`, + "Retry j5_spawn_agent; if it keeps failing, tell the human.", + ), + ), + ); + if (home === null) { + return yield* stateError( + `Caller thread ${scope.thread.threadId} is a Subagent and is not an agent-to-agent participant.`, + "Return your result to the agent that started you; it can spawn agents.", + ); + } + const project = yield* ledger + .readProjectLedger(home.projectId) + .pipe( + Effect.mapError((error) => + stateError( + `Caller thread ${scope.thread.threadId} is registered in project ${home.projectId}, but that project's ledger is unavailable: ${error instanceof Error ? error.message : String(error)}.`, + "Tell the human before retrying j5_spawn_agent.", + ), + ), + ); + const membership = yield* resolveCallerMembership(scope); + if (membership.projectId !== home.projectId || membership.participantId !== home.participantId) { + return yield* stateError( + `Caller thread ${scope.thread.threadId} is registered as ${home.projectId}/${home.participantId}, but its current membership is ${membership.projectId}/${membership.participantId}.`, + "Call j5_list_participants to inspect current membership, then ask the human to repair the mismatch before retrying j5_spawn_agent.", + ); + } + return { ...membership, project }; +}); diff --git a/apps/server/src/j5/a2a/SpawnAgentService.ts b/apps/server/src/j5/a2a/SpawnAgentService.ts new file mode 100644 index 0000000000000..fb2acccd0ff7c --- /dev/null +++ b/apps/server/src/j5/a2a/SpawnAgentService.ts @@ -0,0 +1,717 @@ +import * as SpawnCompositionService from "./SpawnCompositionService.ts"; +import * as AgentCrewInstanceService from "./AgentCrewInstanceService.ts"; +import * as ProviderRegistry from "../../provider/ProviderRegistry.ts"; +import * as ProjectService from "../../project/ProjectService.ts"; +import * as ManagedProjectFolders from "../../project/ManagedProjectFolders.ts"; +import * as ThreadManagementService from "../../orchestration-v2/ThreadManagementService.ts"; +import * as OrchestratorMcpService from "../../mcp/OrchestratorMcpService.ts"; +import { + isAgentPersonaReasoningOptionId, + type ModelSelection, + ProjectId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import type { SqlError } from "effect/sql/SqlError"; +import { + requireThreadScope, + type McpInvocationScope, + type McpThreadInvocationScope, +} from "../../mcp/McpInvocationContext.ts"; +import { loadCaller } from "../../mcp/threadAccess.ts"; + +import { resolveAttachmentReferences } from "../../mcp/toolkits/attachment/handlers.ts"; +import { + AttachmentClaimError, + claimPendingAttachments, + validateAttachmentLimits, +} from "../../orchestration-v2/AttachmentClaims.ts"; +import { + type DispatchModes, + exceededDispatchModeLimit, +} from "../../orchestration-v2/DispatchModeLimit.ts"; + +import { makeAgentPersonaLibrary } from "../agents/agentPersonaLibrary.ts"; +import { translateAgentPersonaProviderPolicy } from "../agents/agentPersonaProviderPolicy.ts"; +import { prepareAgentPersonaPeerSpawn } from "../agents/agentPersonaSpawn.ts"; + +import { preflightSpawnCaller, stateError } from "./AgentCaller.ts"; +import { participantIdForThread } from "./HomeRegistrar.ts"; +import { outsideAgentParticipantId, LedgerProjectId } from "./contracts.ts"; +import { + assertPersonaWithinApprovedLevel, + outsideAgentCaller, + outsideSpawnHasNoCheckout, + outsideSpawnNeedsProject, +} from "./mcp/outsideAgent.ts"; +import type { J5SpawnAgentInput } from "./mcp/tools.ts"; + +import { type RequestReplayConflictError, RequestReplayService } from "./RequestReplayService.ts"; +import { + SpawnWorkspaceService, + namedBaseRefs, + namedWorktreePaths, + resolveSpawnWorkspace, + spawnCreateCommandId, + spawnThreadCheckout, + spawnWorkspaceFromInput, +} from "./spawnWorkspace.ts"; +import { + spawnThreadId, + spawnHomeCommandId, + spawnPlacementCommandId, + spawnTitle, + spawnMessageId, + spawnFirstTurnText, +} from "./spawnIds.ts"; +import { ChatAttachmentId, type ChatAttachment, type ThreadId } from "@t3tools/contracts"; +import * as FileSystem from "effect/FileSystem"; +import { planAttachmentClaim, resolveAttachmentPath } from "../../attachmentStore.ts"; +import { ServerConfig } from "../../config.ts"; +export class SpawnAgentService extends Context.Service< + SpawnAgentService, + { + readonly spawn: ( + input: J5SpawnAgentInput, + scope: McpInvocationScope, + ) => ReturnType; + } +>()("t3/j5/a2a/SpawnAgentService") {} + +const selectSpawnModel = Effect.fn("j5.a2a.mcp.selectSpawnModel")(function* ( + scope: McpInvocationScope, + input: { readonly provider: string; readonly model: string; readonly reasoning: string }, +) { + const capabilities = yield* (yield* OrchestratorMcpService.OrchestratorMcpService) + .capabilities(scope) + .pipe( + Effect.mapError((error) => + stateError( + `Provider capabilities are unavailable for j5_spawn_agent: ${error.message}.`, + "Call orchestrator_capabilities, choose an available provider, model, and reasoning option, then retry j5_spawn_agent.", + ), + ), + ); + const provider = capabilities.providers.find( + (candidate) => candidate.providerInstanceId === input.provider, + ); + if (provider === undefined) { + return yield* stateError( + `Provider ${input.provider} is not present in current orchestrator capabilities.`, + "Call orchestrator_capabilities and retry j5_spawn_agent with a listed provider.", + ); + } + if (provider.constraints.length > 0) { + return yield* stateError( + `Provider ${input.provider} is currently unavailable: ${provider.constraints.join(" ")}`, + "Call orchestrator_capabilities and retry j5_spawn_agent with an unconstrained provider.", + ); + } + const model = provider.models.find((candidate) => candidate.id === input.model); + if (model === undefined) { + return yield* stateError( + `Model ${input.model} is not listed for provider ${input.provider}.`, + "Call orchestrator_capabilities and retry j5_spawn_agent with a model listed for that provider.", + ); + } + const reasoningDescriptor = model.options?.find( + (descriptor) => descriptor.type === "select" && isAgentPersonaReasoningOptionId(descriptor.id), + ); + if (reasoningDescriptor === undefined || reasoningDescriptor.type !== "select") { + return yield* stateError( + `Model ${input.model} on provider ${input.provider} exposes no reasoning options; j5_spawn_agent requires explicit reasoning selection.`, + "Call orchestrator_capabilities and choose a model that exposes reasoning options before retrying j5_spawn_agent.", + ); + } + if (!reasoningDescriptor.options.some((option) => option.id === input.reasoning)) { + return yield* stateError( + `Reasoning ${input.reasoning} is not listed for model ${input.model} on provider ${input.provider}.`, + `Call orchestrator_capabilities and retry j5_spawn_agent with one of: ${reasoningDescriptor.options.map((option) => option.id).join(", ")}.`, + ); + } + return { + instanceId: provider.providerInstanceId, + model: model.id, + options: [{ id: reasoningDescriptor.id, value: input.reasoning }], + } satisfies ModelSelection; +}); + +/** + * A Role-ful spawn keeps the explicit provider/model/reasoning pick; the saved agent's declared + * routes constrain it and its authority policy becomes the child's runtime mode. A child's + * permissions come from its own saved agent's policy or from the human's approval, never from + * the parent: J5 carries no parent-child permission ceiling (Jackson, 2026-09-16), because any + * such guard is one message to a trusting peer away from bypass and every child-creation door + * would have to enforce it identically. + */ +const prepareSpawnPersona = Effect.fn("j5.a2a.mcp.prepareSpawnPersona")(function* ( + input: { + readonly persona: string; + readonly provider: string; + readonly model: string; + readonly reasoning: string; + }, + modelSelection: ModelSelection, +) { + const library = yield* makeAgentPersonaLibrary; + const providers = yield* (yield* ProviderRegistry.ProviderRegistry).getProviders; + const assignment = yield* prepareAgentPersonaPeerSpawn( + { + personaId: input.persona, + provider: providers.find((candidate) => candidate.instanceId === modelSelection.instanceId), + instanceId: modelSelection.instanceId, + model: input.model, + reasoning: input.reasoning, + }, + library, + ).pipe( + Effect.mapError((error) => + stateError( + `Persona ${input.persona} cannot be spawned as requested: ${error.message}`, + "Call orchestrator_capabilities, then retry j5_spawn_agent with a provider, model, and reasoning from that persona's declared routes, or omit persona for a plain Peer Agent.", + ), + ), + ); + const policy = translateAgentPersonaProviderPolicy( + assignment.authorityPolicy, + assignment.resolvedDriver, + ); + return { + assignment, + modelSelection: assignment.resolvedModelSelection, + runtimeMode: policy.runtimeMode, + }; +}); + +/** + * The calling thread as a spawner: its home, its project and its checkout. An outside agent has + * none of these, so `j5_spawn_agent` reads this for a thread caller only. + */ +const preflightThreadSpawner = Effect.fn("j5.a2a.mcp.preflightThreadSpawner")(function* ( + scope: McpThreadInvocationScope, +) { + const caller = yield* preflightSpawnCaller(scope); + // Only a Captain grows a Crew, and only through the human gate (Bryant, 2026-09-14): a seat + // that wants more hands escalates to its Captain; its own helpers are subagents. + const membership = yield* (yield* AgentCrewInstanceService.AgentCrewInstanceService) + .findMembership(caller.participantId) + .pipe( + Effect.mapError((error) => + stateError( + `Crew membership for ${caller.participantId} cannot be read: ${error.message}.`, + "Retry j5_spawn_agent once crew records are readable.", + ), + ), + ); + if (membership !== null) { + return yield* stateError( + `Caller ${caller.participantId} is seat ${membership.seatName} of crew ${membership.crewInstanceId}; crew members cannot spawn Peer Agents.`, + "Ask your Captain for the seat with j5_send_message, or run the work yourself as a subagent with delegate_task.", + ); + } + const parent = yield* (yield* ThreadManagementService.ThreadManagementService) + .getThreadProjection(scope.thread.threadId) + .pipe( + Effect.mapError((error) => + stateError( + `Caller thread ${scope.thread.threadId} cannot be read for j5_spawn_agent: ${error.message}.`, + "Read the caller thread state and retry j5_spawn_agent after it is available.", + ), + ), + ); + return { + participantId: caller.participantId, + // Retry keys are the provider session's, as they were before outside agents could spawn. + requestNamespace: scope.thread.providerSessionId, + home: { + ledgerProject: { id: caller.projectId, title: caller.project.name }, + thread: parent.thread, + }, + outside: undefined, + }; +}); + +/** Read-only preflight; claiming repeats the checks because uploads can change before dispatch. */ +const preflightSpawnUploads = Effect.fn("j5.a2a.mcp.preflightSpawnUploads")(function* ( + threadId: ThreadId, + attachments: ReadonlyArray, +) { + const config = yield* ServerConfig; + const fs = yield* FileSystem.FileSystem; + yield* Effect.forEach( + attachments, + (attachment) => + Effect.gen(function* () { + const claim = planAttachmentClaim({ + attachmentsDir: config.attachmentsDir, + threadId, + attachmentId: attachment.id, + }); + if (!claim.ok) + return yield* new AttachmentClaimError({ + message: `Attachment cannot be sent: ${claim.reason}.`, + }); + const info = yield* fs.stat(claim.currentPath).pipe( + Effect.mapError( + (cause) => + new AttachmentClaimError({ + message: `Attachment cannot be sent: attachment not found.`, + cause, + }), + ), + ); + if (Number(info.size) !== attachment.sizeBytes) + return yield* new AttachmentClaimError({ + message: `Attachment cannot be sent: stored size does not match.`, + }); + const expectedPath = resolveAttachmentPath({ + attachmentsDir: config.attachmentsDir, + attachment: { + ...attachment, + id: ChatAttachmentId.make(claim.finalId), + mimeType: attachment.mimeType.toLowerCase(), + }, + }); + if (expectedPath !== claim.finalPath) + return yield* new AttachmentClaimError({ + message: `Attachment cannot be sent: attachment type does not match the upload.`, + }); + }), + { concurrency: 1, discard: true }, + ); +}); + +const spawn = Effect.fn("j5.a2a.spawnAgent")(function* ( + input: J5SpawnAgentInput, + scope: McpInvocationScope, +) { + const crypto = yield* Crypto.Crypto; + // An outside agent has no thread, home, project or checkout: it is recorded as the spawner + // and the new agent sits at the top level of the project it names. + const outside = yield* outsideAgentCaller; + const spawner = + outside === undefined + ? yield* preflightThreadSpawner(yield* requireThreadScope(scope, "This tool")) + : { + participantId: outsideAgentParticipantId(outside.client.sessionId), + // A new sign-in is a new session, so it is a new set of retry keys. + requestNamespace: scope.requestNamespace, + home: undefined, + outside, + }; + const { home } = spawner; + const requestKey = input.client_request_id ?? (yield* crypto.randomUUIDv4().pipe(Effect.orDie)); + const stableInput = { providerSessionId: spawner.requestNamespace, requestKey }; + const threadId = spawnThreadId(stableInput); + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const spawnReadFailure = (error: { readonly message: string }) => + stateError( + `Peer Agent thread ${threadId} could not be read: ${error.message}`, + "Retry j5_spawn_agent with the same client_request_id once it is readable.", + ); + const existing = yield* threadManagement + .getThreadShell(threadId) + .pipe(Effect.mapError(spawnReadFailure)); + const workspaceRequest = + input.workspace.type === "worktree" + ? { ...input.workspace, start_from_origin: input.workspace.start_from_origin ?? false } + : input.workspace.type === "existing_worktree" + ? { + ...input.workspace, + worktree_path: input.workspace.worktree_path.replace(/[\\/]+$/, ""), + } + : input.workspace; + const request = { + ...input, + client_request_id: undefined, + title: input.title ?? null, + scratch: input.scratch ?? false, + workspace: workspaceRequest, + }; + const replayService = yield* RequestReplayService; + const replayFailure = (error: SqlError | RequestReplayConflictError) => + error._tag === "RequestReplayConflictError" + ? stateError(error.message, "Inspect the original target before starting new work.") + : stateError( + `The spawn's client_request_id could not be checked: ${error.message}`, + "Retry j5_spawn_agent with the same client_request_id.", + ); + // A generated key can never be retried, so it has nothing to bind. + const replayable = input.client_request_id !== undefined; + if (replayable) + yield* replayService.check(threadId, request).pipe(Effect.mapError(replayFailure)); + // Refuse invalid uploads before acceptance so corrected metadata can reuse the key. + if (input.attachments !== undefined) { + const attachments = input.attachments; + yield* resolveAttachmentReferences(attachments, []).pipe( + Effect.flatMap(validateAttachmentLimits), + Effect.andThen( + new Set(attachments.map((attachment) => attachment.id)).size === attachments.length + ? Effect.void + : new AttachmentClaimError({ message: "Duplicate attachment ids are not allowed." }), + ), + // Accepted retries may outlive their pending upload; only a new child needs preflight. + Effect.andThen( + existing === null ? preflightSpawnUploads(threadId, attachments) : Effect.void, + ), + Effect.mapError((error) => + stateError( + `Peer Agent was not created: ${error.message}`, + "Retry j5_spawn_agent with corrected attachments; the same client_request_id still works.", + ), + ), + ); + } + const selected = existing?.modelSelection ?? (yield* selectSpawnModel(scope, input)); + const personaId = input.persona; + const persona = + personaId === undefined || existing !== null + ? undefined + : yield* prepareSpawnPersona({ ...input, persona: personaId }, selected); + const modelSelection = existing?.modelSelection ?? persona?.modelSelection ?? selected; + // A persona's policy sets its permissions. Without one the agent gets the caller's modes, + // or the ones the caller chose, which upstream's rule keeps within the caller's own. + if (personaId !== undefined && input.runtime_mode !== undefined) { + return yield* stateError( + `Persona ${personaId} sets its own permission mode, so runtime_mode cannot be chosen for it.`, + "Retry j5_spawn_agent without runtime_mode, or without persona.", + ); + } + const { limits } = yield* loadCaller(); + // An outside persona's replay is capped against the existing thread's modes below. + if (persona !== undefined && personaId !== undefined && outside !== undefined) { + yield* assertPersonaWithinApprovedLevel(outside, personaId, persona.runtimeMode); + } + // With no mode chosen the agent gets the caller's: its thread's, or its approved level. + const runtimeMode = + existing?.runtimeMode ?? + input.runtime_mode ?? + persona?.runtimeMode ?? + home?.thread.runtimeMode ?? + limits.runtimeMode; + const interactionMode = + existing?.interactionMode ?? + input.interaction_mode ?? + home?.thread.interactionMode ?? + limits.interactionMode; + { + // Each mode is held to the caller's own only where the caller chose it, so choosing an + // interaction mode does not put a persona's permission mode under the ceiling. + const exceeded = exceededDispatchModeLimit(limits, { + runtimeMode: input.runtime_mode ?? limits.runtimeMode, + interactionMode: input.interaction_mode ?? limits.interactionMode, + }); + if (exceeded !== undefined) { + return yield* stateError( + `The ${exceeded === "runtime" ? `permission mode ${runtimeMode}` : `interaction mode ${interactionMode}`} is broader than your own.`, + "Retry j5_spawn_agent with a mode no broader than yours, or omit it to give the agent your own.", + ); + } + } + const firstAttempt = existing === null; + // A retry finishes the agent its first attempt created, in the modes it was created with. + // A caller's modes can be narrowed within one provider session, so those are checked + // against what the caller may touch now. A persona's agent runs under its own policy, + // except for an outside agent, whose approved level caps every agent it starts. This early + // check is the only one an unbound legacy agent reaches, since bind refuses it before the + // start; the start checks again for an agent a concurrent attempt created since. + const replayExceedsCaller = (caller: DispatchModes, thread: DispatchModes) => { + if (personaId !== undefined && outside === undefined) return Effect.void; + const exceeded = exceededDispatchModeLimit(caller, thread); + return exceeded === undefined + ? Effect.void + : Effect.fail( + stateError( + `Peer Agent ${participantIdForThread(threadId)} already exists with a ${exceeded === "runtime" ? "permission" : "interaction"} mode broader than yours is now.`, + "Ask the user to start that agent, or spawn a new one with a fresh client_request_id.", + ), + ); + }; + if (existing !== null) yield* replayExceedsCaller(limits, existing); + + // The project the agent joins: the caller's, another one, or upstream's "No project". + if (input.scratch === true && input.project_id !== undefined) { + return yield* stateError( + "scratch spawns an agent without a project, so it cannot be combined with project_id.", + "Retry j5_spawn_agent with one of them.", + ); + } + const target = + input.scratch === true + ? yield* (yield* ManagedProjectFolders.ManagedProjectFolders).ensureScratchProject.pipe( + Effect.map(({ projectId }) => projectId), + Effect.mapError((error) => + stateError( + `An agent without a project cannot be spawned here: ${error.message}`, + "Retry j5_spawn_agent with a project_id, or without scratch for your own project.", + ), + ), + ) + : input.project_id !== undefined + ? ProjectId.make(input.project_id) + : home === undefined + ? yield* outsideSpawnNeedsProject + : home.thread.projectId; + // The spawner's own project and checkout, when the agent joins that project. + const own = home !== undefined && target === home.thread.projectId ? home : undefined; + const elsewhere = own === undefined; + const targetProject = + own !== undefined + ? own.ledgerProject + : yield* (yield* ProjectService.ProjectService).getById(target).pipe( + Effect.mapError((error) => + stateError( + `Project ${target} cannot be read now: ${error.message}.`, + "Retry j5_spawn_agent.", + ), + ), + Effect.flatMap( + Option.match({ + onNone: () => + Effect.fail( + stateError( + `This server has no project ${target}.`, + "Call t3_project_list and retry j5_spawn_agent with one of its project ids.", + ), + ), + onSome: (project) => + Effect.succeed({ id: LedgerProjectId.make(project.id), title: project.title }), + }), + ), + ); + if (input.scratch === true && input.workspace.type !== "root") { + return yield* stateError( + "An agent without a project works in a folder of its own, not in a checkout or a worktree.", + 'Retry j5_spawn_agent with workspace {"type":"root"}.', + ); + } + if (home === undefined && input.workspace.type === "shared") { + return yield* outsideSpawnHasNoCheckout; + } + if (elsewhere && input.workspace.type === "shared") { + return yield* stateError( + `Your own checkout belongs to your project, and this agent joins project ${target}.`, + 'Retry j5_spawn_agent with workspace {"type":"root"} for that project\'s main checkout, or a worktree of it.', + ); + } + const spawnWorkspace = yield* SpawnWorkspaceService; + // The project's main checkout binds nothing, so it travels as the shared type with no + // checkout to share: one create command, and nothing asked of git. + const choice = + input.workspace.type === "root" + ? ({ type: "shared" } as const) + : spawnWorkspaceFromInput(input.workspace); + // A replay must not refuse the branch its own first attempt created, so a named branch is + // checked for only before the thread exists. + const checkBranches = choice.type === "worktree" && choice.branch !== undefined && firstAttempt; + // Sharing a checkout asks nothing of git. + const checkout = + choice.type === "shared" + ? null + : yield* spawnWorkspace.inspect({ + projectId: target, + worktreePath: own?.thread.worktreePath ?? null, + checkBranches, + baseRefs: namedBaseRefs([choice]), + existingWorktreePaths: namedWorktreePaths([choice]), + }); + const workspace = yield* Effect.fromResult( + checkout === null + ? Result.succeed({ type: "shared" } as const) + : resolveSpawnWorkspace(checkout, choice), + ).pipe( + Effect.mapError((error) => + stateError(`Peer Agent was not created: ${error.detail}`, error.nextStep), + ), + ); + if (replayable) + yield* replayService + .bind({ + id: threadId, + target: `Peer Agent ${participantIdForThread(threadId)} on thread ${threadId}`, + request, + legacy: existing !== null, + }) + .pipe(Effect.mapError(replayFailure)); + return yield* spawnWorkspace + .withSpawnStart( + { stableInput, threadId, workspace }, + Effect.gen(function* () { + // What a shared-type thread binds: the caller's checkout, or the project's main one. + // As upstream's launch does, a main-checkout thread asks for a folder of its own, and + // gets one only in the "No project" project. It is claimed here, inside the start + // that only one call at a time may run, and only before the thread exists; a replay + // replays its create. The thread is looked for again now that this call holds the + // start: an earlier attempt may have created it since the read above. + const current = yield* threadManagement + .getThreadShell(threadId) + .pipe(Effect.mapError(spawnReadFailure)); + if (current !== null) yield* replayExceedsCaller((yield* loadCaller()).limits, current); + const sharedCheckout = + current !== null + ? current + : input.workspace.type !== "root" && home !== undefined + ? home.thread + : { + branch: null, + worktreePath: Option.getOrNull( + yield* (yield* ManagedProjectFolders.ManagedProjectFolders) + .folderForThread({ projectId: target, threadId, text: input.brief }) + .pipe( + Effect.mapError((error) => + stateError( + `A folder for the agent could not be made: ${error.message}`, + "Retry j5_spawn_agent with the same client_request_id.", + ), + ), + ), + ), + }; + yield* threadManagement + .dispatch({ + type: "thread.create", + createdBy: "agent", + creationSource: "mcp", + commandId: spawnCreateCommandId(stableInput, workspace.type), + threadId, + projectId: target, + title: spawnTitle(input.brief, input.title), + modelSelection: current?.modelSelection ?? modelSelection, + runtimeMode: current?.runtimeMode ?? runtimeMode, + interactionMode: current?.interactionMode ?? interactionMode, + ...(persona === undefined ? {} : { agentPersonaAssignment: persona.assignment }), + ...(current === null + ? spawnThreadCheckout(workspace, sharedCheckout) + : { branch: current.branch, worktreePath: current.worktreePath }), + }) + .pipe( + Effect.mapError((error) => + stateError( + `Peer Agent thread ${threadId} could not be created: ${error.message}.`, + error._tag === "OrchestratorCommandPreviouslyRejectedError" + ? "Inspect the rejection, correct the request, and retry j5_spawn_agent with a fresh client_request_id; the rejected key is permanently bound." + : "Inspect the caller thread and provider state, then retry j5_spawn_agent with the same client_request_id.", + ), + ), + ); + const child = yield* threadManagement + .getThreadProjection(threadId) + .pipe( + Effect.mapError((error) => + stateError( + `Created Peer Agent thread ${threadId} is not readable: ${error.message}.`, + "Retry j5_spawn_agent with the same client_request_id so registration can continue safely.", + ), + ), + ); + const facts = yield* (yield* SpawnCompositionService.SpawnCompositionService) + .recordFacts({ + homeCommandId: spawnHomeCommandId(stableInput), + placementCommandId: spawnPlacementCommandId(stableInput), + projectId: targetProject.id, + threadId, + provenance: { + kind: "spawned-by", + spawnedByParticipantId: spawner.participantId, + source: "j5_spawn", + }, + ...(outside === undefined ? {} : { outsideSpawnerName: outside.client.label }), + createdAt: DateTime.formatIso(child.thread.createdAt), + }) + .pipe( + Effect.mapError((error) => + stateError( + `Peer Agent thread ${threadId} exists as a visible orphan without committed home/placement facts or a started brief: ${error.message}.`, + "Retry j5_spawn_agent with the same client_request_id only after repairing transient state; otherwise ask the human operator to retire or repair the orphan after A9 lifecycle support lands.", + ), + ), + ); + // In the spawner's own project the agent sits under it; in another it is a root, as + // is every agent an outside agent starts. + if ( + facts.placement.provenance.kind !== "spawned-by" || + facts.placement.provenance.source !== "j5_spawn" || + (facts.placement.placementParentId === null) !== elsewhere + ) { + return yield* stateError( + `Peer Agent ${facts.home.participantId} committed placement facts that do not satisfy the J5 spawn contract.`, + "Call j5_list_participants to inspect committed placement truth and ask the human operator to repair the inconsistent record.", + ); + } + // The brief's files are claimed into the new thread, which now exists. + const attachments = + input.attachments === undefined + ? [] + : (yield* resolveAttachmentReferences(input.attachments, []).pipe( + Effect.flatMap((references) => + claimPendingAttachments({ threadId, attachments: references }), + ), + Effect.mapError((error) => + stateError( + `Peer Agent ${facts.home.participantId} is registered and addressable, but its brief's attachments could not be claimed: ${error.message}`, + "Retry j5_spawn_agent with the same client_request_id and the original attachment ids after repairing the upload; use a fresh client_request_id for a changed brief.", + ), + ), + )).attachments; + yield* spawnWorkspace + .startBrief({ + workspace, + stableInput, + ledgerProjectId: facts.home.projectId, + projectId: target, + threadId, + title: spawnTitle(input.brief, input.title), + messageId: spawnMessageId(stableInput), + text: spawnFirstTurnText({ + brief: input.brief, + participantId: facts.home.participantId, + projectId: facts.home.projectId, + projectTitle: targetProject.title, + spawnedByParticipantId: spawner.participantId, + ...(outside === undefined + ? { spawnerThreadId: scope.thread?.threadId } + : { outsideAgentName: outside.client.label }), + }), + modelSelection: child.thread.modelSelection, + runtimeMode: child.thread.runtimeMode, + interactionMode: child.thread.interactionMode, + attachments, + }) + .pipe( + Effect.mapError((error) => + stateError( + `Peer Agent ${facts.home.participantId} is registered and addressable, but its brief did not start: ${error.message}.`, + "Retry j5_spawn_agent with the same client_request_id to start the same brief safely.", + ), + ), + ); + return { + participant_id: facts.home.participantId, + thread_id: threadId, + project_id: facts.home.projectId, + project_title: targetProject.title, + placement: { + placement_parent_id: facts.placement.placementParentId, + provenance: { + kind: "spawned-by" as const, + spawned_by_participant_id: facts.placement.provenance.spawnedByParticipantId, + source: facts.placement.provenance.source, + }, + }, + }; + }), + ) + .pipe( + Effect.catchTags({ + SpawnWorkspaceError: (error) => + Effect.fail(stateError(`Peer Agent was not created: ${error.detail}`, error.nextStep)), + }), + ); +}); + +export const layer = Layer.succeed(SpawnAgentService, SpawnAgentService.of({ spawn })); diff --git a/apps/server/src/j5/a2a/mcp/attachments.ts b/apps/server/src/j5/a2a/mcp/attachments.ts index 02d925c3c3d0d..53281351ac0d2 100644 --- a/apps/server/src/j5/a2a/mcp/attachments.ts +++ b/apps/server/src/j5/a2a/mcp/attachments.ts @@ -1,15 +1,9 @@ -import { - ChatAttachmentId, - type ChatAttachment, - OrchestratorMcpFailure, - type ThreadId, -} from "@t3tools/contracts"; +import { type ChatAttachment, OrchestratorMcpFailure, type ThreadId } from "@t3tools/contracts"; import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import { Tool, Toolkit } from "effect/ai"; -import { planAttachmentClaim, resolveAttachmentPath } from "../../../attachmentStore.ts"; import { ServerSecretStore } from "../../../auth/ServerSecretStore.ts"; import { ServerConfig } from "../../../config.ts"; import { McpInvocationContext } from "../../../mcp/McpInvocationContext.ts"; @@ -18,7 +12,6 @@ import { resolveAttachmentReferences } from "../../../mcp/toolkits/attachment/ha import type { McpAttachmentInput } from "../../../mcp/toolkits/attachment/input.ts"; import { AttachmentToolkit } from "../../../mcp/toolkits/attachment/tools.ts"; import { - AttachmentClaimError, claimPendingAttachments, releaseClaimedAttachments, } from "../../../orchestration-v2/AttachmentClaims.ts"; @@ -51,56 +44,6 @@ export const J5AttachmentUploadToolkit = Toolkit.make( AttachmentToolkit.tools.t3_attachment_discard, ); -/** Read-only preflight; claiming repeats the checks because uploads can change before dispatch. */ -export const preflightSpawnUploads = Effect.fn("j5.a2a.mcp.preflightSpawnUploads")(function* ( - threadId: ThreadId, - attachments: ReadonlyArray, -) { - const config = yield* ServerConfig; - const fs = yield* FileSystem.FileSystem; - yield* Effect.forEach( - attachments, - (attachment) => - Effect.gen(function* () { - const claim = planAttachmentClaim({ - attachmentsDir: config.attachmentsDir, - threadId, - attachmentId: attachment.id, - }); - if (!claim.ok) - return yield* new AttachmentClaimError({ - message: `Attachment '${attachment.name}' cannot be sent: ${claim.reason}.`, - }); - const info = yield* fs.stat(claim.currentPath).pipe( - Effect.mapError( - (cause) => - new AttachmentClaimError({ - message: `Attachment '${attachment.name}' cannot be sent: attachment not found.`, - cause, - }), - ), - ); - if (Number(info.size) !== attachment.sizeBytes) - return yield* new AttachmentClaimError({ - message: `Attachment '${attachment.name}' cannot be sent: stored size does not match.`, - }); - const expectedPath = resolveAttachmentPath({ - attachmentsDir: config.attachmentsDir, - attachment: { - ...attachment, - id: ChatAttachmentId.make(claim.finalId), - mimeType: attachment.mimeType.toLowerCase(), - }, - }); - if (expectedPath !== claim.finalPath) - return yield* new AttachmentClaimError({ - message: `Attachment '${attachment.name}' cannot be sent: attachment type does not match the upload.`, - }); - }), - { concurrency: 1, discard: true }, - ); -}); - /** * Sends a message with files for an agent on this server. Each attachment is a pending upload, * or one the receiver's thread already holds, and is claimed into that thread before `send` diff --git a/apps/server/src/j5/a2a/mcp/handlers.ts b/apps/server/src/j5/a2a/mcp/handlers.ts index 1bb7c7197e630..8aeac3112730e 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -1,54 +1,39 @@ -import { - type ChatAttachment, - isAgentPersonaReasoningOptionId, - type ModelSelection, - ProjectId, -} from "@t3tools/contracts"; +import * as Layer from "effect/Layer"; +import * as SpawnAgentService from "../SpawnAgentService.ts"; +import { stateError, preflightSpawnCaller, resolveCallerMembership } from "../AgentCaller.ts"; +import { type ChatAttachment, ProjectId } from "@t3tools/contracts"; import { playbookHandlers } from "../../playbooks/mcp.ts"; import { playbookWorkspaceRoot } from "../../playbooks/workspace.ts"; import * as Crypto from "effect/Crypto"; -import * as Data from "effect/Data"; + import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; -import * as Result from "effect/Result"; -import type { SqlError } from "effect/sql/SqlError"; import { McpInvocationContext, - type McpInvocationScope, type McpThreadInvocationScope, requireThreadScope, } from "../../../mcp/McpInvocationContext.ts"; import * as McpToolAccess from "../../../mcp/McpToolAccess.ts"; -import { resolveAttachmentReferences } from "../../../mcp/toolkits/attachment/handlers.ts"; + import { assertTargetWithinLimits, type CallerLimits, loadCaller, } from "../../../mcp/threadAccess.ts"; -import { OrchestratorMcpService } from "../../../mcp/OrchestratorMcpService.ts"; -import { - AttachmentClaimError, - claimPendingAttachments, - validateAttachmentLimits, -} from "../../../orchestration-v2/AttachmentClaims.ts"; -import { - type DispatchModes, - exceededDispatchModeLimit, -} from "../../../orchestration-v2/DispatchModeLimit.ts"; + import { OrchestratorV2 } from "../../../orchestration-v2/Orchestrator.ts"; import { ThreadManagementService, latestActiveRun, } from "../../../orchestration-v2/ThreadManagementService.ts"; -import { ManagedProjectFolders } from "../../../project/ManagedProjectFolders.ts"; + import { ProjectService } from "../../../project/ProjectService.ts"; import { ProviderRegistry } from "../../../provider/ProviderRegistry.ts"; import { makeAgentPersonaLibrary } from "../../agents/agentPersonaLibrary.ts"; import { buildAgentPersonaCatalog } from "../../agents/agentPersonaRouting.ts"; -import { translateAgentPersonaProviderPolicy } from "../../agents/agentPersonaProviderPolicy.ts"; -import { prepareAgentPersonaPeerSpawn } from "../../agents/agentPersonaSpawn.ts"; + import { AgentCrewInstanceService } from "../AgentCrewInstanceService.ts"; import type { ArchiveAgentConsequenceFacts } from "../ArchiveAgentService.ts"; import { @@ -73,44 +58,22 @@ import { ParticipantPlacementService } from "../PlacementService.ts"; import { withDeliveryNotice } from "../receiverBacklog.ts"; import { A2ASendService } from "../SendService.ts"; import { stopThread } from "../stopThread.ts"; -import { preflightSpawnUploads, sendClaimingAttachments } from "./attachments.ts"; +import { sendClaimingAttachments } from "./attachments.ts"; import { - assertPersonaWithinApprovedLevel, outsideAgentCaller, - outsideSpawnHasNoCheckout, - outsideSpawnNeedsProject, sendAsOutsideAgent, spawnAndBrief, actsAsThreadCaller, } from "./outsideAgent.ts"; -import { SpawnCompositionService } from "../SpawnCompositionService.ts"; -import { type RequestReplayConflictError, RequestReplayService } from "../RequestReplayService.ts"; -import { - SpawnWorkspaceService, - namedBaseRefs, - namedWorktreePaths, - resolveSpawnWorkspace, - spawnCreateCommandId, - spawnThreadCheckout, -} from "../spawnWorkspace.ts"; -import { ThreadRegistration } from "../ThreadRegistration.ts"; -import { - crewSeatRequestKey, - lifecycleCommandId, - spawnFirstTurnText, - spawnHomeCommandId, - spawnMessageId, - spawnPlacementCommandId, - spawnThreadId, - spawnTitle, - stablePart, -} from "../spawnIds.ts"; + +import { spawnWorkspaceFromInput } from "../spawnWorkspace.ts"; + +import { crewSeatRequestKey, lifecycleCommandId, stablePart } from "../spawnIds.ts"; import { CommCommandId, LedgerProjectId, type ParticipantDirectoryRow, type ParticipantId, - outsideAgentParticipantId, } from "../contracts.ts"; import type { ParticipantProvenanceView } from "../placementContracts.ts"; import { @@ -119,18 +82,8 @@ import { type J5ArchiveCrewFailure, type J5McpFailure, type J5ProposeCrewInput, - spawnWorkspaceFromInput, } from "./tools.ts"; -class J5AgentToolStateError extends Data.TaggedError("J5AgentToolStateError")<{ - readonly state: string; - readonly nextCommand: string; -}> { - override get message(): string { - return `${this.state} ${this.nextCommand}`; - } -} - const failure = (error: unknown): J5McpFailure => ({ code: typeof error === "object" && error !== null && "_tag" in error @@ -220,13 +173,6 @@ export const commandIdForRequest = (input: { ); }; -type AgentDirectoryRow = ParticipantDirectoryRow & { - readonly participant: Extract; -}; - -const stateError = (state: string, nextCommand: string) => - new J5AgentToolStateError({ state, nextCommand }); - /** * The calling thread's scope, for a handler that has already ruled out an outside agent or is * declared `actsAsCaller`. Tools an outside agent is refused use `actsAsThreadCaller`, which names @@ -236,232 +182,6 @@ const callerScope = McpInvocationContext.pipe( Effect.flatMap((scope) => requireThreadScope(scope, "This tool")), ); -const resolveCallerMembership = Effect.fn("j5.a2a.mcp.resolveCallerMembership")(function* ( - scope: McpThreadInvocationScope, -) { - const directory = yield* (yield* A2ASendService) - .listParticipants(scope.thread.threadId) - .pipe( - Effect.mapError((error) => - stateError( - `Caller thread ${scope.thread.threadId} has no usable membership in its project: ${error instanceof Error ? error.message : String(error)}.`, - "Call j5_list_participants to inspect current membership before retrying.", - ), - ), - ); - const memberships = directory.filter( - (row): row is AgentDirectoryRow => - row.participant.kind === "agent" && row.participant.threadId === scope.thread.threadId, - ); - if (memberships.length === 0) { - return yield* stateError( - `Caller membership is missing for thread ${scope.thread.threadId}.`, - "Call j5_list_participants to inspect current membership before retrying.", - ); - } - if (memberships.length !== 1) { - return yield* stateError( - `Caller membership for thread ${scope.thread.threadId} is ambiguous across projects ${memberships.map((row) => row.projectId).join(", ")}.`, - "Call j5_list_participants to inspect current membership before retrying.", - ); - } - return memberships[0]!; -}); - -const preflightSpawnCaller = Effect.fn("j5.a2a.mcp.preflightSpawnCaller")(function* ( - scope: McpThreadInvocationScope, -) { - const ledger = yield* A2ALedger; - // A thread from before every thread registered at creation registers here, on its first call. - const home = yield* (yield* ThreadRegistration) - .ensureRegistered(scope.thread.threadId) - .pipe( - Effect.mapError((error) => - stateError( - `Caller thread ${scope.thread.threadId} could not be registered in its project: ${error instanceof Error ? error.message : String(error)}.`, - "Retry j5_spawn_agent; if it keeps failing, tell the human.", - ), - ), - ); - if (home === null) { - return yield* stateError( - `Caller thread ${scope.thread.threadId} is a Subagent and is not an agent-to-agent participant.`, - "Return your result to the agent that started you; it can spawn agents.", - ); - } - const project = yield* ledger - .readProjectLedger(home.projectId) - .pipe( - Effect.mapError((error) => - stateError( - `Caller thread ${scope.thread.threadId} is registered in project ${home.projectId}, but that project's ledger is unavailable: ${error instanceof Error ? error.message : String(error)}.`, - "Tell the human before retrying j5_spawn_agent.", - ), - ), - ); - const membership = yield* resolveCallerMembership(scope); - if (membership.projectId !== home.projectId || membership.participantId !== home.participantId) { - return yield* stateError( - `Caller thread ${scope.thread.threadId} is registered as ${home.projectId}/${home.participantId}, but its current membership is ${membership.projectId}/${membership.participantId}.`, - "Call j5_list_participants to inspect current membership, then ask the human to repair the mismatch before retrying j5_spawn_agent.", - ); - } - return { ...membership, project }; -}); - -const selectSpawnModel = Effect.fn("j5.a2a.mcp.selectSpawnModel")(function* ( - scope: McpInvocationScope, - input: { readonly provider: string; readonly model: string; readonly reasoning: string }, -) { - const capabilities = yield* (yield* OrchestratorMcpService) - .capabilities(scope) - .pipe( - Effect.mapError((error) => - stateError( - `Provider capabilities are unavailable for j5_spawn_agent: ${error.message}.`, - "Call orchestrator_capabilities, choose an available provider, model, and reasoning option, then retry j5_spawn_agent.", - ), - ), - ); - const provider = capabilities.providers.find( - (candidate) => candidate.providerInstanceId === input.provider, - ); - if (provider === undefined) { - return yield* stateError( - `Provider ${input.provider} is not present in current orchestrator capabilities.`, - "Call orchestrator_capabilities and retry j5_spawn_agent with a listed provider.", - ); - } - if (provider.constraints.length > 0) { - return yield* stateError( - `Provider ${input.provider} is currently unavailable: ${provider.constraints.join(" ")}`, - "Call orchestrator_capabilities and retry j5_spawn_agent with an unconstrained provider.", - ); - } - const model = provider.models.find((candidate) => candidate.id === input.model); - if (model === undefined) { - return yield* stateError( - `Model ${input.model} is not listed for provider ${input.provider}.`, - "Call orchestrator_capabilities and retry j5_spawn_agent with a model listed for that provider.", - ); - } - const reasoningDescriptor = model.options?.find( - (descriptor) => descriptor.type === "select" && isAgentPersonaReasoningOptionId(descriptor.id), - ); - if (reasoningDescriptor === undefined || reasoningDescriptor.type !== "select") { - return yield* stateError( - `Model ${input.model} on provider ${input.provider} exposes no reasoning options; j5_spawn_agent requires explicit reasoning selection.`, - "Call orchestrator_capabilities and choose a model that exposes reasoning options before retrying j5_spawn_agent.", - ); - } - if (!reasoningDescriptor.options.some((option) => option.id === input.reasoning)) { - return yield* stateError( - `Reasoning ${input.reasoning} is not listed for model ${input.model} on provider ${input.provider}.`, - `Call orchestrator_capabilities and retry j5_spawn_agent with one of: ${reasoningDescriptor.options.map((option) => option.id).join(", ")}.`, - ); - } - return { - instanceId: provider.providerInstanceId, - model: model.id, - options: [{ id: reasoningDescriptor.id, value: input.reasoning }], - } satisfies ModelSelection; -}); - -/** - * A Role-ful spawn keeps the explicit provider/model/reasoning pick; the saved agent's declared - * routes constrain it and its authority policy becomes the child's runtime mode. A child's - * permissions come from its own saved agent's policy or from the human's approval, never from - * the parent: J5 carries no parent-child permission ceiling (Jackson, 2026-09-16), because any - * such guard is one message to a trusting peer away from bypass and every child-creation door - * would have to enforce it identically. - */ -const prepareSpawnPersona = Effect.fn("j5.a2a.mcp.prepareSpawnPersona")(function* ( - input: { - readonly persona: string; - readonly provider: string; - readonly model: string; - readonly reasoning: string; - }, - modelSelection: ModelSelection, -) { - const library = yield* makeAgentPersonaLibrary; - const providers = yield* (yield* ProviderRegistry).getProviders; - const assignment = yield* prepareAgentPersonaPeerSpawn( - { - personaId: input.persona, - provider: providers.find((candidate) => candidate.instanceId === modelSelection.instanceId), - instanceId: modelSelection.instanceId, - model: input.model, - reasoning: input.reasoning, - }, - library, - ).pipe( - Effect.mapError((error) => - stateError( - `Persona ${input.persona} cannot be spawned as requested: ${error.message}`, - "Call orchestrator_capabilities, then retry j5_spawn_agent with a provider, model, and reasoning from that persona's declared routes, or omit persona for a plain Peer Agent.", - ), - ), - ); - const policy = translateAgentPersonaProviderPolicy( - assignment.authorityPolicy, - assignment.resolvedDriver, - ); - return { - assignment, - modelSelection: assignment.resolvedModelSelection, - runtimeMode: policy.runtimeMode, - }; -}); - -/** - * The calling thread as a spawner: its home, its project and its checkout. An outside agent has - * none of these, so `j5_spawn_agent` reads this for a thread caller only. - */ -const preflightThreadSpawner = Effect.fn("j5.a2a.mcp.preflightThreadSpawner")(function* ( - scope: McpThreadInvocationScope, -) { - const caller = yield* preflightSpawnCaller(scope); - // Only a Captain grows a Crew, and only through the human gate (Bryant, 2026-09-14): a seat - // that wants more hands escalates to its Captain; its own helpers are subagents. - const membership = yield* (yield* AgentCrewInstanceService) - .findMembership(caller.participantId) - .pipe( - Effect.mapError((error) => - stateError( - `Crew membership for ${caller.participantId} cannot be read: ${error.message}.`, - "Retry j5_spawn_agent once crew records are readable.", - ), - ), - ); - if (membership !== null) { - return yield* stateError( - `Caller ${caller.participantId} is seat ${membership.seatName} of crew ${membership.crewInstanceId}; crew members cannot spawn Peer Agents.`, - "Ask your Captain for the seat with j5_send_message, or run the work yourself as a subagent with delegate_task.", - ); - } - const parent = yield* (yield* ThreadManagementService) - .getThreadProjection(scope.thread.threadId) - .pipe( - Effect.mapError((error) => - stateError( - `Caller thread ${scope.thread.threadId} cannot be read for j5_spawn_agent: ${error.message}.`, - "Read the caller thread state and retry j5_spawn_agent after it is available.", - ), - ), - ); - return { - participantId: caller.participantId, - // Retry keys are the provider session's, as they were before outside agents could spawn. - requestNamespace: scope.thread.providerSessionId, - home: { - ledgerProject: { id: caller.projectId, title: caller.project.name }, - thread: parent.thread, - }, - outside: undefined, - }; -}); - /** Crew requests come from a Peer Agent with a home that is not itself a crew member (R20). */ const preflightCrewCaptain = Effect.fn("j5.a2a.mcp.preflightCrewCaptain")(function* ( scope: McpThreadInvocationScope, @@ -996,432 +716,7 @@ const handlers = { j5_spawn_agent: McpToolAccess.writes((input) => Effect.gen(function* () { const scope = yield* McpInvocationContext; - const crypto = yield* Crypto.Crypto; - // An outside agent has no thread, home, project or checkout: it is recorded as the spawner - // and the new agent sits at the top level of the project it names. - const outside = yield* outsideAgentCaller; - const spawner = - outside === undefined - ? yield* preflightThreadSpawner(yield* callerScope) - : { - participantId: outsideAgentParticipantId(outside.client.sessionId), - // A new sign-in is a new session, so it is a new set of retry keys. - requestNamespace: scope.requestNamespace, - home: undefined, - outside, - }; - const { home } = spawner; - const requestKey = - input.client_request_id ?? (yield* crypto.randomUUIDv4().pipe(Effect.orDie)); - const stableInput = { providerSessionId: spawner.requestNamespace, requestKey }; - const threadId = spawnThreadId(stableInput); - const threadManagement = yield* ThreadManagementService; - const spawnReadFailure = (error: { readonly message: string }) => - stateError( - `Peer Agent thread ${threadId} could not be read: ${error.message}`, - "Retry j5_spawn_agent with the same client_request_id once it is readable.", - ); - const existing = yield* threadManagement - .getThreadShell(threadId) - .pipe(Effect.mapError(spawnReadFailure)); - const workspaceRequest = - input.workspace.type === "worktree" - ? { ...input.workspace, start_from_origin: input.workspace.start_from_origin ?? false } - : input.workspace.type === "existing_worktree" - ? { - ...input.workspace, - worktree_path: input.workspace.worktree_path.replace(/[\\/]+$/, ""), - } - : input.workspace; - const request = { - ...input, - client_request_id: undefined, - title: input.title ?? null, - scratch: input.scratch ?? false, - workspace: workspaceRequest, - }; - const replayService = yield* RequestReplayService; - const replayFailure = (error: SqlError | RequestReplayConflictError) => - error._tag === "RequestReplayConflictError" - ? stateError(error.message, "Inspect the original target before starting new work.") - : stateError( - `The spawn's client_request_id could not be checked: ${error.message}`, - "Retry j5_spawn_agent with the same client_request_id.", - ); - // A generated key can never be retried, so it has nothing to bind. - const replayable = input.client_request_id !== undefined; - if (replayable) - yield* replayService.check(threadId, request).pipe(Effect.mapError(replayFailure)); - // Refuse invalid uploads before acceptance so corrected metadata can reuse the key. - if (input.attachments !== undefined) { - const attachments = input.attachments; - yield* resolveAttachmentReferences(attachments, []).pipe( - Effect.flatMap(validateAttachmentLimits), - Effect.andThen( - new Set(attachments.map((attachment) => attachment.id)).size === attachments.length - ? Effect.void - : new AttachmentClaimError({ message: "Duplicate attachment ids are not allowed." }), - ), - // Accepted retries may outlive their pending upload; only a new child needs preflight. - Effect.andThen( - existing === null ? preflightSpawnUploads(threadId, attachments) : Effect.void, - ), - Effect.mapError((error) => - stateError( - `Peer Agent was not created: ${error.message}`, - "Retry j5_spawn_agent with corrected attachments; the same client_request_id still works.", - ), - ), - ); - } - const selected = existing?.modelSelection ?? (yield* selectSpawnModel(scope, input)); - const personaId = input.persona; - const persona = - personaId === undefined || existing !== null - ? undefined - : yield* prepareSpawnPersona({ ...input, persona: personaId }, selected); - const modelSelection = existing?.modelSelection ?? persona?.modelSelection ?? selected; - // A persona's policy sets its permissions. Without one the agent gets the caller's modes, - // or the ones the caller chose, which upstream's rule keeps within the caller's own. - if (personaId !== undefined && input.runtime_mode !== undefined) { - return yield* stateError( - `Persona ${personaId} sets its own permission mode, so runtime_mode cannot be chosen for it.`, - "Retry j5_spawn_agent without runtime_mode, or without persona.", - ); - } - const { limits } = yield* loadCaller(); - // An outside persona's replay is capped against the existing thread's modes below. - if (persona !== undefined && personaId !== undefined && outside !== undefined) { - yield* assertPersonaWithinApprovedLevel(outside, personaId, persona.runtimeMode); - } - // With no mode chosen the agent gets the caller's: its thread's, or its approved level. - const runtimeMode = - existing?.runtimeMode ?? - input.runtime_mode ?? - persona?.runtimeMode ?? - home?.thread.runtimeMode ?? - limits.runtimeMode; - const interactionMode = - existing?.interactionMode ?? - input.interaction_mode ?? - home?.thread.interactionMode ?? - limits.interactionMode; - { - // Each mode is held to the caller's own only where the caller chose it, so choosing an - // interaction mode does not put a persona's permission mode under the ceiling. - const exceeded = exceededDispatchModeLimit(limits, { - runtimeMode: input.runtime_mode ?? limits.runtimeMode, - interactionMode: input.interaction_mode ?? limits.interactionMode, - }); - if (exceeded !== undefined) { - return yield* stateError( - `The ${exceeded === "runtime" ? `permission mode ${runtimeMode}` : `interaction mode ${interactionMode}`} is broader than your own.`, - "Retry j5_spawn_agent with a mode no broader than yours, or omit it to give the agent your own.", - ); - } - } - const firstAttempt = existing === null; - // A retry finishes the agent its first attempt created, in the modes it was created with. - // A caller's modes can be narrowed within one provider session, so those are checked - // against what the caller may touch now. A persona's agent runs under its own policy, - // except for an outside agent, whose approved level caps every agent it starts. This early - // check is the only one an unbound legacy agent reaches, since bind refuses it before the - // start; the start checks again for an agent a concurrent attempt created since. - const replayExceedsCaller = (caller: DispatchModes, thread: DispatchModes) => { - if (personaId !== undefined && outside === undefined) return Effect.void; - const exceeded = exceededDispatchModeLimit(caller, thread); - return exceeded === undefined - ? Effect.void - : Effect.fail( - stateError( - `Peer Agent ${participantIdForThread(threadId)} already exists with a ${exceeded === "runtime" ? "permission" : "interaction"} mode broader than yours is now.`, - "Ask the user to start that agent, or spawn a new one with a fresh client_request_id.", - ), - ); - }; - if (existing !== null) yield* replayExceedsCaller(limits, existing); - - // The project the agent joins: the caller's, another one, or upstream's "No project". - if (input.scratch === true && input.project_id !== undefined) { - return yield* stateError( - "scratch spawns an agent without a project, so it cannot be combined with project_id.", - "Retry j5_spawn_agent with one of them.", - ); - } - const target = - input.scratch === true - ? yield* (yield* ManagedProjectFolders).ensureScratchProject.pipe( - Effect.map(({ projectId }) => projectId), - Effect.mapError((error) => - stateError( - `An agent without a project cannot be spawned here: ${error.message}`, - "Retry j5_spawn_agent with a project_id, or without scratch for your own project.", - ), - ), - ) - : input.project_id !== undefined - ? ProjectId.make(input.project_id) - : home === undefined - ? yield* outsideSpawnNeedsProject - : home.thread.projectId; - // The spawner's own project and checkout, when the agent joins that project. - const own = home !== undefined && target === home.thread.projectId ? home : undefined; - const elsewhere = own === undefined; - const targetProject = - own !== undefined - ? own.ledgerProject - : yield* (yield* ProjectService).getById(target).pipe( - Effect.mapError((error) => - stateError( - `Project ${target} cannot be read now: ${error.message}.`, - "Retry j5_spawn_agent.", - ), - ), - Effect.flatMap( - Option.match({ - onNone: () => - Effect.fail( - stateError( - `This server has no project ${target}.`, - "Call t3_project_list and retry j5_spawn_agent with one of its project ids.", - ), - ), - onSome: (project) => - Effect.succeed({ id: LedgerProjectId.make(project.id), title: project.title }), - }), - ), - ); - if (input.scratch === true && input.workspace.type !== "root") { - return yield* stateError( - "An agent without a project works in a folder of its own, not in a checkout or a worktree.", - 'Retry j5_spawn_agent with workspace {"type":"root"}.', - ); - } - if (home === undefined && input.workspace.type === "shared") { - return yield* outsideSpawnHasNoCheckout; - } - if (elsewhere && input.workspace.type === "shared") { - return yield* stateError( - `Your own checkout belongs to your project, and this agent joins project ${target}.`, - 'Retry j5_spawn_agent with workspace {"type":"root"} for that project\'s main checkout, or a worktree of it.', - ); - } - const spawnWorkspace = yield* SpawnWorkspaceService; - // The project's main checkout binds nothing, so it travels as the shared type with no - // checkout to share: one create command, and nothing asked of git. - const choice = - input.workspace.type === "root" - ? ({ type: "shared" } as const) - : spawnWorkspaceFromInput(input.workspace); - // A replay must not refuse the branch its own first attempt created, so a named branch is - // checked for only before the thread exists. - const checkBranches = - choice.type === "worktree" && choice.branch !== undefined && firstAttempt; - // Sharing a checkout asks nothing of git. - const checkout = - choice.type === "shared" - ? null - : yield* spawnWorkspace.inspect({ - projectId: target, - worktreePath: own?.thread.worktreePath ?? null, - checkBranches, - baseRefs: namedBaseRefs([choice]), - existingWorktreePaths: namedWorktreePaths([choice]), - }); - const workspace = yield* Effect.fromResult( - checkout === null - ? Result.succeed({ type: "shared" } as const) - : resolveSpawnWorkspace(checkout, choice), - ).pipe( - Effect.mapError((error) => - stateError(`Peer Agent was not created: ${error.detail}`, error.nextStep), - ), - ); - if (replayable) - yield* replayService - .bind({ - id: threadId, - target: `Peer Agent ${participantIdForThread(threadId)} on thread ${threadId}`, - request, - legacy: existing !== null, - }) - .pipe(Effect.mapError(replayFailure)); - return yield* spawnWorkspace - .withSpawnStart( - { stableInput, threadId, workspace }, - Effect.gen(function* () { - // What a shared-type thread binds: the caller's checkout, or the project's main one. - // As upstream's launch does, a main-checkout thread asks for a folder of its own, and - // gets one only in the "No project" project. It is claimed here, inside the start - // that only one call at a time may run, and only before the thread exists; a replay - // replays its create. The thread is looked for again now that this call holds the - // start: an earlier attempt may have created it since the read above. - const current = yield* threadManagement - .getThreadShell(threadId) - .pipe(Effect.mapError(spawnReadFailure)); - if (current !== null) yield* replayExceedsCaller((yield* loadCaller()).limits, current); - const sharedCheckout = - current !== null - ? current - : input.workspace.type !== "root" && home !== undefined - ? home.thread - : { - branch: null, - worktreePath: Option.getOrNull( - yield* (yield* ManagedProjectFolders) - .folderForThread({ projectId: target, threadId, text: input.brief }) - .pipe( - Effect.mapError((error) => - stateError( - `A folder for the agent could not be made: ${error.message}`, - "Retry j5_spawn_agent with the same client_request_id.", - ), - ), - ), - ), - }; - yield* threadManagement - .dispatch({ - type: "thread.create", - createdBy: "agent", - creationSource: "mcp", - commandId: spawnCreateCommandId(stableInput, workspace.type), - threadId, - projectId: target, - title: spawnTitle(input.brief, input.title), - modelSelection: current?.modelSelection ?? modelSelection, - runtimeMode: current?.runtimeMode ?? runtimeMode, - interactionMode: current?.interactionMode ?? interactionMode, - ...(persona === undefined ? {} : { agentPersonaAssignment: persona.assignment }), - ...(current === null - ? spawnThreadCheckout(workspace, sharedCheckout) - : { branch: current.branch, worktreePath: current.worktreePath }), - }) - .pipe( - Effect.mapError((error) => - stateError( - `Peer Agent thread ${threadId} could not be created: ${error.message}.`, - error._tag === "OrchestratorCommandPreviouslyRejectedError" - ? "Inspect the rejection, correct the request, and retry j5_spawn_agent with a fresh client_request_id; the rejected key is permanently bound." - : "Inspect the caller thread and provider state, then retry j5_spawn_agent with the same client_request_id.", - ), - ), - ); - const child = yield* threadManagement - .getThreadProjection(threadId) - .pipe( - Effect.mapError((error) => - stateError( - `Created Peer Agent thread ${threadId} is not readable: ${error.message}.`, - "Retry j5_spawn_agent with the same client_request_id so registration can continue safely.", - ), - ), - ); - const facts = yield* (yield* SpawnCompositionService) - .recordFacts({ - homeCommandId: spawnHomeCommandId(stableInput), - placementCommandId: spawnPlacementCommandId(stableInput), - projectId: targetProject.id, - threadId, - provenance: { - kind: "spawned-by", - spawnedByParticipantId: spawner.participantId, - source: "j5_spawn", - }, - ...(outside === undefined ? {} : { outsideSpawnerName: outside.client.label }), - createdAt: DateTime.formatIso(child.thread.createdAt), - }) - .pipe( - Effect.mapError((error) => - stateError( - `Peer Agent thread ${threadId} exists as a visible orphan without committed home/placement facts or a started brief: ${error.message}.`, - "Retry j5_spawn_agent with the same client_request_id only after repairing transient state; otherwise ask the human operator to retire or repair the orphan after A9 lifecycle support lands.", - ), - ), - ); - // In the spawner's own project the agent sits under it; in another it is a root, as - // is every agent an outside agent starts. - if ( - facts.placement.provenance.kind !== "spawned-by" || - facts.placement.provenance.source !== "j5_spawn" || - (facts.placement.placementParentId === null) !== elsewhere - ) { - return yield* stateError( - `Peer Agent ${facts.home.participantId} committed placement facts that do not satisfy the J5 spawn contract.`, - "Call j5_list_participants to inspect committed placement truth and ask the human operator to repair the inconsistent record.", - ); - } - // The brief's files are claimed into the new thread, which now exists. - const attachments = - input.attachments === undefined - ? [] - : (yield* resolveAttachmentReferences(input.attachments, []).pipe( - Effect.flatMap((references) => - claimPendingAttachments({ threadId, attachments: references }), - ), - Effect.mapError((error) => - stateError( - `Peer Agent ${facts.home.participantId} is registered and addressable, but its brief's attachments could not be claimed: ${error.message}`, - "Retry j5_spawn_agent with the same client_request_id and the original attachment ids after repairing the upload; use a fresh client_request_id for a changed brief.", - ), - ), - )).attachments; - yield* spawnWorkspace - .startBrief({ - workspace, - stableInput, - ledgerProjectId: facts.home.projectId, - projectId: target, - threadId, - title: spawnTitle(input.brief, input.title), - messageId: spawnMessageId(stableInput), - text: spawnFirstTurnText({ - brief: input.brief, - participantId: facts.home.participantId, - projectId: facts.home.projectId, - projectTitle: targetProject.title, - spawnedByParticipantId: spawner.participantId, - ...(outside === undefined - ? { spawnerThreadId: scope.thread?.threadId } - : { outsideAgentName: outside.client.label }), - }), - modelSelection: child.thread.modelSelection, - runtimeMode: child.thread.runtimeMode, - interactionMode: child.thread.interactionMode, - attachments, - }) - .pipe( - Effect.mapError((error) => - stateError( - `Peer Agent ${facts.home.participantId} is registered and addressable, but its brief did not start: ${error.message}.`, - "Retry j5_spawn_agent with the same client_request_id to start the same brief safely.", - ), - ), - ); - return { - participant_id: facts.home.participantId, - thread_id: threadId, - project_id: facts.home.projectId, - project_title: targetProject.title, - placement: { - placement_parent_id: facts.placement.placementParentId, - provenance: { - kind: "spawned-by" as const, - spawned_by_participant_id: facts.placement.provenance.spawnedByParticipantId, - source: facts.placement.provenance.source, - }, - }, - }; - }), - ) - .pipe( - Effect.catchTags({ - SpawnWorkspaceError: (error) => - Effect.fail( - stateError(`Peer Agent was not created: ${error.detail}`, error.nextStep), - ), - }), - ); + return yield* (yield* SpawnAgentService.SpawnAgentService).spawn(input, scope); }).pipe(Effect.mapError(failure)), ), j5_propose_crew: actsAsThreadCaller( @@ -1722,4 +1017,6 @@ const handlers = { export const layer = McpToolAccess.toLayer(J5Toolkit, handlers); /** The same handlers as a plain layer, for tests that call a tool without registering it. */ -export const J5ToolkitHandlersLive = McpToolAccess.HandlersLayer.layer(layer); +export const J5ToolkitHandlersLive = McpToolAccess.HandlersLayer.layer(layer).pipe( + Layer.provideMerge(SpawnAgentService.layer), +); diff --git a/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index abc937c6a5901..0be75899a0bf7 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -1,3 +1,4 @@ +import * as SpawnAgentService from "../SpawnAgentService.ts"; import { RequestReplayService } from "../RequestReplayService.ts"; import { Tool, Toolkit } from "effect/ai"; import { playbookTools } from "../../playbooks/mcp.ts"; @@ -260,21 +261,6 @@ export const J5SpawnWorkspace = Schema.Union([ ]); export type J5SpawnWorkspace = typeof J5SpawnWorkspace.Type; -/** The stored camelCase form of an MCP workspace choice; unset fields stay unset. */ -export const spawnWorkspaceFromInput = (workspace: J5SpawnWorkspace) => - workspace.type === "shared" - ? { type: "shared" as const } - : workspace.type === "existing_worktree" - ? { type: "existing_worktree" as const, worktreePath: workspace.worktree_path } - : { - type: "worktree" as const, - baseRef: workspace.base_ref, - ...(workspace.branch === undefined ? {} : { branch: workspace.branch }), - ...(workspace.start_from_origin === undefined - ? {} - : { startFromOrigin: workspace.start_from_origin }), - }; - /** * A spawn's workspace choice: a Crew seat's three, and the project's own checkout, which is * upstream's `root`. A spawn into another project has no "your own checkout" to share. @@ -614,6 +600,7 @@ const placementDependencies = [ ]; const spawnDependencies = [ + SpawnAgentService.SpawnAgentService, McpInvocationContext.McpInvocationContext, A2ASendService, Crypto.Crypto, diff --git a/apps/server/src/j5/a2a/runtimeLayer.ts b/apps/server/src/j5/a2a/runtimeLayer.ts index 1f80d4a9e93af..a97093c39db62 100644 --- a/apps/server/src/j5/a2a/runtimeLayer.ts +++ b/apps/server/src/j5/a2a/runtimeLayer.ts @@ -1,3 +1,4 @@ +import * as SpawnAgentService from "./SpawnAgentService.ts"; import * as Layer from "effect/Layer"; import { layerEventSink as OrchestrationV2EventSinkLayerLive } from "../../orchestration-v2/runtimeLayer.ts"; import { layer as playbookCrewRelayLayer } from "../playbooks/PlaybookCrewRelay.ts"; @@ -232,6 +233,7 @@ export const makeJ5A2AAuxiliaryLayer = ( archiveFactsProvided, spawnWorkspaceProvided, requestReplayLayer, + SpawnAgentService.layer, agentCrewInstanceLayer, archiveCrewProvided, crewProposalProvided, diff --git a/apps/server/src/j5/a2a/spawnWorkspace.test.ts b/apps/server/src/j5/a2a/spawnWorkspace.test.ts index c7f440b207a5e..5a7c2e0544434 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.test.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.test.ts @@ -1,3 +1,4 @@ +import * as SpawnAgentService from "./SpawnAgentService.ts"; import { assert, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { @@ -459,9 +460,17 @@ const spawnHarness = (input: { Effect.provideService(McpInvocationContext, input.scope ?? invocation), ); }); + const serviceCall = (args: J5SpawnAgentInput) => + Effect.gen(function* () { + const service = yield* SpawnAgentService.SpawnAgentService; + return yield* service + .spawn(args, input.scope ?? invocation) + .pipe(Effect.provideService(McpInvocationContext, input.scope ?? invocation)); + }); return { layer, call, + serviceCall, log, commands, launches, @@ -485,6 +494,32 @@ const spawnArgs = { const message = (response: { readonly result: unknown }) => (response.result as { readonly message: string }).message; +it.effect("accepts and replays a direct domain-service spawn", () => + Effect.gen(function* () { + const { layer, serviceCall, commands } = yield* spawnHarness({ + checkout: { isRepo: true, refName: "j5/main" }, + }); + yield* Effect.gen(function* () { + const args = { + ...spawnArgs, + workspace: { type: "shared" as const }, + client_request_id: "domain-service", + }; + const original = yield* serviceCall(args); + assert.deepStrictEqual(yield* serviceCall(args), original); + const beforeRefusal = yield* Ref.get(commands); + const refused = yield* serviceCall({ ...args, brief: "Different work" }).pipe(Effect.flip); + assert.include(refused.message, "different request"); + assert.deepStrictEqual(yield* Ref.get(commands), beforeRefusal); + const briefIds = beforeRefusal.flatMap((command) => + command.type === "message.dispatch" ? [command.commandId] : [], + ); + assert.isAbove(briefIds.length, 0); + assert.lengthOf([...new Set(briefIds)], 1, "retries keep the same dispatch identity"); + }).pipe(Effect.provide(layer)); + }), +); + it.effect("spawns into another project's main checkout, as a root of that project", () => Effect.gen(function* () { const { layer, call, commands, factProjects } = yield* spawnHarness({ @@ -1020,6 +1055,7 @@ it.effect.each(["size", "type"] as const)( : { ...attachment, mimeType: "image/jpeg" }; const refused = yield* call({ ...args, attachments: [incorrect] }); assert.isTrue(refused.isFailure); + assert.notInclude(message(refused), attachment.name); assert.include( message(refused), mismatch === "size" ? "stored size does not match" : "type does not match", diff --git a/apps/server/src/j5/a2a/spawnWorkspace.ts b/apps/server/src/j5/a2a/spawnWorkspace.ts index 927e0c97ac7a7..0fd1f8852e5b2 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.ts @@ -1,3 +1,4 @@ +import type { J5SpawnWorkspace } from "./mcp/tools.ts"; import type { ChatAttachment, CommandId, @@ -544,3 +545,18 @@ export const layerFromReceiptStore = Layer.effect(SpawnWorkspaceService, make); /** The receipt store is a stateless reader over the shared receipt table, built here for J5. */ export const layer = layerFromReceiptStore.pipe(Layer.provide(commandReceiptStoreLayer)); + +/** The stored camelCase form of an MCP workspace choice; unset fields stay unset. */ +export const spawnWorkspaceFromInput = (workspace: J5SpawnWorkspace) => + workspace.type === "shared" + ? { type: "shared" as const } + : workspace.type === "existing_worktree" + ? { type: "existing_worktree" as const, worktreePath: workspace.worktree_path } + : { + type: "worktree" as const, + baseRef: workspace.base_ref, + ...(workspace.branch === undefined ? {} : { branch: workspace.branch }), + ...(workspace.start_from_origin === undefined + ? {} + : { startFromOrigin: workspace.start_from_origin }), + }; diff --git a/apps/server/src/mcp/toolkits/worktree/registration.test.ts b/apps/server/src/mcp/toolkits/worktree/registration.test.ts index 6dcc0c05edf47..67b4c24f0f59d 100644 --- a/apps/server/src/mcp/toolkits/worktree/registration.test.ts +++ b/apps/server/src/mcp/toolkits/worktree/registration.test.ts @@ -1,3 +1,4 @@ +import * as SpawnAgentService from "../../../j5/a2a/SpawnAgentService.ts"; import { RequestReplayService } from "../../../j5/a2a/RequestReplayService.ts"; import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts"; import * as ProjectionStore from "../../../orchestration-v2/ProjectionStore.ts"; @@ -101,6 +102,7 @@ const layerStubServices = Layer.mergeAll( Layer.mock(PlaybookStore)({}), Layer.mock(SpawnCompositionService)({}), Layer.mock(RequestReplayService)({}), + SpawnAgentService.layer, Layer.mock(SpawnWorkspaceService)({}), Layer.mock(ThreadRegistration)({}), ); From abb7269552c644668fe96434141a6da9cabb8eee Mon Sep 17 00:00:00 2001 From: Bastian Huppertz Date: Fri, 23 Oct 2026 15:46:50 +0200 Subject: [PATCH 8/9] fix(j5): complete replay recovery and canonical contracts --- .../src/j5/a2a/RequestReplayService.test.ts | 27 +++- .../server/src/j5/a2a/RequestReplayService.ts | 30 ++-- apps/server/src/j5/a2a/SpawnAgentService.ts | 69 +++++---- apps/server/src/j5/a2a/mcp/handlers.ts | 2 +- apps/server/src/j5/a2a/mcp/tools.test.ts | 28 ++++ apps/server/src/j5/a2a/mcp/tools.ts | 4 +- apps/server/src/j5/a2a/runtimeLayer.ts | 4 +- apps/server/src/j5/a2a/spawnWorkspace.test.ts | 142 ++++++++++++++++-- apps/server/src/j5/a2a/spawnWorkspace.ts | 48 ++++-- .../a2a/test-support/spawnWorkspaceFakes.ts | 6 +- .../toolkits/worktree/registration.test.ts | 4 +- docs/j5/product/a2a/agent-tools.md | 5 +- 12 files changed, 288 insertions(+), 81 deletions(-) diff --git a/apps/server/src/j5/a2a/RequestReplayService.test.ts b/apps/server/src/j5/a2a/RequestReplayService.test.ts index 77ac4dc18970c..131487b1a30f4 100644 --- a/apps/server/src/j5/a2a/RequestReplayService.test.ts +++ b/apps/server/src/j5/a2a/RequestReplayService.test.ts @@ -8,7 +8,7 @@ import * as Path from "effect/Path"; import * as Result from "effect/Result"; import * as SqlClient from "effect/sql/SqlClient"; import migration from "./migrations/044_RequestReplay.ts"; -import { RequestReplayService, layer } from "./RequestReplayService.ts"; +import * as RequestReplayService from "./RequestReplayService.ts"; it.effect("persists the original request across database reopen and refuses changed reuse", () => Effect.gen(function* () { @@ -24,12 +24,16 @@ it.effect("persists the original request across database reopen and refuses chan yield* Effect.scoped( Effect.gen(function* () { yield* migration; - yield* (yield* RequestReplayService).bind(first); - }).pipe(Effect.provide(layer.pipe(Layer.provideMerge(NodeSqliteClient.layer({ filename }))))), + yield* (yield* RequestReplayService.RequestReplayService).bind(first); + }).pipe( + Effect.provide( + RequestReplayService.layer.pipe(Layer.provideMerge(NodeSqliteClient.layer({ filename }))), + ), + ), ); yield* Effect.scoped( Effect.gen(function* () { - const replay = yield* RequestReplayService; + const replay = yield* RequestReplayService.RequestReplayService; yield* replay.bind({ ...first, legacy: true, @@ -57,9 +61,18 @@ it.effect("persists the original request across database reopen and refuses chan .bind({ ...first, id: "legacy", legacy: true }) .pipe(Effect.result); assert.isTrue(Result.isFailure(legacy)); - if (Result.isFailure(legacy)) - assert.include(legacy.failure.message, "predates replay verification"); - }).pipe(Effect.provide(layer.pipe(Layer.provideMerge(NodeSqliteClient.layer({ filename }))))), + if (Result.isFailure(legacy)) { + assert.equal(legacy.failure._tag, "RequestReplayUnverifiableError"); + assert.equal( + legacy.failure.message, + "The original request for agent:original predates replay verification and cannot be compared. Inspect that target and use a fresh client_request_id for new work.", + ); + } + }).pipe( + Effect.provide( + RequestReplayService.layer.pipe(Layer.provideMerge(NodeSqliteClient.layer({ filename }))), + ), + ), ); }).pipe(Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/j5/a2a/RequestReplayService.ts b/apps/server/src/j5/a2a/RequestReplayService.ts index f9cae1d1df23e..eec5b15e4d20e 100644 --- a/apps/server/src/j5/a2a/RequestReplayService.ts +++ b/apps/server/src/j5/a2a/RequestReplayService.ts @@ -15,16 +15,24 @@ export const requestReplayConflict = (target: string) => ({ export class RequestReplayConflictError extends Schema.TaggedError()( "RequestReplayConflictError", - { target: Schema.String, legacy: Schema.Boolean }, + { target: Schema.String }, ) { override get message() { - if (this.legacy) - return `The original request for ${this.target} predates replay verification and cannot be compared. Inspect that target and use a fresh client_request_id for new work.`; const { detail, nextStep } = requestReplayConflict(this.target); return `${detail} ${nextStep}`; } } +/** The target exists from before replay binding, so no stored request proves this one is it. */ +export class RequestReplayUnverifiableError extends Schema.TaggedError()( + "RequestReplayUnverifiableError", + { target: Schema.String }, +) { + override get message() { + return `The original request for ${this.target} predates replay verification and cannot be compared. Inspect that target and use a fresh client_request_id for new work.`; + } +} + const canonical = (value: unknown): unknown => { if (Array.isArray(value)) return value.map(canonical); if (value === null || typeof value !== "object") return value; @@ -54,7 +62,10 @@ export class RequestReplayService extends Context.Service< readonly target: string; readonly request: unknown; readonly legacy: boolean; - }) => Effect.Effect; + }) => Effect.Effect< + void, + SqlError | RequestReplayConflictError | RequestReplayUnverifiableError + >; } >()("t3/j5/a2a/RequestReplayService") {} @@ -69,7 +80,7 @@ export const layer = Layer.effect( `; const original = rows[0]; if (original !== undefined && original.request_digest !== requestDigest(request)) - return yield* new RequestReplayConflictError({ target: original.target, legacy: false }); + return yield* new RequestReplayConflictError({ target: original.target }); }, ); const bind: RequestReplayService["Service"]["bind"] = Effect.fn("j5.requestReplay.bind")( @@ -86,11 +97,10 @@ export const layer = Layer.effect( SELECT target, request_digest FROM j5_a2a_request_replay WHERE id = ${input.id} `; const original = rows[0]; - if (original === undefined || original.request_digest !== digest) - return yield* new RequestReplayConflictError({ - target: original?.target ?? input.target, - legacy: original === undefined, - }); + if (original === undefined) + return yield* new RequestReplayUnverifiableError({ target: input.target }); + if (original.request_digest !== digest) + return yield* new RequestReplayConflictError({ target: original.target }); }, sql.withTransaction, ); diff --git a/apps/server/src/j5/a2a/SpawnAgentService.ts b/apps/server/src/j5/a2a/SpawnAgentService.ts index fb2acccd0ff7c..c0d732d2c4d24 100644 --- a/apps/server/src/j5/a2a/SpawnAgentService.ts +++ b/apps/server/src/j5/a2a/SpawnAgentService.ts @@ -51,16 +51,8 @@ import { } from "./mcp/outsideAgent.ts"; import type { J5SpawnAgentInput } from "./mcp/tools.ts"; -import { type RequestReplayConflictError, RequestReplayService } from "./RequestReplayService.ts"; -import { - SpawnWorkspaceService, - namedBaseRefs, - namedWorktreePaths, - resolveSpawnWorkspace, - spawnCreateCommandId, - spawnThreadCheckout, - spawnWorkspaceFromInput, -} from "./spawnWorkspace.ts"; +import * as RequestReplayService from "./RequestReplayService.ts"; +import * as SpawnWorkspace from "./spawnWorkspace.ts"; import { spawnThreadId, spawnHomeCommandId, @@ -72,7 +64,7 @@ import { import { ChatAttachmentId, type ChatAttachment, type ThreadId } from "@t3tools/contracts"; import * as FileSystem from "effect/FileSystem"; import { planAttachmentClaim, resolveAttachmentPath } from "../../attachmentStore.ts"; -import { ServerConfig } from "../../config.ts"; +import * as ServerConfig from "../../config.ts"; export class SpawnAgentService extends Context.Service< SpawnAgentService, { @@ -241,7 +233,7 @@ const preflightSpawnUploads = Effect.fn("j5.a2a.mcp.preflightSpawnUploads")(func threadId: ThreadId, attachments: ReadonlyArray, ) { - const config = yield* ServerConfig; + const config = yield* ServerConfig.ServerConfig; const fs = yield* FileSystem.FileSystem; yield* Effect.forEach( attachments, @@ -333,14 +325,24 @@ const spawn = Effect.fn("j5.a2a.spawnAgent")(function* ( scratch: input.scratch ?? false, workspace: workspaceRequest, }; - const replayService = yield* RequestReplayService; - const replayFailure = (error: SqlError | RequestReplayConflictError) => - error._tag === "RequestReplayConflictError" - ? stateError(error.message, "Inspect the original target before starting new work.") - : stateError( + const replayService = yield* RequestReplayService.RequestReplayService; + const replayFailure = ( + error: + | SqlError + | RequestReplayService.RequestReplayConflictError + | RequestReplayService.RequestReplayUnverifiableError, + ) => { + switch (error._tag) { + case "SqlError": + return stateError( `The spawn's client_request_id could not be checked: ${error.message}`, "Retry j5_spawn_agent with the same client_request_id.", ); + case "RequestReplayConflictError": + case "RequestReplayUnverifiableError": + return stateError(error.message, "Inspect the original target before starting new work."); + } + }; // A generated key can never be retried, so it has nothing to bind. const replayable = input.client_request_id !== undefined; if (replayable) @@ -499,13 +501,13 @@ const spawn = Effect.fn("j5.a2a.spawnAgent")(function* ( 'Retry j5_spawn_agent with workspace {"type":"root"} for that project\'s main checkout, or a worktree of it.', ); } - const spawnWorkspace = yield* SpawnWorkspaceService; + const spawnWorkspace = yield* SpawnWorkspace.SpawnWorkspaceService; // The project's main checkout binds nothing, so it travels as the shared type with no // checkout to share: one create command, and nothing asked of git. const choice = input.workspace.type === "root" ? ({ type: "shared" } as const) - : spawnWorkspaceFromInput(input.workspace); + : SpawnWorkspace.spawnWorkspaceFromInput(input.workspace); // A replay must not refuse the branch its own first attempt created, so a named branch is // checked for only before the thread exists. const checkBranches = choice.type === "worktree" && choice.branch !== undefined && firstAttempt; @@ -517,13 +519,13 @@ const spawn = Effect.fn("j5.a2a.spawnAgent")(function* ( projectId: target, worktreePath: own?.thread.worktreePath ?? null, checkBranches, - baseRefs: namedBaseRefs([choice]), - existingWorktreePaths: namedWorktreePaths([choice]), + baseRefs: SpawnWorkspace.namedBaseRefs([choice]), + existingWorktreePaths: SpawnWorkspace.namedWorktreePaths([choice]), }); const workspace = yield* Effect.fromResult( checkout === null ? Result.succeed({ type: "shared" } as const) - : resolveSpawnWorkspace(checkout, choice), + : SpawnWorkspace.resolveSpawnWorkspace(checkout, choice), ).pipe( Effect.mapError((error) => stateError(`Peer Agent was not created: ${error.detail}`, error.nextStep), @@ -577,7 +579,7 @@ const spawn = Effect.fn("j5.a2a.spawnAgent")(function* ( type: "thread.create", createdBy: "agent", creationSource: "mcp", - commandId: spawnCreateCommandId(stableInput, workspace.type), + commandId: SpawnWorkspace.spawnCreateCommandId(stableInput, workspace.type), threadId, projectId: target, title: spawnTitle(input.brief, input.title), @@ -586,7 +588,7 @@ const spawn = Effect.fn("j5.a2a.spawnAgent")(function* ( interactionMode: current?.interactionMode ?? interactionMode, ...(persona === undefined ? {} : { agentPersonaAssignment: persona.assignment }), ...(current === null - ? spawnThreadCheckout(workspace, sharedCheckout) + ? SpawnWorkspace.spawnThreadCheckout(workspace, sharedCheckout) : { branch: current.branch, worktreePath: current.worktreePath }), }) .pipe( @@ -643,9 +645,24 @@ const spawn = Effect.fn("j5.a2a.spawnAgent")(function* ( "Call j5_list_participants to inspect committed placement truth and ask the human operator to repair the inconsistent record.", ); } - // The brief's files are claimed into the new thread, which now exists. + // The brief's files are claimed into the new thread, which now exists. Once the brief's + // receipt shows it accepted, they are the thread's already: claiming again would copy them + // a second time, and fails once the pending upload is swept. A thread without that + // receipt never got its brief, so a retry still claims. + const briefAccepted = + current !== null && + (yield* spawnWorkspace + .briefAccepted({ stableInput, workspace: workspace.type }) + .pipe( + Effect.mapError((error) => + stateError( + `Peer Agent ${facts.home.participantId} is registered and addressable, but whether its brief started could not be read: ${error.message}`, + "Retry j5_spawn_agent with the same client_request_id.", + ), + ), + )); const attachments = - input.attachments === undefined + input.attachments === undefined || briefAccepted ? [] : (yield* resolveAttachmentReferences(input.attachments, []).pipe( Effect.flatMap((references) => diff --git a/apps/server/src/j5/a2a/mcp/handlers.ts b/apps/server/src/j5/a2a/mcp/handlers.ts index 8aeac3112730e..1959d03562e57 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -711,7 +711,7 @@ const handlers = { }).pipe(Effect.mapError(failure)), ), // Declared `writes`, as send and stop are, so an outside agent is admitted and a read-only - // client is refused. The handler holds the chosen modes to the caller's limits itself: a + // client is refused. The spawn service holds the chosen modes to the caller's limits: a // thread's own modes, or the level an outside agent's sign-in was approved at. j5_spawn_agent: McpToolAccess.writes((input) => Effect.gen(function* () { diff --git a/apps/server/src/j5/a2a/mcp/tools.test.ts b/apps/server/src/j5/a2a/mcp/tools.test.ts index 62b7dd6a3aa40..5d0c1fece13d9 100644 --- a/apps/server/src/j5/a2a/mcp/tools.test.ts +++ b/apps/server/src/j5/a2a/mcp/tools.test.ts @@ -1,6 +1,9 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { ProviderInstanceId } from "@t3tools/contracts"; import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Schema from "effect/Schema"; import { Tool } from "effect/ai"; @@ -25,6 +28,31 @@ import { const decodeProposeCrew = Schema.decodeUnknownSync(J5ProposeCrewInput); const decodeRequestCrewMember = Schema.decodeUnknownSync(J5RequestCrewMemberInput); +it.effect("publishes the canonical spawn description byte-for-byte", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const document = yield* fileSystem.readFileString( + decodeURIComponent( + new URL("../../../../../../docs/j5/product/a2a/agent-tools.md", import.meta.url).pathname, + ), + ); + const description = document.match( + /### `j5_spawn_agent`[\s\S]*?\*\*Description \(contract\):\*\* "([\s\S]*?)"\n\n\| Input/, + )?.[1]; + if (description === undefined) { + return yield* Effect.die( + "j5_spawn_agent contract description is missing from agent-tools.md", + ); + } + const documentedDescription = description + .split("\n") + .map((line) => line.trim()) + .join(" "); + assert.equal(J5_SPAWN_AGENT_DESCRIPTION, documentedDescription); + assert.equal(J5SpawnAgentTool.description, documentedDescription); + }).pipe(Effect.provide(NodeServices.layer)), +); + it("publishes the ratified single-target lifecycle contracts fail-closed", () => { assert.equal(J5SendMessageTool.description, A2A_SEND_TOOL_DESCRIPTION); assert.include( diff --git a/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index 0be75899a0bf7..baa555ac94d9a 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -1,5 +1,5 @@ import * as SpawnAgentService from "../SpawnAgentService.ts"; -import { RequestReplayService } from "../RequestReplayService.ts"; +import * as RequestReplayService from "../RequestReplayService.ts"; import { Tool, Toolkit } from "effect/ai"; import { playbookTools } from "../../playbooks/mcp.ts"; import * as Schema from "effect/Schema"; @@ -608,7 +608,7 @@ const spawnDependencies = [ ThreadRegistration, A2ALedger, SpawnCompositionService, - RequestReplayService, + RequestReplayService.RequestReplayService, // Resolves the workspace, binds the request key to it, and starts the brief. SpawnWorkspaceService, ThreadManagementService, diff --git a/apps/server/src/j5/a2a/runtimeLayer.ts b/apps/server/src/j5/a2a/runtimeLayer.ts index a97093c39db62..4b126b62c27dc 100644 --- a/apps/server/src/j5/a2a/runtimeLayer.ts +++ b/apps/server/src/j5/a2a/runtimeLayer.ts @@ -50,7 +50,7 @@ import { layer as peerAdminLayer } from "./PeerAdminService.ts"; import { layer as threadRegistrationLayer } from "./ThreadRegistration.ts"; import { layer as spawnCompositionLayer } from "./SpawnCompositionService.ts"; import { layer as spawnWorkspaceLayer } from "./spawnWorkspace.ts"; -import { layer as requestReplayLayer } from "./RequestReplayService.ts"; +import * as RequestReplayService from "./RequestReplayService.ts"; import { layer as sharedConversationLayer } from "../sharing/SharedConversation.ts"; import { layer as sharedThreadsLayer } from "../sharing/SharedThreads.ts"; import { layer as agentHandoffArtifactDeleteLayer } from "../agents/agentHandoffArtifactDelete.ts"; @@ -232,7 +232,7 @@ export const makeJ5A2AAuxiliaryLayer = ( lifecycleServiceProvided, archiveFactsProvided, spawnWorkspaceProvided, - requestReplayLayer, + RequestReplayService.layer, SpawnAgentService.layer, agentCrewInstanceLayer, archiveCrewProvided, diff --git a/apps/server/src/j5/a2a/spawnWorkspace.test.ts b/apps/server/src/j5/a2a/spawnWorkspace.test.ts index 5a7c2e0544434..07a1041ca9179 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.test.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.test.ts @@ -4,6 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { type AuthMcpClientAccess, ChatAttachmentId, + CommandId, EnvironmentId, ProjectId, ProviderDriverKind, @@ -15,7 +16,7 @@ import { } from "@t3tools/contracts"; import * as Context from "effect/Context"; import { layerMemory } from "../../persistence/Sqlite.ts"; -import { RequestReplayService, layer as requestReplayLayer } from "./RequestReplayService.ts"; +import * as RequestReplayService from "./RequestReplayService.ts"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -169,7 +170,7 @@ const callerThread = (threadId: ThreadId, runtimeMode: RuntimeMode = "full-acces const spawnHarness = (input: { readonly checkout: FakeCheckout; - readonly replay?: Layer.Layer; + readonly replay?: Layer.Layer; /** Git as an agent's shell leaves it, served through upstream-style cached refs. */ readonly liveCheckout?: Ref.Ref; /** The durable command log; pass one from an earlier harness to model a restart. */ @@ -436,13 +437,13 @@ const spawnHarness = (input: { ...(input.liveCheckout === undefined ? {} : { liveCheckout: input.liveCheckout }), launches, launch: () => Ref.update(log, (items) => [...items, "launch"]), - // An accepted create leaves its receipt, as the orchestrator's does. - accepted: Ref.get(commands).pipe( - Effect.map((all) => - all.flatMap((command) => - command.type === "thread.create" ? [command.commandId] : [], - ), - ), + // An accepted command leaves its receipt, as the orchestrator's does, and a launch its + // initial message's, as ThreadLaunch's does. + accepted: Effect.all([Ref.get(commands), Ref.get(launches)]).pipe( + Effect.map(([all, launched]) => [ + ...all.map((command) => command.commandId), + ...launched.map((launch) => CommandId.make(`${launch.commandId}:initial-message`)), + ]), ), }), ), @@ -978,6 +979,110 @@ it.effect("claims the brief's attachments into the new agent's thread", () => }), ); +/** A finished pending upload of three bytes, as the attachment tool leaves one. */ +const writePendingUpload = Effect.gen(function* () { + const config = yield* ServerConfig; + const fs = yield* FileSystem.FileSystem; + const attachment = { + type: "image" as const, + id: ChatAttachmentId.make(createPendingAttachmentId()!), + name: "screen.png", + mimeType: "image/png", + sizeBytes: 3, + }; + const path = resolveAttachmentPath({ attachmentsDir: config.attachmentsDir, attachment })!; + yield* fs.writeFile(path, new Uint8Array([1, 2, 3])); + const stored = fs.readDirectory(config.attachmentsDir).pipe(Effect.map((names) => names.length)); + return { attachment, path, stored }; +}); + +it.effect.each(["shared", "worktree"] as const)( + "replays an accepted %s spawn without claiming its files again, even after the upload is swept", + (type) => + Effect.gen(function* () { + const { layer, call, commands, launches } = yield* spawnHarness({ + checkout: { isRepo: true, refName: "j5/main" }, + }); + yield* Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const upload = yield* writePendingUpload; + const args = { + ...spawnArgs, + workspace: + type === "shared" + ? { type: "shared" as const } + : { type: "worktree" as const, base_ref: "j5/main" }, + attachments: [upload.attachment], + client_request_id: `accepted-attached-${type}`, + }; + const original = yield* call(args); + assert.isFalse(original.isFailure); + const briefs = Effect.all([Ref.get(commands), Ref.get(launches)]).pipe( + Effect.map(([all, launched]) => [ + ...all.flatMap((command) => + command.type === "message.dispatch" ? [command.attachments] : [], + ), + ...launched.map((launch) => launch.initialMessage?.attachments ?? []), + ]), + ); + assert.lengthOf((yield* briefs)[0] ?? [], 1, "the first brief carries the claimed copy"); + const stored = yield* upload.stored; + + const immediate = yield* call(args); + assert.deepStrictEqual(immediate.result, original.result); + assert.equal(yield* upload.stored, stored, "a replay makes no second copy"); + + yield* fs.remove(upload.path); + const swept = yield* call(args); + assert.isFalse(swept.isFailure, message(swept)); + assert.deepStrictEqual(swept.result, original.result); + assert.equal(yield* upload.stored, stored - 1, "only the swept upload is gone"); + + const changed = yield* call({ ...args, brief: "Different work" }); + assert.isTrue(changed.isFailure); + assert.include(message(changed), "different request"); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("claims again on a retry after the brief failed, since only its receipt proves it", () => + Effect.gen(function* () { + const { layer, call, commands, failBrief } = yield* spawnHarness({ + checkout: { isRepo: true, refName: "j5/main" }, + }); + yield* Effect.gen(function* () { + const config = yield* ServerConfig; + const fs = yield* FileSystem.FileSystem; + const upload = yield* writePendingUpload; + const args = { + ...spawnArgs, + workspace: { type: "shared" as const }, + attachments: [upload.attachment], + client_request_id: "partial-attached", + }; + yield* Ref.set(failBrief, true); + const failed = yield* call(args); + assert.isTrue(failed.isFailure); + assert.include(message(failed), "brief did not start"); + yield* Ref.set(failBrief, false); + + const retried = yield* call(args); + assert.isFalse(retried.isFailure, message(retried)); + const brief = (yield* Ref.get(commands)).find( + (command) => command.type === "message.dispatch", + ); + const claimed = brief?.type === "message.dispatch" ? brief.attachments[0] : undefined; + assert.notEqual(claimed?.id, upload.attachment.id, "the brief carries a claimed copy"); + assert.deepEqual( + yield* fs.readFile( + resolveAttachmentPath({ attachmentsDir: config.attachmentsDir, attachment: claimed! })!, + ), + new Uint8Array([1, 2, 3]), + ); + }).pipe(Effect.provide(layer)); + }), +); + it.effect( "refuses invalid attachments before binding, so the same key takes a corrected list", () => @@ -1081,8 +1186,11 @@ it.effect("tells a caller to retry the same key when the replay store cannot be new SqlError({ reason: new UnknownError({ cause: new Error("disk I/O error") }) }), ); const replay = Layer.succeed( - RequestReplayService, - RequestReplayService.of({ check: () => unreadable, bind: () => unreadable }), + RequestReplayService.RequestReplayService, + RequestReplayService.RequestReplayService.of({ + check: () => unreadable, + bind: () => unreadable, + }), ); const { layer, call, commands } = yield* spawnHarness({ checkout: { isRepo: true, refName: "j5/main" }, @@ -1176,8 +1284,8 @@ it.effect("records no replay binding for a spawn without client_request_id", () Effect.gen(function* () { const unused = Effect.die(new Error("a keyless spawn has no retry key to bind")); const replay = Layer.succeed( - RequestReplayService, - RequestReplayService.of({ check: () => unused, bind: () => unused }), + RequestReplayService.RequestReplayService, + RequestReplayService.RequestReplayService.of({ check: () => unused, bind: () => unused }), ); const { layer, call } = yield* spawnHarness({ checkout: { isRepo: true, refName: "j5/main" }, @@ -1192,10 +1300,12 @@ it.effect("records no replay binding for a spawn without client_request_id", () it.effect("binds a client_request_id to its first workspace type, across a restart", () => Effect.gen(function* () { - const replayContext = yield* Layer.build(requestReplayLayer.pipe(Layer.provide(layerMemory))); + const replayContext = yield* Layer.build( + RequestReplayService.layer.pipe(Layer.provide(layerMemory)), + ); const replay = Layer.succeed( - RequestReplayService, - Context.get(replayContext, RequestReplayService), + RequestReplayService.RequestReplayService, + Context.get(replayContext, RequestReplayService.RequestReplayService), ); const first = yield* spawnHarness({ checkout: { isRepo: true, refName: "j5/main" }, replay }); yield* Effect.gen(function* () { diff --git a/apps/server/src/j5/a2a/spawnWorkspace.ts b/apps/server/src/j5/a2a/spawnWorkspace.ts index 0fd1f8852e5b2..d85c5ed301056 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.ts @@ -1,13 +1,13 @@ import type { J5SpawnWorkspace } from "./mcp/tools.ts"; -import type { - ChatAttachment, +import { + type ChatAttachment, CommandId, - MessageId, - ModelSelection, - ProjectId, - ProviderInteractionMode, - RuntimeMode, - ThreadId, + type MessageId, + type ModelSelection, + type ProjectId, + type ProviderInteractionMode, + type RuntimeMode, + type ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Data from "effect/Data"; @@ -21,6 +21,7 @@ import type { CrewWorkspaceOptions } from "@t3tools/contracts/j5"; import { GitWorkflowService } from "../../git/GitWorkflowService.ts"; import { CommandReceiptStoreV2, + type CommandReceiptStoreV2Error, layerFromApplicationReceipts as commandReceiptStoreLayer, } from "../../orchestration-v2/CommandReceiptStore.ts"; import { @@ -242,6 +243,19 @@ export const spawnCreateCommandId = ( const WORKSPACE_TYPES = ["shared", "worktree", "existing_worktree"] as const; +const spawnLaunchCommandId = (stableInput: SpawnStableInput) => + lifecycleCommandId({ ...stableInput, operation: "spawn-launch" }); + +/** The brief's message command: dispatched directly, or by ThreadLaunch as its initial message. */ +const spawnBriefCommandId = ( + stableInput: SpawnStableInput, + workspace: ResolvedSpawnWorkspace["type"], +): CommandId => + workspace === "worktree" + ? // ThreadLaunchService derives its initial message's command id this way. + CommandId.make(`${spawnLaunchCommandId(stableInput)}:initial-message`) + : lifecycleCommandId({ ...stableInput, operation: "spawn-brief" }); + /** * The new thread's binding at creation: the caller's checkout, the existing worktree and its * branch, or none until ThreadLaunch binds a new worktree. @@ -328,6 +342,14 @@ export interface SpawnWorkspaceServiceShape { void, OrchestratorV2Error | ThreadLaunchError | ThreadManagementProviderInstanceDisabledError >; + /** + * Whether the brief's message has an accepted receipt, so its files already belong to the + * thread. A thread alone proves nothing: a partial failure can leave one without its brief. + */ + readonly briefAccepted: (input: { + readonly stableInput: SpawnStableInput; + readonly workspace: ResolvedSpawnWorkspace["type"]; + }) => Effect.Effect; } export class SpawnWorkspaceService extends Context.Service< @@ -497,7 +519,7 @@ const make = Effect.gen(function* () { type: "message.dispatch", createdBy: "agent", creationSource: "mcp", - commandId: lifecycleCommandId({ ...input.stableInput, operation: "spawn-brief" }), + commandId: spawnBriefCommandId(input.stableInput, input.workspace.type), threadId: input.threadId, messageId: input.messageId, text: input.text, @@ -508,7 +530,7 @@ const make = Effect.gen(function* () { .pipe(Effect.asVoid) : launcher .launch({ - commandId: lifecycleCommandId({ ...input.stableInput, operation: "spawn-launch" }), + commandId: spawnLaunchCommandId(input.stableInput), threadId: input.threadId, reuseExistingThread: true, projectId: input.projectId, @@ -532,11 +554,17 @@ const make = Effect.gen(function* () { }) .pipe(Effect.asVoid); + const briefAccepted: SpawnWorkspaceServiceShape["briefAccepted"] = (input) => + receipts + .getByCommandId(spawnBriefCommandId(input.stableInput, input.workspace)) + .pipe(Effect.map((receipt) => Option.isSome(receipt) && receipt.value.status === "accepted")); + return SpawnWorkspaceService.of({ inspect, workspaceOptions, withSpawnStart, startBrief, + briefAccepted, }); }); diff --git a/apps/server/src/j5/a2a/test-support/spawnWorkspaceFakes.ts b/apps/server/src/j5/a2a/test-support/spawnWorkspaceFakes.ts index 3c16a039ee416..a11e2605c09db 100644 --- a/apps/server/src/j5/a2a/test-support/spawnWorkspaceFakes.ts +++ b/apps/server/src/j5/a2a/test-support/spawnWorkspaceFakes.ts @@ -14,7 +14,7 @@ import { import { ProjectService } from "../../../project/ProjectService.ts"; import { layerFromReceiptStore } from "../spawnWorkspace.ts"; import { layerMemory } from "../../../persistence/Sqlite.ts"; -import { RequestReplayService, layer as requestReplayLayer } from "../RequestReplayService.ts"; +import * as RequestReplayService from "../RequestReplayService.ts"; export interface FakeCheckout { readonly isRepo: boolean; @@ -57,7 +57,7 @@ const fakeRefs = (checkout: FakeCheckout, workspaceRoot: string) => { */ export const fakeSpawnWorkspaceLayer = (options: { readonly checkout: FakeCheckout; - readonly replay?: Layer.Layer; + readonly replay?: Layer.Layer; /** * When given, git reads this instead, as an agent's shell leaves it. The direct reads see it as * it is now, and a checkout's status does once invalidated; `listRefs` keeps serving the @@ -155,6 +155,6 @@ export const fakeSpawnWorkspaceLayer = (options: { }), ), ), - Layer.merge(options.replay ?? requestReplayLayer.pipe(Layer.provide(layerMemory))), + Layer.merge(options.replay ?? RequestReplayService.layer.pipe(Layer.provide(layerMemory))), ); }; diff --git a/apps/server/src/mcp/toolkits/worktree/registration.test.ts b/apps/server/src/mcp/toolkits/worktree/registration.test.ts index 67b4c24f0f59d..6d6740468bb32 100644 --- a/apps/server/src/mcp/toolkits/worktree/registration.test.ts +++ b/apps/server/src/mcp/toolkits/worktree/registration.test.ts @@ -1,5 +1,5 @@ import * as SpawnAgentService from "../../../j5/a2a/SpawnAgentService.ts"; -import { RequestReplayService } from "../../../j5/a2a/RequestReplayService.ts"; +import * as RequestReplayService from "../../../j5/a2a/RequestReplayService.ts"; import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts"; import * as ProjectionStore from "../../../orchestration-v2/ProjectionStore.ts"; import * as DeviceService from "../../../device/DeviceService.ts"; @@ -101,7 +101,7 @@ const layerStubServices = Layer.mergeAll( Layer.mock(PlaybookCrewRelay)({}), Layer.mock(PlaybookStore)({}), Layer.mock(SpawnCompositionService)({}), - Layer.mock(RequestReplayService)({}), + Layer.mock(RequestReplayService.RequestReplayService)({}), SpawnAgentService.layer, Layer.mock(SpawnWorkspaceService)({}), Layer.mock(ThreadRegistration)({}), diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index a96d4614f5aaa..bb96265bca424 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -87,8 +87,8 @@ runtime_mode and interaction_mode. Attach files to the brief with attachments. C every time (see the workspace field). A new worktree is prepared after this returns, and the agent begins once it is bound, possibly while the project's setup script is still running; if preparing it fails, the agent's thread shows why, and it is not retried. Reuse client_request_id to retry the -same spawn safely; a retry replays the first spawn, so a different base_ref or worktree_path needs a -fresh client_request_id." +same spawn safely; reusing it with any change to the request is refused, so use a fresh one for new +work." | Input | Type | Required | Meaning | | ------------------- | ------------------------------------- | -------- | ------------------------------------------------- | @@ -485,3 +485,4 @@ run; `j5_stop_crew` doesn't, and unarchiving doesn't restart it. - 2026-10-12 — review of outside agents: `delegate_task` and the playbook reads name the legal move too; an outside agent's listing reports only what it can do; a project with no thread yet lists its people and no agents; the level is checked when a message is sent (PR #560). - 2026-10-12 — Stop: the next message delivered to a stopped agent resumes its queue and runs after the held messages, where it used to run ahead of them; the `j5_stop_agent` and `j5_stop_crew` descriptions say so (Jackson, [#580](https://github.com/Jacksondr5/j5code/issues/580)). - 2026-10-17 — the advance onto upstream's nightly `v0.1.1-nightly.20261017.3238`: `t3_workflow_stop`, `write_pull_request_guides` and `read_pull_request_guide` join the kept upstream tools as-is, and `delegate_task`'s description takes upstream's sentences on a child's own worktree, a wait that ends at the child's question, and runtime modes (Jackson's decisions of that day; [register of divergences](../upstream.md), D1 and D2). +- 2026-10-23 — spawn and Crew retries bind the whole request, refuse changed requests and unverifiable pre-upgrade requests, and replay accepted work; the `j5_spawn_agent` contract description matches the shipped string ([PR #660](https://github.com/Jacksondr5/j5code/pull/660)). From b50d81c2e9921555c1ac16fe49bb760a940c0886 Mon Sep 17 00:00:00 2001 From: Bastian Huppertz Date: Mon, 26 Oct 2026 17:02:58 +0100 Subject: [PATCH 9/9] fix(j5): refuse cross-workspace legacy retries before binding --- apps/server/src/j5/a2a/SpawnAgentService.ts | 22 ++++--- apps/server/src/j5/a2a/spawnWorkspace.test.ts | 59 +++++++++++++++++++ apps/server/src/j5/a2a/spawnWorkspace.ts | 37 +++++++++++- docs/j5/product/a2a/agent-tools.md | 4 +- 4 files changed, 109 insertions(+), 13 deletions(-) diff --git a/apps/server/src/j5/a2a/SpawnAgentService.ts b/apps/server/src/j5/a2a/SpawnAgentService.ts index 5d66e7a503de1..4eb54367a725c 100644 --- a/apps/server/src/j5/a2a/SpawnAgentService.ts +++ b/apps/server/src/j5/a2a/SpawnAgentService.ts @@ -523,14 +523,6 @@ const spawn = Effect.fn("j5.a2a.spawnAgent")(function* ( stateError(`Peer Agent was not created: ${error.detail}`, error.nextStep), ), ); - if (replayable) - yield* replayService - .bind({ - id: threadId, - target: `Peer Agent ${participantIdForThread(threadId)} on thread ${threadId}`, - request, - }) - .pipe(Effect.mapError(replayFailure)); return yield* spawnWorkspace .withSpawnStart( { stableInput, threadId }, @@ -544,7 +536,19 @@ const spawn = Effect.fn("j5.a2a.spawnAgent")(function* ( const current = yield* threadManagement .getThreadShell(threadId) .pipe(Effect.mapError(spawnReadFailure)); - if (current !== null) yield* replayExceedsCaller((yield* loadCaller()).limits, current); + if (current !== null) { + yield* spawnWorkspace.assertExistingWorkspace({ stableInput, workspace: workspace.type }); + yield* replayExceedsCaller((yield* loadCaller()).limits, current); + } + if (replayable) + yield* replayService + .bind({ + id: threadId, + target: `Peer Agent ${participantIdForThread(threadId)} on thread ${threadId}`, + request, + }) + .pipe(Effect.mapError(replayFailure)); + const sharedCheckout = current !== null ? current diff --git a/apps/server/src/j5/a2a/spawnWorkspace.test.ts b/apps/server/src/j5/a2a/spawnWorkspace.test.ts index 27fed48846440..857225fdb3b8b 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.test.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.test.ts @@ -31,6 +31,7 @@ import * as Result from "effect/Result"; import * as Sink from "effect/Sink"; import { SqlError, UnknownError } from "effect/sql/SqlError"; import * as Stream from "effect/Stream"; +import * as SqlClient from "effect/sql/SqlClient"; import { McpInvocationContext, type McpInvocationScope } from "../../mcp/McpInvocationContext.ts"; import { OrchestratorMcpService } from "../../mcp/OrchestratorMcpService.ts"; @@ -1841,6 +1842,64 @@ it.effect("an outside agent's narrowed approved level still caps an identical re }), ); +it.effect.each(["shared", "worktree"] as const)( + "refuses a cross-type pre-upgrade %s retry without binding or changing the thread", + (type) => + Effect.gen(function* () { + const replayContext = yield* Layer.build( + RequestReplayService.layer.pipe(Layer.provideMerge(layerMemory)), + ); + const replay = Layer.succeed( + RequestReplayService.RequestReplayService, + Context.get(replayContext, RequestReplayService.RequestReplayService), + ); + const sql = Context.get(replayContext, SqlClient.SqlClient); + const harness = yield* spawnHarness({ + checkout: { isRepo: true, refName: "j5/main" }, + replay, + }); + yield* Effect.gen(function* () { + const args = { + ...spawnArgs, + title: "Original title", + workspace: + type === "shared" + ? { type: "shared" as const } + : { type: "worktree" as const, base_ref: "j5/main" }, + client_request_id: `pre-upgrade-cross-${type}`, + }; + const original = yield* harness.call(args); + assert.isFalse(original.isFailure, message(original)); + // This thread predates request binding, so only its create receipt survives the upgrade. + yield* sql`DELETE FROM j5_a2a_request_replay`; + const beforeCommands = yield* Ref.get(harness.commands); + const beforeLaunches = yield* Ref.get(harness.launches); + const threads = yield* ThreadManagementService; + const id = (original.result as { readonly thread_id: ThreadId }).thread_id; + const beforeThread = yield* threads.getThreadProjection(id); + const refused = yield* harness.call({ + ...args, + title: "Must not overwrite", + workspace: + type === "shared" + ? { type: "worktree" as const, base_ref: "j5/main" } + : { type: "shared" as const }, + }); + assert.isTrue(refused.isFailure); + assert.include(message(refused), "already bound to workspace"); + assert.deepStrictEqual(yield* Ref.get(harness.commands), beforeCommands); + assert.deepStrictEqual(yield* Ref.get(harness.launches), beforeLaunches); + assert.deepStrictEqual(yield* threads.getThreadProjection(id), beforeThread); + assert.lengthOf(yield* sql`SELECT id FROM j5_a2a_request_replay`, 0); + + const corrected = yield* harness.call(args); + assert.isFalse(corrected.isFailure, message(corrected)); + assert.deepStrictEqual(corrected.result, original.result); + assert.lengthOf(yield* sql`SELECT id FROM j5_a2a_request_replay`, 1); + }).pipe(Effect.provide(harness.layer)); + }), +); + it.effect("binds the first retry of a pre-upgrade spawn and holds its key to it", () => Effect.gen(function* () { // The agent exists from before replay binding, so its key has no stored request. diff --git a/apps/server/src/j5/a2a/spawnWorkspace.ts b/apps/server/src/j5/a2a/spawnWorkspace.ts index 5469c9afc8ce6..636f5167dc6c2 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.ts @@ -139,6 +139,7 @@ const NO_WORKSPACE_OPTIONS: CrewWorkspaceOptions = { export class SpawnWorkspaceError extends Data.TaggedError("SpawnWorkspaceError")<{ readonly detail: string; readonly nextStep: string; + readonly cause?: unknown; }> { override get message(): string { return this.detail; @@ -309,6 +310,11 @@ export interface SpawnWorkspaceServiceShape { readonly projectId: ProjectId; readonly worktreePath: string | null; }) => Effect.Effect; + /** Check the accepted create receipt before first binding a pre-upgrade thread's retry. */ + readonly assertExistingWorkspace: (input: { + readonly stableInput: SpawnStableInput; + readonly workspace: ResolvedSpawnWorkspace["type"]; + }) => Effect.Effect; /** * Runs one spawn's start (create, facts, brief), refusing it while another start for the same * thread is in flight. @@ -316,8 +322,9 @@ export interface SpawnWorkspaceServiceShape { * Invariant: every door that dispatches `thread.create` for a spawn thread id goes through this. * The orchestrator has no existing-thread guard and the projection upserts, so a second create * under another workspace type's command id would overwrite the first thread. A key keeps its - * workspace type because its request is bound before the start (`RequestReplayService`), and a - * Crew seat's because its approval is recorded before any seat starts. + * workspace type through its request binding; a pre-upgrade thread's create receipt is checked + * before its first binding inside the guard. A Crew seat's approval records its workspace + * before any seat starts. */ readonly withSpawnStart: ( input: { @@ -469,6 +476,31 @@ const make = Effect.gen(function* () { }; }).pipe(Effect.catch(() => Effect.succeed(NO_WORKSPACE_OPTIONS))); + const assertExistingWorkspace: SpawnWorkspaceServiceShape["assertExistingWorkspace"] = (input) => + Effect.gen(function* () { + for (const other of ["shared", "worktree", "existing_worktree"] as const) { + if (other === input.workspace) continue; + const receipt = yield* receipts + .getByCommandId(spawnCreateCommandId(input.stableInput, other)) + .pipe( + Effect.mapError( + (cause) => + new SpawnWorkspaceError({ + detail: "The spawn's earlier workspace choice could not be read.", + nextStep: "Retry with the same client_request_id.", + cause, + }), + ), + ); + if (Option.isSome(receipt) && receipt.value.status === "accepted") { + return yield* new SpawnWorkspaceError({ + detail: `client_request_id ${input.stableInput.requestKey} is already bound to workspace {"type":"${other}"}.`, + nextStep: "Retry with that workspace, or use a fresh client_request_id.", + }); + } + } + }); + const withSpawnStart: SpawnWorkspaceServiceShape["withSpawnStart"] = ( input: Parameters[0], effect: Effect.Effect, @@ -542,6 +574,7 @@ const make = Effect.gen(function* () { inspect, workspaceOptions, withSpawnStart, + assertExistingWorkspace, startBrief, briefAccepted, }); diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index 22356f80707f4..d9a09f1a90ca8 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -117,7 +117,7 @@ work." **Rules.** The new agent is an ordinary root-lineage thread created through upstream's creation seam, never through delegation. It is created in the caller's project unless the caller names another with `project_id` or sets `scratch`, and it joins that project's ledger. An [outside agent](index.md#participants) has no project, so it passes one of the two on every spawn. These are what upstream's own launch tool offers and J5's lacked (Jackson, 2026-10-11). In another project the caller is still recorded as the spawner, but the placement tree is one project's, so the agent is a root there and stays at the top level of the sidebar. An outside agent is in no project's tree, so every agent it starts is a root, with the outside agent's `outside:` id recorded as its spawner. Without a persona the agent runs in the caller's permission and interaction modes, or in ones the caller chose, which may be no broader than the caller's own. For an outside agent the caller's modes are the level its sign-in was approved at, and a read-only sign-in spawns nothing. A persona's policy sets its permissions. For a thread caller it has no ceiling (2026-09-16). For an outside agent it must be within the approved level, because that level is a promise the approval page makes about an agent the person does not watch. Either caller may still choose a narrower interaction mode for a persona. A retry finishes the agent its first attempt created, in the modes it was created with, so it is refused when those are now broader than the caller's own; a caller's modes can be narrowed between the two. An outside agent's retry keys belong to its sign-in, whose level never changes. `attachments` are pending uploads, claimed into the new thread once it exists and carried by the brief. Placement and provenance are recorded atomically with creation; then the brief starts as the first turn. The new agent's first turn also states its own participant id and project as platform-provided facts, beside the brief and never inside it. When an outside agent started it, those facts name the outside agent by its label and say that `j5_send_message` cannot reply to it. Provider, model and reasoning are required and explicit even when a Role is given: a Role's allowlist constrains the choice and an out-of-list pick is an error naming the Role, never a silent default. The brief carries the task and the reply expectation; the spawner does not follow a spawn with a reply-expected `j5_send_message` — that form is for later work owed by an existing participant. Selection guidance and brief-writing conventions live in the [Spawning Guide](../features/spawning-guide.md). -**Workspace.** The spawner chooses where a Peer Agent works every time; there is no default, because the spawner knows whether it is starting a reviewer that must see uncommitted work, a builder that must not collide, or a scout that can't collide at all (Jackson, 2026-10-03). `{type: "shared"}` is the caller's own checkout and branch, and asks nothing of git; it is refused for an agent that joins another project, and for an outside agent, which has no checkout. `{type: "root"}` is the project's main checkout, upstream's name for it, and the only choice with `scratch`. As upstream's launch does, a main-checkout thread in the "No project" project gets a fresh folder of its own, whether the caller set `scratch` or named that project by its id. `{type: "worktree"}` is a new worktree from `base_ref`, which is required and must resolve to a commit (with `start_from_origin`, its fetched origin copy counts); a `branch` that already exists is refused. `{type: "existing_worktree"}` is one of the project's git worktrees other than its main checkout, named by path; the agent works on the branch git has checked out there, and any other path is refused with the valid ones listed. A choice that needs git is refused when the repository can't be read, before anything is created. A new worktree's thread is created unbound, with its registration and placement committed, so `j5_spawn_agent` returns as soon as the agent is registered and its brief accepted, not once the worktree is ready. Upstream's ThreadLaunch then creates the worktree, names a temporary `j5code/` branch and renames it from the brief in the background, and holds the brief as a preparing run until the worktree is bound and the project's setup script has started. The setup script is awaited first only when it is set to finish before the agent starts (`async: false`); otherwise the agent may begin while it is still running. If preparation fails, the agent's thread shows the failed preparation, as any upstream launch does; it is not retried or retired, and the spawner is not told. The agent is then unbound, which upstream reads as the project's checkout, so a later message to it runs there, where every Peer Agent worked before workspaces existed. J5 doesn't guard this upstream behaviour: in Jackson's install, 3 of 61 preparations failed, all on the first day, and none was messaged again (Jackson, 2026-10-06). A shared checkout or an existing worktree binds at creation, so its brief starts at once. A `client_request_id` is bound to the whole request it was first accepted with, before anything is created, and the binding survives a restart. A retry with any change, including another workspace, `base_ref` or `worktree_path`, is refused, naming the agent the first attempt created; new work needs a fresh `client_request_id`. A request refused before it is accepted, such as one with duplicate attachment ids or an unusable workspace, binds nothing, so it can be corrected under the same key. A retry of a spawn from before request binding binds the request it first retries with and carries on; later changes under that key are refused. A second start for the same thread while one is in flight is refused with a retry instruction, so two concurrent retries cannot both create it. An existing worktree is looked up in upstream's ref listing, which refreshes every few seconds, so one created moments ago may be refused once; retry in a moment. Closing or archiving a Peer Agent never removes its worktree. +**Workspace.** The spawner chooses where a Peer Agent works every time; there is no default, because the spawner knows whether it is starting a reviewer that must see uncommitted work, a builder that must not collide, or a scout that can't collide at all (Jackson, 2026-10-03). `{type: "shared"}` is the caller's own checkout and branch, and asks nothing of git; it is refused for an agent that joins another project, and for an outside agent, which has no checkout. `{type: "root"}` is the project's main checkout, upstream's name for it, and the only choice with `scratch`. As upstream's launch does, a main-checkout thread in the "No project" project gets a fresh folder of its own, whether the caller set `scratch` or named that project by its id. `{type: "worktree"}` is a new worktree from `base_ref`, which is required and must resolve to a commit (with `start_from_origin`, its fetched origin copy counts); a `branch` that already exists is refused. `{type: "existing_worktree"}` is one of the project's git worktrees other than its main checkout, named by path; the agent works on the branch git has checked out there, and any other path is refused with the valid ones listed. A choice that needs git is refused when the repository can't be read, before anything is created. A new worktree's thread is created unbound, with its registration and placement committed, so `j5_spawn_agent` returns as soon as the agent is registered and its brief accepted, not once the worktree is ready. Upstream's ThreadLaunch then creates the worktree, names a temporary `j5code/` branch and renames it from the brief in the background, and holds the brief as a preparing run until the worktree is bound and the project's setup script has started. The setup script is awaited first only when it is set to finish before the agent starts (`async: false`); otherwise the agent may begin while it is still running. If preparation fails, the agent's thread shows the failed preparation, as any upstream launch does; it is not retried or retired, and the spawner is not told. The agent is then unbound, which upstream reads as the project's checkout, so a later message to it runs there, where every Peer Agent worked before workspaces existed. J5 doesn't guard this upstream behaviour: in Jackson's install, 3 of 61 preparations failed, all on the first day, and none was messaged again (Jackson, 2026-10-06). A shared checkout or an existing worktree binds at creation, so its brief starts at once. A `client_request_id` is bound to the whole request it was first accepted with, before anything is created, and the binding survives a restart. A retry with any change, including another workspace, `base_ref` or `worktree_path`, is refused, naming the agent the first attempt created; new work needs a fresh `client_request_id`. A request refused before it is accepted, such as one with duplicate attachment ids or an unusable workspace, binds nothing, so it can be corrected under the same key. A retry of a spawn from before request binding binds its first retry when the workspace type matches its accepted create receipt, and is refused otherwise; later request changes under that key are refused. A second start for the same thread while one is in flight is refused with a retry instruction, so two concurrent retries cannot both create it. An existing worktree is looked up in upstream's ref listing, which refreshes every few seconds, so one created moments ago may be refused once; retry in a moment. Closing or archiving a Peer Agent never removes its worktree. **Result:** the new agent's `participant_id` and `thread_id`, its `project_id` and `project_title`, and its placement with the caller recorded as spawner: under the caller in the caller's own project, and with no parent in another or when the caller is an outside agent. @@ -490,4 +490,4 @@ run; `j5_stop_crew` doesn't, and unarchiving doesn't restart it. - 2026-10-24 — `j5_spawn_agent` requires a short `title`, as upstream's `t3_thread_launch` does, instead of naming the agent after the start of its brief ([#296](https://github.com/Jacksondr5/j5code/issues/296)). - 2026-10-24 — `j5_send_message`'s `deliveryNotice` also tells the sender when its message waits on the receiver's held queue, failed worktree setup or usage limit, and that it should not be sent again (Jackson, [#272](https://github.com/Jacksondr5/j5code/issues/272)). - 2026-10-24 — upstream's queue tools join the kept upstream tools; `t3_queue_edit` edits only a message the caller sent, inside its envelope (Jackson, [#136](https://github.com/Jacksondr5/j5code/issues/136)). -- 2026-10-24 — the first retry of an unbound pre-upgrade spawn binds that request and continues, accepting the old replay behavior once rather than refusing upgrade-time retries (Jackson, 2026-10-24; [PR #660](https://github.com/Jacksondr5/j5code/pull/660)). +- 2026-10-24 — a pre-upgrade spawn retry binds its request when the workspace type matches its accepted create receipt and is refused otherwise (Jackson, 2026-10-24; [PR #660](https://github.com/Jacksondr5/j5code/pull/660)).