diff --git a/FORK.md b/FORK.md index 9a461f9af419b..524e16abd0b27 100644 --- a/FORK.md +++ b/FORK.md @@ -332,7 +332,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, 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/AgentCrewProposalService.test.ts b/apps/server/src/j5/a2a/AgentCrewProposalService.test.ts index 14995ab22f105..f314d81cd833f 100644 --- a/apps/server/src/j5/a2a/AgentCrewProposalService.test.ts +++ b/apps/server/src/j5/a2a/AgentCrewProposalService.test.ts @@ -299,3 +299,38 @@ it.effect( ), ), ); + +it.effect("preserves library playbook paths in pre-upgrade and current proposals", () => + 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', '/library/release.yaml' + )`; + yield* runJ5A2AMigrations(); + const proposals = yield* AgentCrewProposalService; + const legacy = yield* proposals.read("legacy"); + assert.deepStrictEqual(legacy?.playbook, { + name: "release", + definitionPath: "/library/release.yaml", + }); + const current = yield* proposals.create({ + ...addition("current", "unused", []), + kind: "roster", + crewInstanceId: null, + playbook: { + name: "release", + definitionPath: "/library/release.yaml", + }, + }); + const reloaded = yield* proposals.read(current.id); + assert.deepStrictEqual(reloaded?.playbook, current.playbook); + 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..b334e32208ade 100644 --- a/apps/server/src/j5/a2a/AgentCrewProposalService.ts +++ b/apps/server/src/j5/a2a/AgentCrewProposalService.ts @@ -48,7 +48,7 @@ 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. */ export interface CrewPlaybookRef { readonly name: string; readonly definitionPath: string; @@ -200,7 +200,10 @@ 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, + }, }); export const layer: Layer.Layer = diff --git a/apps/server/src/j5/a2a/CrewLaunchService.ts b/apps/server/src/j5/a2a/CrewLaunchService.ts index bb4311eee4e03..2196299b0d0cd 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.ts @@ -589,14 +589,13 @@ export const layer = Layer.effect( const seatName = member.seat.name; // Seats go through the same start guard as j5_spawn_agent (see `withSpawnStart`), so every // door that creates a spawn thread keeps its invariant. A Crew's launches are already - // serialized and its approval binds each seat's workspace type, so neither refusal is - // expected here; the brief takes the guard again once every seat exists. + // serialized, so its in-flight refusal is not expected here; the brief takes the guard + // again once every seat exists. const started = yield* Effect.result( spawnWorkspace.withSpawnStart( { stableInput: member.stableInput, threadId: member.threadId, - workspace: member.workspace, }, startSeat(captain, member), ), @@ -669,7 +668,6 @@ export const layer = Layer.effect( { stableInput: member.stableInput, threadId: member.threadId, - workspace: member.workspace, }, spawnWorkspace.startBrief({ workspace: member.workspace, diff --git a/apps/server/src/j5/a2a/CrewProposalService.test.ts b/apps/server/src/j5/a2a/CrewProposalService.test.ts index 998a352a80522..1ca84413fc1b8 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.test.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.test.ts @@ -14,11 +14,13 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Ref from "effect/Ref"; import * as Result from "effect/Result"; +import * as SqlClient from "effect/sql/SqlClient"; import * as Schema from "effect/Schema"; import { SqlError, UnknownError } from "effect/sql/SqlError"; import { stringify } from "yaml"; @@ -78,7 +80,8 @@ import { runJ5A2AMigrations } from "./Migrations.ts"; import { SpawnCompositionService } from "./SpawnCompositionService.ts"; import type { ResolvedSpawnWorkspace } from "./spawnWorkspace.ts"; import { fakeSpawnWorkspaceLayer, noRepository } from "./test-support/spawnWorkspaceFakes.ts"; -import { crewSeatRequestKey, spawnThreadId } from "./spawnIds.ts"; +import { crewSeatRequestKey, lifecycleId, spawnThreadId } from "./spawnIds.ts"; +import { CREW_PROPOSAL_SESSION } from "./crewSeatIds.ts"; import { ParticipantId, LedgerProjectId } from "./contracts.ts"; const projectId = LedgerProjectId.make("ledger:crew-proposal"); @@ -294,8 +297,16 @@ const assertCrewFull = (error: { readonly _tag: string; readonly message: string assert.include(error.message, "propose a new crew"); }; -const fixture = Effect.gen(function* () { - const database = NodeSqliteClient.layer({ filename: ":memory:" }); +const fixtureWithDatabase = Effect.fn("test.crewProposal.fixture")(function* ( + filename: string, + options: { + readonly beforeCreate?: Effect.Effect; + 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), ); @@ -333,6 +344,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))), @@ -342,7 +363,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), ), @@ -424,6 +447,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; @@ -1803,7 +1828,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]), [ @@ -2343,7 +2371,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]), [ @@ -2415,3 +2446,702 @@ 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 checkout changes, 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( + (yield* store.definitionPathFor(`${workspaceRoot}/other`, "release")).definitionPath, + libraryFile, + ); + const moved = yield* gate.propose({ + requestKey: "release", + captain: { + ...captain, + thread: { ...captain.thread, worktreePath: `${workspaceRoot}/other` }, + }, + displayName: "Release Crew", + brief: "Ship the change.", + playbook: { name: "release.yaml", workspaceRoot: `${workspaceRoot}/other` }, + seats: [custom("planner", ["plan"]), custom("builder", ["build"])], + }); + assert.deepStrictEqual(moved.proposal, original.proposal); + + yield* fs.writeFileString(localFile, stringify({ ...release(), title: "Local override" })); + const preview = yield* gate.preview({ proposalId: original.proposal.id }); + assert.equal(preview.playbook?.title, "Release", "preview reads the stored library path"); + 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, steps 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, seats: [custom("planner", ["review"]), custom("builder", ["build"])] }, + { ...input, playbook: undefined }, + { ...input, captain: { ...captain, participantId: ParticipantId.make("other-captain") } }, + { ...input, captain: { ...captain, thread: thread(ThreadId.make("other-thread")) } }, + ]) { + 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 a pre-field library proposal by name after the Captain changes checkout", () => + Effect.gen(function* () { + const { layer, workspaceRoot } = yield* playbookFixture; + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const sql = yield* SqlClient.SqlClient; + const id = lifecycleId({ + kind: "crew", + operation: "proposal", + providerSessionId: CREW_PROPOSAL_SESSION, + requestKey: "legacy-library", + }); + const seats = [custom("planner", ["plan"]), custom("builder", ["build"])]; + 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 ( + ${id}, ${projectId}, ${captainId}, ${captainThread}, 'roster', 'open', + 'Ship the change.', 'Release Crew', ${JSON.stringify(seats)}, + ${DateTime.formatIso(createdAt)}, 'release', '/library/release.yaml' + )`; + const stored = yield* (yield* AgentCrewProposalService).read(id); + assert.deepStrictEqual(stored?.playbook, { + name: "release", + definitionPath: "/library/release.yaml", + }); + const movedRoot = `${workspaceRoot}/other`; + const replay = yield* gate.propose({ + requestKey: "legacy-library", + captain: { ...captain, thread: { ...captain.thread, worktreePath: movedRoot } }, + displayName: "Release Crew", + brief: "Ship the change.", + playbook: { name: "release.yaml", workspaceRoot: movedRoot }, + seats, + }); + assert.deepStrictEqual(replay.proposal, stored); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listForCaptain(captainId), 1); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect.each(["roster", "addition"] as const)( + "treats omitted and empty seat steps as the same %s request after SQLite round trip", + (kind) => + Effect.gen(function* () { + const { layer } = yield* fixture; + yield* Effect.gen(function* () { + const gate = withPreview(yield* CrewProposalService); + const crew = kind === "addition" ? yield* seedCrew(gate, "steps-crew", 1) : null; + for (const initialSteps of [undefined, []] as const) { + const requestKey = `steps-${kind}-${initialSteps === undefined ? "omitted" : "empty"}`; + const request = (steps: ReadonlyArray | undefined) => + kind === "roster" + ? gate.propose({ + requestKey, + captain, + displayName: "Steps Crew", + brief: "Original", + seats: [custom("writer", steps)], + }) + : gate.requestMember({ + requestKey, + captain, + crewInstanceId: crew!.id, + brief: null, + seat: custom(`writer-${initialSteps === undefined ? "omitted" : "empty"}`, steps), + }); + const original = yield* request(initialSteps); + const replay = yield* request(initialSteps === undefined ? [] : undefined); + assert.deepStrictEqual(replay.proposal, original.proposal); + const changed = yield* request(["build"]).pipe(Effect.flip); + assert.equal(changed._tag, "CrewProposalRequestError"); + assert.include(changed.message, original.proposal.id); + assert.include(changed.message, "different request"); + } + }).pipe(Effect.provide(layer)); + }), +); diff --git a/apps/server/src/j5/a2a/CrewProposalService.ts b/apps/server/src/j5/a2a/CrewProposalService.ts index 80f466713a6c4..1ada4789e8ffe 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.ts @@ -23,6 +23,7 @@ import { type CrewPlaybookRef, type CrewProposal, type CrewProposalSeat, + type CreateCrewProposalInput, } from "./AgentCrewProposalService.ts"; import { CREW_SEAT_CAP, @@ -42,6 +43,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 +236,32 @@ const memberSteps = (instance: AgentCrewInstance | null) => playbookStepIds: member.playbookStepIds ?? [], })); +type ProposalRequest = Omit & { + readonly playbook?: Pick | null | undefined; +}; + +// Proposal rows preserve original intent across upgrades; human edits go to approvedSeats. +const proposalRequest = (proposal: ProposalRequest) => ({ + 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?.name ?? null, + seats: proposal.requestedSeats.map(({ personaSwaps: _swaps, workspace, ...seat }) => ({ + ...seat, + steps: seat.steps ?? [], + 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* () { @@ -587,53 +616,80 @@ export const layer = Layer.effect( }); }); + const replayProposal = Effect.fn("j5.a2a.crewProposal.replay")(function* ( + original: CrewProposal, + request: ProposalRequest, + ) { + 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; - 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 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"))); + 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: + input.playbook === undefined + ? null + : { name: input.playbook.name.replace(/\.yaml$/, "") }, + } satisfies ProposalRequest; + // The optional playbook summary describes fresh validation; replay never reads a changed definition. + if (original !== null) return yield* replayProposal(original, request); + const playbookRef = + input.playbook === undefined + ? null + : yield* playbooks + .definitionPathFor(input.playbook.workspaceRoot, input.playbook.name) + .pipe( + Effect.map(({ stem, definitionPath }) => ({ name: stem, definitionPath })), + Effect.mapError(playbookRefusal(input.playbook.name, "propose")), + ); + 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, + playbook: playbookRef, 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 +728,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 +755,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 +766,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 52ee3beaaf910..b954efd8b8099 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -33,6 +33,44 @@ const enableAndAssertForeignKeys = Effect.gen(function* () { assert.deepStrictEqual(rows, [{ foreign_keys: 1 }]); }); +it.effect("upgrades the current main schema with replay storage", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations(); + yield* runJ5A2AMigrations({ toMigrationInclusive: 46 }); + 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.notInclude( + 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 >= 47 ORDER BY migration_id + `; + assert.deepStrictEqual(applied, [{ migration_id: 47, name: "RequestReplay" }]); + }).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; @@ -100,6 +138,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () { migration_id: 44, name: "QueuedMessageEdits" }, { migration_id: 45, name: "McpClientApprovers" }, { migration_id: 46, name: "LocalDeliveryOrder" }, + { migration_id: 47, name: "RequestReplay" }, ]); assert.deepStrictEqual( migrationEntries.map(([id, name]) => [id, name]), @@ -150,6 +189,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () [44, "QueuedMessageEdits"], [45, "McpClientApprovers"], [46, "LocalDeliveryOrder"], + [47, "RequestReplay"], ], ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), @@ -1398,7 +1438,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, 45, 46, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, ], ); 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 5565f7c561179..f54cf6c49cca9 100644 --- a/apps/server/src/j5/a2a/Migrations.ts +++ b/apps/server/src/j5/a2a/Migrations.ts @@ -47,6 +47,7 @@ import Migration0043 from "./migrations/043_TaskSchedulers.ts"; import Migration0044 from "./migrations/044_QueuedMessageEdits.ts"; import Migration0045 from "./migrations/045_McpClientApprovers.ts"; import Migration0046 from "./migrations/046_LocalDeliveryOrder.ts"; +import Migration0047 from "./migrations/047_RequestReplay.ts"; export const J5_A2A_MIGRATIONS_TABLE = "j5_a2a_migrations"; @@ -104,6 +105,7 @@ export const migrationEntries = [ [44, "QueuedMessageEdits", Migration0044], [45, "McpClientApprovers", Migration0045], [46, "LocalDeliveryOrder", Migration0046], + [47, "RequestReplay", Migration0047], ] 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..1118e2b40525a --- /dev/null +++ b/apps/server/src/j5/a2a/RequestReplayService.test.ts @@ -0,0 +1,76 @@ +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/047_RequestReplay.ts"; +import * as RequestReplayService 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 }, + }; + yield* Effect.scoped( + Effect.gen(function* () { + yield* migration; + 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.RequestReplayService; + yield* replay.bind({ + ...first, + 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.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<{ + readonly count: number; + }>`SELECT COUNT(*) AS count FROM j5_a2a_request_replay`; + assert.equal(rows[0]?.count, 1); + yield* replay.check("new-key", {}); + assert.isTrue(Result.isFailure(yield* replay.check(first.id, {}).pipe(Effect.result))); + // A key from before binding existed binds its first retry, then holds it like any other. + const legacy = { ...first, id: "pre-upgrade", target: "agent:pre-upgrade" }; + yield* replay.check(legacy.id, legacy.request); + yield* replay.bind(legacy); + yield* replay.bind(legacy); + const changedLegacy = yield* replay + .bind({ ...legacy, request: { brief: "different" } }) + .pipe(Effect.result); + assert.isTrue(Result.isFailure(changedLegacy)); + if (Result.isFailure(changedLegacy)) + assert.equal(changedLegacy.failure._tag, "RequestReplayConflictError"); + }).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 new file mode 100644 index 0000000000000..bf6bee9667579 --- /dev/null +++ b/apps/server/src/j5/a2a/RequestReplayService.ts @@ -0,0 +1,94 @@ +// @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 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 }, +) { + override get message() { + const { detail, nextStep } = requestReplayConflict(this.target); + return `${detail} ${nextStep}`; + } +} + +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 const requestDigest = (request: unknown) => + NodeCrypto.createHash("sha256") + .update(JSON.stringify(canonical(request))) + .digest("hex"); + +export class RequestReplayService extends Context.Service< + RequestReplayService, + { + readonly check: ( + id: string, + request: unknown, + ) => Effect.Effect; + /** + * Binds before side effects. A key first used before binding existed binds whichever retry + * arrives first (Jackson, 2026-10-24): only a request in flight at the upgrade can hit that. + */ + readonly bind: (input: { + readonly id: string; + readonly target: string; + readonly request: unknown; + }) => Effect.Effect; + } +>()("t3/j5/a2a/RequestReplayService") {} + +export const layer = Layer.effect( + RequestReplayService, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + 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 !== requestDigest(request)) + return yield* new RequestReplayConflictError({ target: original.target }); + }, + ); + const bind: RequestReplayService["Service"]["bind"] = Effect.fn("j5.requestReplay.bind")( + function* (input) { + const digest = requestDigest(input.request); + 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 }); + }, + sql.withTransaction, + ); + return RequestReplayService.of({ bind, check }); + }), +); diff --git a/apps/server/src/j5/a2a/SpawnAgentService.ts b/apps/server/src/j5/a2a/SpawnAgentService.ts new file mode 100644 index 0000000000000..4eb54367a725c --- /dev/null +++ b/apps/server/src/j5/a2a/SpawnAgentService.ts @@ -0,0 +1,729 @@ +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 * as RequestReplayService from "./RequestReplayService.ts"; +import * as SpawnWorkspace 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 * as 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.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, + scratch: input.scratch ?? false, + workspace: workspaceRequest, + }; + const replayService = yield* RequestReplayService.RequestReplayService; + const replayFailure = (error: SqlError | RequestReplayService.RequestReplayConflictError) => { + 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": + 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) + 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. The start + // checks, after reading the thread again, so an agent a concurrent attempt created counts too. + 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.", + ), + ); + }; + + // 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* 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) + : 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; + // 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: SpawnWorkspace.namedBaseRefs([choice]), + existingWorktreePaths: SpawnWorkspace.namedWorktreePaths([choice]), + }); + const workspace = yield* Effect.fromResult( + checkout === null + ? Result.succeed({ type: "shared" } as const) + : SpawnWorkspace.resolveSpawnWorkspace(checkout, choice), + ).pipe( + Effect.mapError((error) => + stateError(`Peer Agent was not created: ${error.detail}`, error.nextStep), + ), + ); + return yield* spawnWorkspace + .withSpawnStart( + { stableInput, threadId }, + 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* 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 + : 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: SpawnWorkspace.spawnCreateCommandId(stableInput, workspace.type), + threadId, + projectId: target, + title: spawnTitle(input.title), + modelSelection: current?.modelSelection ?? modelSelection, + runtimeMode: current?.runtimeMode ?? runtimeMode, + interactionMode: current?.interactionMode ?? interactionMode, + ...(persona === undefined ? {} : { agentPersonaAssignment: persona.assignment }), + ...(current === null + ? SpawnWorkspace.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. 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 || briefAccepted + ? [] + : (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.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/handlers.test.ts b/apps/server/src/j5/a2a/mcp/handlers.test.ts index 6952b58ff054e..0fb95723eb911 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.test.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.test.ts @@ -1611,7 +1611,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 77226f6e625a9..1959d03562e57 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -1,46 +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 { 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 { claimPendingAttachments } from "../../../orchestration-v2/AttachmentClaims.ts"; -import { 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 { @@ -67,41 +60,20 @@ import { A2ASendService } from "../SendService.ts"; import { stopThread } from "../stopThread.ts"; import { sendClaimingAttachments } from "./attachments.ts"; import { - assertPersonaWithinApprovedLevel, outsideAgentCaller, - outsideSpawnHasNoCheckout, - outsideSpawnNeedsProject, sendAsOutsideAgent, spawnAndBrief, actsAsThreadCaller, } from "./outsideAgent.ts"; -import { SpawnCompositionService } from "../SpawnCompositionService.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 { @@ -110,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 @@ -211,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 @@ -227,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, @@ -982,365 +711,12 @@ 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* () { 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 selected = yield* selectSpawnModel(scope, input); - const threadManagement = yield* ThreadManagementService; - const personaId = input.persona; - const persona = - personaId === undefined - ? undefined - : yield* prepareSpawnPersona({ ...input, persona: personaId }, selected); - const 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) { - 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. - 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 = - input.runtime_mode ?? - persona?.runtimeMode ?? - home?.thread.runtimeMode ?? - limits.runtimeMode; - const 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 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)) { - 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.", - ); - } - } - - // 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), - ), - ); - 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 created = - input.workspace.type === "root" && - (yield* threadManagement - .getThreadShell(threadId) - .pipe(Effect.orElseSucceed(() => null))) !== null; - 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.", - ), - ), - ), - ), - }; - yield* threadManagement - .dispatch({ - type: "thread.create", - createdBy: "agent", - creationSource: "mcp", - commandId: spawnCreateCommandId(stableInput, workspace.type), - threadId, - projectId: target, - title: spawnTitle(input.title), - modelSelection, - runtimeMode, - interactionMode, - ...(persona === undefined ? {} : { agentPersonaAssignment: persona.assignment }), - ...spawnThreadCheckout(workspace, sharedCheckout), - }) - .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 attachments that are pending uploads.", - ), - ), - )).attachments; - yield* spawnWorkspace - .startBrief({ - workspace, - stableInput, - ledgerProjectId: facts.home.projectId, - projectId: target, - threadId, - title: spawnTitle(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, - runtimeMode, - 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( @@ -1641,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.test.ts b/apps/server/src/j5/a2a/mcp/tools.test.ts index e978dd22ce897..2f1aa2fa9a3e1 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"; @@ -19,6 +22,7 @@ import { J5StopAgentTool, J5Toolkit, J5_PROPOSE_CREW_DESCRIPTION, + J5_REQUEST_CREW_MEMBER_DESCRIPTION, J5_SPAWN_AGENT_DESCRIPTION, J5_STOP_AGENT_DESCRIPTION, } from "./tools.ts"; @@ -27,6 +31,35 @@ const decodeProposeCrew = Schema.decodeUnknownSync(J5ProposeCrewInput); const decodeRequestCrewMember = Schema.decodeUnknownSync(J5RequestCrewMemberInput); const decodeSpawnAgent = Schema.decodeUnknownSync(J5SpawnAgentInput); +it.effect.each([ + { name: "j5_spawn_agent", description: J5_SPAWN_AGENT_DESCRIPTION, tool: J5SpawnAgentTool }, + { name: "j5_propose_crew", description: J5_PROPOSE_CREW_DESCRIPTION, tool: J5ProposeCrewTool }, + { + name: "j5_request_crew_member", + description: J5_REQUEST_CREW_MEMBER_DESCRIPTION, + tool: J5RequestCrewMemberTool, + }, +])("publishes the canonical $name description byte-for-byte", ({ name, description, tool }) => + 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 section = document.split("### `" + name + "`")[1]?.split("\n### ")[0]; + const quoted = section?.match(/\*\*Description \(contract\):\*\* "([\s\S]*?)"\n\n/)?.[1]; + if (quoted === undefined) + return yield* Effect.die(`${name} contract description is missing from agent-tools.md`); + const documented = quoted + .split("\n") + .map((line) => line.trim()) + .join(" "); + assert.equal(description, documented); + assert.equal(tool.description, documented); + }).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 2b86f540218e7..6fa9cb3834393 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -1,3 +1,5 @@ +import * as SpawnAgentService from "../SpawnAgentService.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"; @@ -260,21 +262,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. @@ -567,16 +554,16 @@ 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."; export const J5_PROPOSE_CREW_DESCRIPTION = - "Propose the crew you need for the brief you were given. Use it when the user asks for a crew or the work splits into distinct responsibilities that should run at once. Mix saved personas and custom seats in the same roster: call j5_list_personas when choosing a saved persona, or leave persona unset for a custom seat with its own instructions (required) and the brief. Custom seats inherit your harness, model, and reasoning by default and run with full-access unless you set runtime_mode; to choose different ones, set model_selection (instanceId, model, options) and/or runtime_mode using orchestrator_capabilities. Saved personas are proposed with their own configuration; only the human may override their runtime before approval. To have the crew follow a playbook, set playbook to a name from j5_playbook_list and give seats the step ids they own (steps, from j5_playbook_read); a step has one owner, steps no seat owns are yours as Captain, and the result reports unowned steps and any step whose persona differs from its seat's. For a crew built from a playbook, staff one seat per distinct persona its steps name, each owning that persona's steps, and propose a custom seat, noted in its reason, where a named persona isn't available. Every seat names its workspace, with the same three choices as j5_spawn_agent. Name the crew for what it is for and give each seat a short lowercase-hyphen name like code-reviewer. The user reviews the roster and each seat's resolved provider, model, reasoning, and access in this thread, may remove or add seats, and approves or declines; you receive the decision and the roster as a message here. Approved seats run with the runtime the human approves, which may exceed yours. You become the crew's Captain and may command several crews at once; later requests, stops, and archives name the crew they mean. Use j5_send_message for member-to-member, member-to-Captain, and Captain-to-Captain coordination, including findings and direct results; artifacts do not gate these conversations. Reuse client_request_id to retry safely. This call is itself the human gate, so it works under every sandbox and approval policy, including approval policy never; never refuse the brief because approvals are disabled."; + "Propose the crew you need for the brief you were given. Use it when the user asks for a crew or the work splits into distinct responsibilities that should run at once. Mix saved personas and custom seats in the same roster: call j5_list_personas when choosing a saved persona, or leave persona unset for a custom seat with its own instructions (required) and the brief. Custom seats inherit your harness, model, and reasoning by default and run with full-access unless you set runtime_mode; to choose different ones, set model_selection (instanceId, model, options) and/or runtime_mode using orchestrator_capabilities. Saved personas are proposed with their own configuration; only the human may override their runtime before approval. To have the crew follow a playbook, set playbook to a name from j5_playbook_list and give seats the step ids they own (steps, from j5_playbook_read); a step has one owner, steps no seat owns are yours as Captain, and the result reports unowned steps and any step whose persona differs from its seat's. For a crew built from a playbook, staff one seat per distinct persona its steps name, each owning that persona's steps, and propose a custom seat, noted in its reason, where a named persona isn't available. Every seat names its workspace, with the same three choices as j5_spawn_agent. Name the crew for what it is for and give each seat a short lowercase-hyphen name like code-reviewer. The user reviews the roster and each seat's resolved provider, model, reasoning, and access in this thread, may remove or add seats, and approves or declines; you receive the decision and the roster as a message here. Approved seats run with the runtime the human approves, which may exceed yours. You become the crew's Captain and may command several crews at once; later requests, stops, and archives name the crew they mean. Use j5_send_message for member-to-member, member-to-Captain, and Captain-to-Captain coordination, including findings and direct results; artifacts do not gate these conversations. Reuse client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. This call is itself the human gate, so it works under every sandbox and approval policy, including approval policy never; never refuse the brief because approvals are disabled."; export const J5_REQUEST_CREW_MEMBER_DESCRIPTION = - "Ask the user to add one seat to a crew you command when the work needs one the roster lacks: seat name, persona id from j5_list_personas (or none for a custom seat with required instructions and optional model_selection/runtime_mode overrides; an omitted model_selection inherits yours and an omitted runtime_mode is full-access; saved-persona runtime changes are made only by the human before approval), a clear reason identifying the concern and missing expertise or responsibility, its workspace (the same three choices as j5_propose_crew), and optionally instructions and a brief for the new seat. On a crew that follows a playbook, steps may claim step ids from j5_playbook_read that no seat owns yet. The user decides from their inbox; you receive the decision and the updated roster as a message here. Continue the already-approved work and direct coordination while the addition is pending. Captain-only; a member sends the concern and needed expertise to its Captain with j5_send_message. Reuse client_request_id to retry safely. Filing the request is the human gate itself and works under every approval policy, including approval policy never."; + "Ask the user to add one seat to a crew you command when the work needs one the roster lacks: seat name, persona id from j5_list_personas (or none for a custom seat with required instructions and optional model_selection/runtime_mode overrides; an omitted model_selection inherits yours and an omitted runtime_mode is full-access; saved-persona runtime changes are made only by the human before approval), a clear reason identifying the concern and missing expertise or responsibility, its workspace (the same three choices as j5_propose_crew), and optionally instructions and a brief for the new seat. On a crew that follows a playbook, steps may claim step ids from j5_playbook_read that no seat owns yet. The user decides from their inbox; you receive the decision and the updated roster as a message here. Continue the already-approved work and direct coordination while the addition is pending. Captain-only; a member sends the concern and needed expertise to its Captain with j5_send_message. Reuse client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. Filing the request is the human gate itself and works under every approval policy, including approval policy never."; export const J5_STOP_AGENT_DESCRIPTION = "Stop one Peer Agent the way a user Stop does: its running turn is interrupted now, turns already queued behind it, messages you sent it included, are held until a person resumes its queue or the next message reaches it (that message resumes the queue and runs after them, in order), its pull request watches end, and the tasks it delegated stop too. The agent remains, stays readable, and can be messaged again later — stopping halts work, it retires nothing. It reaches any agent on this server, in any project. Reuse client_request_id to retry safely."; @@ -617,6 +604,7 @@ const placementDependencies = [ ]; const spawnDependencies = [ + SpawnAgentService.SpawnAgentService, McpInvocationContext.McpInvocationContext, A2ASendService, Crypto.Crypto, @@ -624,6 +612,7 @@ const spawnDependencies = [ ThreadRegistration, A2ALedger, SpawnCompositionService, + 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/migrations/047_RequestReplay.ts b/apps/server/src/j5/a2a/migrations/047_RequestReplay.ts new file mode 100644 index 0000000000000..e96c8651094c6 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/047_RequestReplay.ts @@ -0,0 +1,15 @@ +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, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) + ) + `; +}); diff --git a/apps/server/src/j5/a2a/runtimeLayer.ts b/apps/server/src/j5/a2a/runtimeLayer.ts index 985283d37d2a1..4b126b62c27dc 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"; @@ -49,6 +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 * 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"; @@ -230,6 +232,8 @@ export const makeJ5A2AAuxiliaryLayer = ( lifecycleServiceProvided, archiveFactsProvided, spawnWorkspaceProvided, + RequestReplayService.layer, + 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 d1f179fd9a4cf..857225fdb3b8b 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.test.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.test.ts @@ -1,8 +1,10 @@ +import * as SpawnAgentService from "./SpawnAgentService.ts"; import { assert, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { type AuthMcpClientAccess, ChatAttachmentId, + CommandId, EnvironmentId, ProjectId, ProviderDriverKind, @@ -12,6 +14,9 @@ import { type OrchestrationV2ThreadProjection, type RuntimeMode, } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import { layerMemory } from "../../persistence/Sqlite.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"; @@ -24,12 +29,15 @@ 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 * as SqlClient from "effect/sql/SqlClient"; import { McpInvocationContext, type McpInvocationScope } from "../../mcp/McpInvocationContext.ts"; 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 +171,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 +180,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 +194,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 +253,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 +288,22 @@ 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, + providerInstanceId: invocation.thread.providerInstanceId, + archivedAt: null, + deletedAt: null, + 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 +317,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 +331,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,16 +434,17 @@ 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"]), - // 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`)), + ]), ), }), ), @@ -407,13 +462,23 @@ 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, failFacts, + failCreate, + failBrief, factProjects, folderClaims, recorded, @@ -432,6 +497,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({ @@ -890,6 +981,237 @@ 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", + () => + 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.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.notInclude(message(refused), attachment.name); + 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( + new SqlError({ reason: new UnknownError({ cause: new Error("disk I/O error") }) }), + ); + const replay = Layer.succeed( + RequestReplayService.RequestReplayService, + 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({ @@ -960,9 +1282,34 @@ 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, + 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 first = yield* spawnHarness({ checkout: { isRepo: true, refName: "j5/main" } }); + const replayContext = yield* Layer.build( + RequestReplayService.layer.pipe(Layer.provide(layerMemory)), + ); + const replay = Layer.succeed( + RequestReplayService.RequestReplayService, + Context.get(replayContext, RequestReplayService.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); @@ -972,6 +1319,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)); @@ -979,6 +1327,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({ @@ -989,16 +1338,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); @@ -1006,13 +1362,22 @@ 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)); }), ); -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(); @@ -1039,7 +1404,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. @@ -1053,7 +1422,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", + mismatched ? "different request" : "already in progress", ); } @@ -1182,7 +1551,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, @@ -1236,3 +1605,329 @@ 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); + 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" }, + { 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); + 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), + 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* 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); + 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); + 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 === "full-access" ? [childMode] : [childMode, childMode], + ); + assert.deepStrictEqual( + creates.map((command) => command.worktreePath), + childMode === "full-access" ? [scratchFolder] : [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); + 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); + 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.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. + const harness = yield* spawnHarness({ + checkout: { isRepo: false, refName: null }, + existingChildRuntimeMode: "full-access", + }); + yield* Effect.gen(function* () { + const args = { + ...spawnArgs, + workspace: { type: "shared" as const }, + client_request_id: "pre-upgrade", + }; + const first = yield* harness.call(args); + assert.isFalse(first.isFailure, message(first)); + const finished = yield* Ref.get(harness.commands); + assert.deepStrictEqual( + finished.map((command) => command.type), + ["thread.create", "message.dispatch"], + "the retry finishes the agent as before", + ); + + const changed = yield* harness.call({ ...args, brief: "Different work" }); + assert.isTrue(changed.isFailure); + assert.include(message(changed), "different request"); + assert.deepStrictEqual(yield* Ref.get(harness.commands), finished); + const again = yield* harness.call(args); + assert.deepStrictEqual(again.result, first.result); + }).pipe(Effect.provide(harness.layer)); + }), +); diff --git a/apps/server/src/j5/a2a/spawnWorkspace.ts b/apps/server/src/j5/a2a/spawnWorkspace.ts index 42d0cdc73789d..636f5167dc6c2 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.ts @@ -1,12 +1,13 @@ -import type { - ChatAttachment, +import type { J5SpawnWorkspace } from "./mcp/tools.ts"; +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"; @@ -20,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 { @@ -49,7 +51,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)); @@ -137,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; @@ -226,8 +229,8 @@ export const resolveSpawnWorkspace = ( }; /** - * A request key is bound to the workspace type it was first accepted with: the create command id - * encodes the type. Shared keeps the original id, so spawns already in flight still replay. + * The create command id encodes the workspace type. Shared keeps the original id, so spawns + * already in flight still replay. */ export const spawnCreateCommandId = ( stableInput: SpawnStableInput, @@ -239,7 +242,18 @@ export const spawnCreateCommandId = ( ? lifecycleCommandId({ ...stableInput, operation: "spawn-create-existing" }) : lifecycleCommandId({ ...stableInput, operation: "spawn-create-worktree" }); -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 @@ -296,21 +310,26 @@ 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, and refusing a request key already accepted with the other workspace type. + * thread is in flight. * * 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 the other type's command id would overwrite the first thread. With one start in flight - * per thread, the receipt check can't race the create it guards. The receipt is durable, so the - * binding outlives the in-process guard across a restart. + * under another workspace type's command id would overwrite the first thread. A key keeps its + * 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: { readonly stableInput: SpawnStableInput; readonly threadId: ThreadId; - readonly workspace: ResolvedSpawnWorkspace; }, effect: Effect.Effect, ) => Effect.Effect; @@ -327,6 +346,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< @@ -449,11 +476,39 @@ const make = Effect.gen(function* () { }; }).pipe(Effect.catch(() => Effect.succeed(NO_WORKSPACE_OPTIONS))); - const withSpawnStart: SpawnWorkspaceServiceShape["withSpawnStart"] = (input, effect) => + 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, + ) => // The check, the add, and the releasing finalizer run with no interruptible gap, so an // interrupt can't leak an entry and block every later start of this thread. Effect.uninterruptibleMask((restore) => - Effect.suspend(() => { + Effect.suspend((): Effect.Effect => { if (startsInFlight.has(input.threadId)) return Effect.fail( new SpawnWorkspaceError({ @@ -462,30 +517,9 @@ const make = Effect.gen(function* () { }), ); startsInFlight.add(input.threadId); - return restore( - Effect.gen(function* () { - for (const other of WORKSPACE_TYPES) { - if (other === input.workspace.type) continue; - const bound = yield* receipts - .getByCommandId(spawnCreateCommandId(input.stableInput, other)) - .pipe( - Effect.mapError( - (error) => - new SpawnWorkspaceError({ - detail: `The spawn's earlier workspace choice could not be read: ${error.message}`, - nextStep: "Retry with the same client_request_id.", - }), - ), - ); - if (Option.isSome(bound)) - 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.`, - }); - } - return yield* effect; - }), - ).pipe(Effect.ensuring(Effect.sync(() => startsInFlight.delete(input.threadId)))); + return restore(effect).pipe( + Effect.ensuring(Effect.sync(() => startsInFlight.delete(input.threadId))), + ); }), ); @@ -496,7 +530,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, @@ -507,7 +541,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, @@ -531,11 +565,18 @@ 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, + assertExistingWorkspace, startBrief, + briefAccepted, }); }); @@ -544,3 +585,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/j5/a2a/test-support/spawnWorkspaceFakes.ts b/apps/server/src/j5/a2a/test-support/spawnWorkspaceFakes.ts index 73e5c97937df7..a11e2605c09db 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 * as RequestReplayService 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 ?? 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 b111ee2d2ee00..194aa2bffe608 100644 --- a/apps/server/src/mcp/toolkits/worktree/registration.test.ts +++ b/apps/server/src/mcp/toolkits/worktree/registration.test.ts @@ -1,3 +1,5 @@ +import * as SpawnAgentService from "../../../j5/a2a/SpawnAgentService.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"; @@ -99,6 +101,8 @@ const layerStubServices = Layer.mergeAll( Layer.mock(PlaybookCrewRelay)({}), Layer.mock(PlaybookStore)({}), Layer.mock(SpawnCompositionService)({}), + 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 4ef6d3184cc5f..d9a09f1a90ca8 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 | | ------------------- | ------------------------------------- | -------- | ------------------------------------------------- | @@ -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. 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. -**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. @@ -216,7 +216,7 @@ seats run with the runtime the human approves, which may exceed yours. You becom and may command several crews at once; later requests, stops, and archives name the crew they mean. Use j5_send_message for member-to-member, member-to-Captain, and Captain-to-Captain coordination, including findings and direct results; artifacts do not gate these conversations. Reuse -client_request_id to retry safely. This call is itself the human gate, so it works under every +client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. This call is itself the human gate, so it works under every sandbox and approval policy, including approval policy never; never refuse the brief because approvals are disabled." @@ -271,7 +271,7 @@ optionally instructions and a brief for the new seat. On a crew that follows a p claim step ids from j5_playbook_read that no seat owns yet. The user decides from their inbox; you receive the decision and the updated roster as a message here. Continue the already-approved work and direct coordination while the addition is pending. Captain-only; a member sends the concern and -needed expertise to its Captain with j5_send_message. Reuse client_request_id to retry safely. Filing +needed expertise to its Captain with j5_send_message. Reuse client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. Filing the request is the human gate itself and works under every approval policy, including approval policy never." @@ -486,6 +486,8 @@ 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 replay accepted work where the original workspace remains available; the `j5_spawn_agent` contract description matches the shipped string ([PR #660](https://github.com/Jacksondr5/j5code/pull/660)). - 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 — 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)).