From 04e260b6dee8cec56c41d90140e28cb8b81547a8 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 11:10:44 -0400 Subject: [PATCH 01/12] feat(j5): start Crew members on their first assignment --- FORK.md | 2 + .../src/j5/a2a/AgentCrewInstanceService.ts | 9 +- .../CrewDeliveryContext.integration.test.ts | 259 ++++++++++++++++ .../src/j5/a2a/CrewDeliveryContext.test.ts | 285 ++++++++++++++++++ apps/server/src/j5/a2a/CrewDeliveryContext.ts | 203 +++++++++++++ .../src/j5/a2a/CrewLaunchReporter.test.ts | 25 ++ apps/server/src/j5/a2a/CrewLaunchReporter.ts | 22 +- .../src/j5/a2a/CrewLaunchService.test.ts | 84 +++--- apps/server/src/j5/a2a/CrewLaunchService.ts | 87 +++--- .../src/j5/a2a/CrewProposalService.test.ts | 43 ++- apps/server/src/j5/a2a/CrewSeatPreparation.ts | 50 +++ apps/server/src/j5/a2a/Migrations.test.ts | 2 + apps/server/src/j5/a2a/Migrations.ts | 2 + apps/server/src/j5/a2a/crewGateNotice.ts | 14 +- apps/server/src/j5/a2a/crewMembershipsRead.ts | 7 +- apps/server/src/j5/a2a/fleetRead.ts | 2 + apps/server/src/j5/a2a/mcp/tools.ts | 4 +- .../migrations/049_CrewSeatActivation.test.ts | 52 ++++ .../a2a/migrations/049_CrewSeatActivation.ts | 27 ++ apps/server/src/j5/a2a/runtimeLayer.ts | 2 + apps/server/src/j5/a2a/spawnIds.ts | 21 +- apps/server/src/j5/a2a/spawnedChildrenRead.ts | 1 + .../j5/test-support/threadLaunchHarness.ts | 13 +- .../src/orchestration-v2/runtimeLayer.ts | 8 +- .../web/src/j5/a2a/ThreadA2ARenderer.test.tsx | 10 + apps/web/src/j5/a2a/ThreadA2ARenderer.tsx | 8 +- .../web/src/j5/crew/crewNotices.logic.test.ts | 12 + apps/web/src/j5/crew/crewNotices.logic.ts | 8 +- apps/web/src/j5/crew/crewState.test.ts | 13 + apps/web/src/j5/crew/crewState.ts | 6 +- apps/web/src/j5/fleet/FleetFacts.tsx | 11 +- apps/web/src/j5/fleet/FleetPage.tsx | 6 +- apps/web/src/j5/threads/SpawnedChildren.tsx | 6 +- .../src/j5/threads/spawnedChildren.logic.ts | 4 +- docs/j5/product/a2a/agent-tools.md | 64 ++-- docs/j5/product/features/crews.md | 14 +- packages/contracts/src/j5.ts | 17 +- .../contracts/src/j5/crewDeliveryContext.ts | 15 + .../src/j5/orchestrationInstructions.ts | 2 +- 39 files changed, 1242 insertions(+), 178 deletions(-) create mode 100644 apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts create mode 100644 apps/server/src/j5/a2a/CrewDeliveryContext.test.ts create mode 100644 apps/server/src/j5/a2a/CrewDeliveryContext.ts create mode 100644 apps/server/src/j5/a2a/CrewSeatPreparation.ts create mode 100644 apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts create mode 100644 apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.ts create mode 100644 packages/contracts/src/j5/crewDeliveryContext.ts diff --git a/FORK.md b/FORK.md index 878cf55ad05d7..5f3ba0f1d6b3d 100644 --- a/FORK.md +++ b/FORK.md @@ -315,6 +315,8 @@ migrations after upstream migrations. 36. Provider event log file names: `apps/server/src/provider/EventNdjsonLogger.ts` `resolveThreadSegment` ends the segment with a twelve-character hash of the whole thread id whenever normalization shortened the id (a colon, a run of punctuation, or the eighty-character cap), because platform-spawned threads (Crew seats, Peer Agents) carry deterministic ids identical up to the cut and every seat of a Crew was landing in one log file. Only a bare uuid id, which normalization leaves untouched, keeps its plain name; ids with colons that were under the cap change name once on upgrade. One appended branch; `EventNdjsonLogger.test.ts` covers it. 37. The lone-seat archive guard (2026-09-17, Bryant's choice of the server dispatch handler over a client-side mirror or an after-the-fact reversal, after Jackson's review of PR #151): the `layer` of `apps/server/src/ws.ts` yields J5-owned `makeCrewSeatArchiveGuard` (`apps/server/src/j5/a2a/crewSeatArchiveGuard.ts`) once and passes it to `layerWsRpc`, which hands it to case 78's command admission, the one J5 call `dispatchCommand` carries. Every client door (web sidebar, mobile swipe, any future client) sends `thread.archive` and `thread.delete` through that one handler, so a live Crew's seat is refused there with a typed error whose message reaches the client as the dispatch error's detail; `j5_archive_crew` and the Captain cascade archive seats through the lifecycle service and never meet the guard. A Crew store that cannot be read lets the command through, because a refusal rests on a live fact, not an outage. The web keeps its pre-archive toast as the friendlier early message. +The same runtime composition wraps the orchestrator with `j5/a2a/CrewDeliveryContext.ts` (#745). Only Crew-seat message dispatches gain the approved first-turn context or net roster changes; direct chat, MCP messages, and playbook handoffs share this seam. J5 migration 48 owns the context and delivery bookkeeping. First assignments for new-worktree seats use upstream's `defer_start` workspace preparation; `j5/a2a/CrewSeatPreparation.ts` starts that preparation from persisted run events and resumes preparing seats on boot. Keep the decorator shared by all thread-management callers; do not move it into one transport. Ordinary threads and non-message commands retain upstream behavior. + 38. Fork placement: `orchestration-v2/runtimeLayer.ts` decorates the single `layerThreadManagementProvided` instance with J5 `ThreadLineage.ts`. It reaches both client intake and MCP. The decorator acts on `thread.fork` only. It registers the source if it has no home yet, then records the fork's home and its `forked-from` provenance in one transaction through the existing creation composition; existing placement policy makes the fork a sibling of its source. A Subagent source is not a participant, so its fork registers like any new thread and gets no placement. Replaying the original command repairs a placement that failed after the fork committed, without another fork. Merge-back passes straight through, and its tool is upstream's (case 2). Upstream dropped its same-project rule for thread tools: fork, merge-back and organize reach any thread in the environment, within the limits upstream's `McpToolAccess` checks, and J5 adds no project rule of its own (Jackson's 2026-10-08 decision 6). Creation-side placement and composition avoid a delivery-to-thread-management dependency cycle. J5 re-declares the fork, organize and queue-edit tools (case 2): fork to expose actionable placement errors, organize to apply the shared crew-seat guard before dispatch, queue edit to hold an agent to its own messages. Unit retirement continues through the internal archive service. Organize settles through upstream's `settleThread`, so a settle asked for during a running turn takes effect when the turn ends, and a Crew seat may settle itself (decision 12). All other adopted tool handlers use original upstream tool objects and handler layers. The queue's cancel, reorder and promote tools are upstream's (#136). Case 34's typed HTTP migration is tracked in #137. 39. The welcome wizard's "Providers" wording: `components/onboarding/WelcomeWizard.tsx` is upstream's file except for branding (case B: the app name and CLI command from `branding.ts`, and the plain header title in place of the T3 wordmark) and four wording edits that say providers where upstream says agents: the second stage's label in `ONBOARDING_STAGES` (`"Providers"`), the Connect stage's sentence ("We'll set up providers and projects on each"), and the file-header and step comments. J5 calls the runtimes providers and keeps "agent" for the threads a person directs. On every upstream advance, re-apply these four edits. The rest of this case is retired (2026-10-04, the Squadron fold, [#412](https://github.com/Jacksondr5/j5code/issues/412)): the wizard's fourth Squadron stage is removed, `apps/web/src/j5/onboarding/` is deleted, and `routes/welcome.tsx` carries only case 73's refusal of the wizard to anyone but a named Owner. Imported conversations register in their project like every other thread (case 10), and the server's assignment route is removed (case 9). diff --git a/apps/server/src/j5/a2a/AgentCrewInstanceService.ts b/apps/server/src/j5/a2a/AgentCrewInstanceService.ts index 7d63cda4d7925..7bd9372a07d07 100644 --- a/apps/server/src/j5/a2a/AgentCrewInstanceService.ts +++ b/apps/server/src/j5/a2a/AgentCrewInstanceService.ts @@ -13,6 +13,7 @@ import { ParticipantId, type LedgerProjectId } from "./contracts.ts"; import { ReadChanges } from "./ReadChanges.ts"; export interface AgentCrewMember { + readonly notStarted?: boolean; readonly seatName: string; /** The saved agent the seat runs as; null for a custom seat that runs as the Captain. */ readonly agentId: string | null; @@ -68,6 +69,7 @@ export interface RecordAgentCrewInput { export interface AgentCrewMembership { readonly crewInstanceId: string; + readonly notStarted?: boolean; readonly seatName: string; } @@ -184,6 +186,7 @@ interface InstanceRow { interface MemberRow { readonly crew_instance_id: string; + readonly not_started: number | null; readonly seat_name: string; readonly agent_id: string | null; readonly participant_id: string; @@ -229,6 +232,7 @@ const stepOwnershipConflict = ( }; const memberFromRow = (row: MemberRow): AgentCrewMember => ({ + ...(row.not_started == null ? {} : { notStarted: row.not_started === 1 }), seatName: row.seat_name, agentId: row.agent_id, participantId: ParticipantId.make(row.participant_id), @@ -272,7 +276,10 @@ export const layer: Layer.Layer` - SELECT * FROM j5_agent_crew_member + SELECT member.*, CASE WHEN context.thread_id IS NULL THEN NULL + WHEN context.delivered_roster IS NULL THEN 1 ELSE 0 END AS not_started + FROM j5_agent_crew_member AS member + LEFT JOIN j5_crew_seat_context AS context ON context.thread_id = member.thread_id WHERE crew_instance_id IN ${sql.in(rows.map(({ id }) => id))} `; return rows.map((row) => instanceFromRows(row, members)); diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts new file mode 100644 index 0000000000000..18602a90dc829 --- /dev/null +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts @@ -0,0 +1,259 @@ +import { assert, it } from "@effect/vitest"; +import { CommandId, EventId, MessageId, ThreadId } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Fiber from "effect/Fiber"; +import * as Stream from "effect/Stream"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { EventSinkV2 } from "../../orchestration-v2/EventSink.ts"; +import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; +import { makeHarness, modelSelection, projectId } from "../test-support/threadLaunchHarness.ts"; +import * as Crews from "./AgentCrewInstanceService.ts"; +import * as Preparation from "./CrewSeatPreparation.ts"; +import { A2ALedger, layer as ledgerLayer } from "./LedgerService.ts"; +import { LedgerProjectId } from "./contracts.ts"; +import { participantIdForThread } from "./HomeRegistrar.ts"; +import { spawnFirstTurnText } from "./spawnIds.ts"; + +it.effect( + "direct chat activates a waiting seat, prepares its worktree, and queues follow-up work", + () => + Effect.gen(function* () { + const checkoutStarted = yield* Deferred.make(); + const finishCheckout = yield* Deferred.make(); + const harness = makeHarness({ + crewDeliveryContext: true, + createWorktree: (input) => + Deferred.succeed(checkoutStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishCheckout)), + Effect.as({ + worktree: { + path: "/repo-worktrees/crew-reviewer", + refName: input.newRefName, + headSha: "abc", + }, + } as never), + ), + }); + const services = Layer.mergeAll( + harness.layer, + Crews.layer.pipe(Layer.provide(harness.layer)), + ledgerLayer.pipe(Layer.provide(harness.layer)), + ); + const layer = Preparation.layer.pipe( + Layer.provideMerge(services), + Layer.provideMerge(harness.orchestrator), + ); + yield* Effect.gen(function* () { + const threads = yield* ThreadManagementService; + const crews = yield* Crews.AgentCrewInstanceService; + const sql = yield* SqlClient.SqlClient; + const threadId = ThreadId.make("thread:crew-reviewer"); + const captainThreadId = ThreadId.make("thread:captain"); + const ledgerProjectId = LedgerProjectId.make(projectId); + yield* (yield* A2ALedger).ensureProject({ + projectId: ledgerProjectId, + createdAt: "2026-10-27T12:00:00Z", + }); + yield* crews.record({ + id: "crew:integration", + projectId: ledgerProjectId, + captainThreadId, + captainParticipantId: participantIdForThread(captainThreadId), + displayName: "Review", + brief: "Shared goal", + createdAt: "2026-10-27T12:00:00Z", + members: [ + { + seatName: "reviewer", + agentId: null, + threadId, + participantId: participantIdForThread(threadId), + reason: "Review the fix", + }, + ], + }); + const text = spawnFirstTurnText({ + brief: "Shared goal", + participantId: participantIdForThread(threadId), + projectId, + projectTitle: "Project", + spawnedByParticipantId: participantIdForThread(captainThreadId), + crew: { + displayName: "Review", + instanceId: "crew:integration", + seatName: "reviewer", + captainParticipantId: participantIdForThread(captainThreadId), + roster: [], + }, + }); + yield* sql`INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace) + VALUES (${threadId}, ${text}, '{"type":"worktree","baseRef":"main"}')`; + yield* threads.dispatch({ + type: "thread.create", + commandId: CommandId.make("command:create-reviewer"), + threadId, + projectId, + title: "Reviewer", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "agent", + creationSource: "mcp", + branch: null, + worktreePath: null, + }); + assert.lengthOf((yield* threads.getThreadProjection(threadId)).runs, 0); + assert.isTrue((yield* crews.read("crew:integration"))!.members[0]!.notStarted); + yield* threads.sendToThread({ + projectId, + threadId, + commandId: CommandId.make("command:first-assignment"), + messageId: MessageId.make("message:first-assignment"), + text: "Review the code now.", + attachments: [], + mode: "auto", + createdBy: "user", + creationSource: "web", + }); + yield* Deferred.await(checkoutStarted); + const preparing = yield* threads.getThreadProjection(threadId); + assert.equal(preparing.runs[0]!.status, "preparing"); + assert.include(preparing.messages[0]!.text, "Shared goal"); + assert.isTrue(preparing.messages[0]!.text.endsWith("Review the code now.")); + assert.isFalse((yield* crews.read("crew:integration"))!.members[0]!.notStarted); + yield* threads.sendToThread({ + projectId, + threadId, + commandId: CommandId.make("command:follow-up"), + messageId: MessageId.make("message:follow-up"), + text: "Check the failure path too.", + attachments: [], + mode: "queue", + createdBy: "agent", + creationSource: "mcp", + }); + const queued = yield* threads.getThreadProjection(threadId); + assert.equal( + queued.messages.find((message) => message.id === "message:follow-up")!.text, + "Check the failure path too.", + ); + assert.isTrue(queued.runs.some((run) => run.status === "queued")); + const released = yield* threads.streamStoredEventsFrom({ afterSequence: 0 }).pipe( + Stream.filter( + (stored) => + stored.event.type === "run.updated" && + stored.event.threadId === threadId && + stored.event.payload.status === "starting", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Deferred.succeed(finishCheckout, undefined); + yield* Fiber.join(released); + const ready = yield* threads.getThreadProjection(threadId); + assert.equal(ready.thread.worktreePath, "/repo-worktrees/crew-reviewer"); + assert.equal(harness.createWorktree.mock.calls[0]?.[0]?.baseRefName, "main"); + assert.lengthOf(harness.createWorktree.mock.calls, 1); + const now = yield* DateTime.now; + yield* (yield* EventSinkV2).write({ + events: ready.runs.map((run) => ({ + id: EventId.make(`event:finished:${run.id}`), + type: "run.updated" as const, + threadId, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { + ...run, + status: "completed" as const, + completedAt: now, + queuePosition: null, + }, + })), + }); + const reused = yield* threads.sendToThread({ + projectId, + threadId, + commandId: CommandId.make("command:reuse-finished-seat"), + messageId: MessageId.make("message:reuse-finished-seat"), + text: "Review the revision.", + attachments: [], + mode: "auto", + createdBy: "agent", + creationSource: "mcp", + }); + assert.equal(reused.message.text, "Review the revision."); + assert.equal(reused.run.threadId, threadId); + assert.equal(reused.projection.thread.worktreePath, ready.thread.worktreePath); + assert.lengthOf((yield* crews.read("crew:integration"))!.members, 1); + assert.lengthOf(harness.createWorktree.mock.calls, 1); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("a preparing Crew seat resumes worktree preparation after restart", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const threads = yield* ThreadManagementService; + const sql = yield* SqlClient.SqlClient; + const threadId = ThreadId.make("thread:preparing-at-restart"); + yield* threads.dispatch({ + type: "thread.create", + commandId: CommandId.make("command:create-at-restart"), + threadId, + projectId, + title: "Reviewer", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "agent", + creationSource: "mcp", + branch: null, + worktreePath: null, + }); + yield* sql`INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace, delivered_roster) + VALUES (${threadId}, 'approved context', '{"type":"worktree","baseRef":"main"}', '[]')`; + yield* threads.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("command:accepted-before-restart"), + threadId, + messageId: MessageId.make("message:accepted-before-restart"), + text: "Existing assignment", + attachments: [], + createdBy: "user", + creationSource: "web", + dispatchMode: { + type: "defer_start", + workspaceStrategy: { type: "worktree", baseRef: "main" }, + }, + }); + assert.equal((yield* threads.getThreadProjection(threadId)).runs[0]!.status, "preparing"); + const context = yield* Effect.context< + | ThreadManagementService + | import("../../orchestration-v2/ThreadLaunchService.ts").ThreadLaunchService + | SqlClient.SqlClient + | EventSinkV2 + >(); + yield* threads.streamStoredEventsFrom({ afterSequence: 0 }).pipe( + Stream.filter( + (stored) => + stored.event.type === "run.updated" && + stored.event.threadId === threadId && + stored.event.payload.status === "starting", + ), + Stream.take(1), + Stream.runDrain, + Effect.provide(Preparation.layer.pipe(Layer.provide(Layer.succeedContext(context)))), + ); + assert.equal( + (yield* threads.getThreadProjection(threadId)).thread.worktreePath, + "/repo-worktrees/feature", + ); + assert.lengthOf(harness.createWorktree.mock.calls, 1); + }).pipe(Effect.provide(Layer.mergeAll(harness.layer, harness.orchestrator))); +}); diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts new file mode 100644 index 0000000000000..ab511098c2b39 --- /dev/null +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts @@ -0,0 +1,285 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + ThreadId, + type OrchestrationV2ServerCommand, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; + +import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts"; +import { + CommandReceiptStoreV2, + type CommandReceiptV2, +} from "../../orchestration-v2/CommandReceiptStore.ts"; +import * as Crews from "./AgentCrewInstanceService.ts"; +import * as DeliveryContext from "./CrewDeliveryContext.ts"; +import { participantIdForThread } from "./HomeRegistrar.ts"; +import { A2ALedger, layer as ledgerLayer } from "./LedgerService.ts"; +import { runJ5A2AMigrations } from "./Migrations.ts"; +import { LedgerProjectId } from "./contracts.ts"; +import { spawnFirstTurnText } from "./spawnIds.ts"; + +const database = NodeSqliteClient.layer({ filename: ":memory:" }); +const base = Layer.mergeAll( + database, + Crews.layer.pipe(Layer.provide(database)), + ledgerLayer.pipe(Layer.provide(database)), +); +const seatId = ThreadId.make("thread:reviewer"); +const captainThreadId = ThreadId.make("thread:captain"); +const projectId = LedgerProjectId.make("project:crew-context"); +const member = (name: string) => ({ + seatName: name, + agentId: null, + threadId: ThreadId.make(`thread:${name}`), + participantId: participantIdForThread(ThreadId.make(`thread:${name}`)), + reason: `Responsibility of ${name}`, +}); +const assignment = (id: string, createdBy: "user" | "agent" | "system" = "agent") => ({ + type: "message.dispatch" as const, + commandId: CommandId.make(`command:${id}`), + threadId: seatId, + messageId: MessageId.make(`message:${id}`), + text: `\nassignment ${id}\nreply_to: sender\n`, + senderThreadId: captainThreadId, + attachments: [], + dispatchMode: { type: "start_immediately" as const }, + createdBy, + creationSource: "mcp" as const, +}); +const fixture = Effect.gen(function* () { + yield* runJ5A2AMigrations(); + const sql = yield* SqlClient.SqlClient; + const crews = yield* Crews.AgentCrewInstanceService; + const createdAt = "2026-10-27T12:00:00.000Z"; + yield* (yield* A2ALedger).ensureProject({ projectId, createdAt }); + yield* crews.record({ + id: "crew:test", + projectId, + captainThreadId, + captainParticipantId: participantIdForThread(captainThreadId), + displayName: "Test crew", + brief: "Shared goal", + createdAt, + members: [member("reviewer"), member("builder")], + }); + const firstTurnText = spawnFirstTurnText({ + brief: "Shared goal", + participantId: participantIdForThread(seatId), + projectId, + projectTitle: "Test", + spawnedByParticipantId: participantIdForThread(captainThreadId), + spawnerThreadId: captainThreadId, + crew: { + displayName: "Test crew", + instanceId: "crew:test", + seatName: "reviewer", + captainParticipantId: participantIdForThread(captainThreadId), + roster: [], + seatInstructions: "Review carefully.", + }, + }); + yield* sql`INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace) + VALUES (${seatId}, ${firstTurnText}, '{"type":"shared"}')`; + const commands = yield* Ref.make>([]); + const receipts = new Map(); + const rejected = new Set(); + const dependencies = Layer.mergeAll( + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadShell: () => Effect.succeed({ worktreePath: null } as never), + getThreadRecords: () => Effect.succeed({ runs: [] } as never), + dispatch: (command) => + Effect.gen(function* () { + if (receipts.has(command.commandId)) return { sequence: 1, storedEvents: [] }; + if (rejected.has(command.commandId)) + return yield* new Orchestrator.OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + }); + yield* Ref.update(commands, (all) => [...all, command]); + receipts.set(command.commandId, { status: "accepted" } as CommandReceiptV2); + return { sequence: 1, storedEvents: [] }; + }), + }), + Layer.mock(CommandReceiptStoreV2)({ + getByCommandId: (id) => Effect.succeed(Option.fromNullishOr(receipts.get(id))), + }), + ); + const layer = DeliveryContext.layer.pipe(Layer.provide(dependencies)); + const send = (command: OrchestrationV2ServerCommand) => + Effect.gen(function* () { + return yield* (yield* Orchestrator.OrchestratorV2).dispatch(command); + }); + return { sql, crews, commands, receipts, rejected, layer, send }; +}); + +it.effect( + "a direct user message starts a seat with its approved brief, current roster and intact envelope", + () => + Effect.gen(function* () { + const f = yield* fixture; + yield* f.crews.addMembers("crew:test", [member("security")]); + yield* f.crews.removeMembers("crew:test", ["builder"]); + const command = assignment("direct", "user"); + yield* f.send(command).pipe(Effect.provide(f.layer)); + const [delivered] = yield* Ref.get(f.commands); + assert.equal(delivered?.type, "message.dispatch"); + if (delivered?.type !== "message.dispatch") return; + assert.include(delivered.text, "\nShared goal\n"); + assert.include(delivered.text, "Review carefully."); + assert.include( + delivered.text, + `- security: participant_id=${member("security").participantId} persona=custom responsibility=Responsibility of security`, + ); + assert.notInclude(delivered.text, "- builder:"); + assert.notInclude(delivered.text, ""); + assert.isTrue(delivered.text.endsWith(command.text)); + assert.equal(delivered.messageId, command.messageId); + assert.equal(delivered.senderThreadId, command.senderThreadId); + assert.equal(delivered.createdBy, "user"); + assert.isFalse((yield* f.crews.read("crew:test"))!.members[0]!.notStarted); + }).pipe(Effect.provide(base)), +); + +it.effect("playbook deliveries activate a new-worktree seat through durable preparation", () => + Effect.gen(function* () { + const f = yield* fixture; + yield* f.sql`UPDATE j5_crew_seat_context SET workspace = '{"type":"worktree","baseRef":"j5/main"}'`; + yield* f + .send({ ...assignment("playbook", "system"), text: "\nDo the review" }) + .pipe(Effect.provide(f.layer)); + const [delivered] = yield* Ref.get(f.commands); + if (delivered?.type !== "message.dispatch") return assert.fail("missing assignment"); + assert.deepStrictEqual(delivered.dispatchMode, { + type: "defer_start", + workspaceStrategy: { type: "worktree", baseRef: "j5/main" }, + }); + assert.include(delivered.text, "Shared goal"); + assert.isTrue(delivered.text.endsWith("\nDo the review")); + }).pipe(Effect.provide(base)), +); + +it.effect("finished members get only their next assignment and net roster changes, once", () => + Effect.gen(function* () { + const f = yield* fixture; + yield* Effect.gen(function* () { + yield* f.send(assignment("first")); + yield* f.crews.addMembers("crew:test", [member("temporary")]); + yield* f.crews.removeMembers("crew:test", ["temporary", "builder"]); + yield* f.crews.addMembers("crew:test", [member("security")]); + assert.lengthOf(yield* Ref.get(f.commands), 1); + yield* f.send(assignment("second")); + yield* f.send(assignment("third")); + yield* f.send(assignment("third")); + }).pipe(Effect.provide(f.layer)); + const delivered = (yield* Ref.get(f.commands)).filter( + (command) => command.type === "message.dispatch", + ); + assert.lengthOf(delivered, 3); + assert.isTrue( + delivered[1]!.text.startsWith("\n"), + ); + assert.include(delivered[1]!.text, "joined: security:"); + assert.include(delivered[1]!.text, "left: builder:"); + assert.notInclude(delivered[1]!.text, "temporary"); + assert.notInclude(delivered[1]!.text, "spawner_brief"); + assert.equal(delivered[2]!.text, assignment("third").text); + }).pipe(Effect.provide(base)), +); + +it.effect("concurrent first assignments introduce a seat only once", () => + Effect.gen(function* () { + const f = yield* fixture; + yield* Effect.all([f.send(assignment("one")), f.send(assignment("two"))], { + concurrency: "unbounded", + }).pipe(Effect.provide(f.layer)); + const commands = (yield* Ref.get(f.commands)).filter( + (command) => command.type === "message.dispatch", + ); + assert.lengthOf( + commands.filter((command) => command.text.includes("")), + 1, + ); + assert.lengthOf(commands, 2); + }).pipe(Effect.provide(base)), +); + +it.effect("a rejected assignment leaves the introduction owed to the next assignment", () => + Effect.gen(function* () { + const f = yield* fixture; + f.rejected.add("command:refused"); + yield* Effect.gen(function* () { + yield* f.send(assignment("refused")).pipe(Effect.result); + yield* f.crews.addMembers("crew:test", [member("security")]); + yield* f.send(assignment("accepted")); + }).pipe(Effect.provide(f.layer)); + const [delivered] = yield* Ref.get(f.commands); + if (delivered?.type !== "message.dispatch") return assert.fail("missing assignment"); + assert.include(delivered.text, ""); + assert.include(delivered.text, "- security:"); + }).pipe(Effect.provide(base)), +); + +it.effect( + "a committed first assignment is recovered after a crash without repeating its introduction", + () => + Effect.gen(function* () { + const f = yield* fixture; + // Simulate the cut between the orchestration commit and J5's delivered-roster write. + yield* f.sql`UPDATE j5_crew_seat_context SET pending_command_id = 'command:first', pending_roster = '[]'`; + f.receipts.set("command:first", { status: "accepted" } as CommandReceiptV2); + yield* f.send(assignment("later")).pipe(Effect.provide(f.layer)); + const [delivered] = yield* Ref.get(f.commands); + if (delivered?.type !== "message.dispatch") return assert.fail("missing assignment"); + assert.notInclude(delivered.text, ""); + assert.include(delivered.text, ""); + }).pipe(Effect.provide(base)), +); + +it.effect( + "follow-up work is refused after a worktree preparation failed instead of running in the project root", + () => + Effect.gen(function* () { + const f = yield* fixture; + yield* f.sql`UPDATE j5_crew_seat_context SET delivered_roster = '[]', workspace = '{"type":"worktree","baseRef":"main"}'`; + const result = yield* f + .send(assignment("after-failed-preparation")) + .pipe(Effect.result, Effect.provide(f.layer)); + assert.equal(result._tag, "Failure"); + if (result._tag === "Failure") + assert.include(result.failure.message, "Retry workspace preparation"); + assert.lengthOf(yield* Ref.get(f.commands), 0); + }).pipe(Effect.provide(base)), +); + +it.effect( + "direct human assignments keep their author attribution and displayed words after activation and replay", + () => + Effect.gen(function* () { + const f = yield* fixture; + const authorPrefix = "[Message from Bryant (owner)]\n\n"; + const command = { ...assignment("authored", "user"), text: authorPrefix + "Review the fix." }; + yield* f.sql`INSERT INTO j5_a2a_message_author + (thread_id, message_id, person_id, display_name, level, stored_prefix, created_at) + VALUES (${seatId}, ${command.messageId}, 'human:owner', 'Bryant', 'owner', ${authorPrefix}, '2026-10-27T12:00:00Z')`; + yield* Effect.gen(function* () { + yield* f.send(command); + yield* f.send(command); + }).pipe(Effect.provide(f.layer)); + const [author] = yield* f.sql<{ readonly stored_prefix: string; readonly person_id: string }>` + SELECT stored_prefix, person_id FROM j5_a2a_message_author WHERE message_id = ${command.messageId} + `; + const [delivered] = yield* Ref.get(f.commands); + if (delivered?.type !== "message.dispatch") return assert.fail("missing assignment"); + assert.equal(author!.person_id, "human:owner"); + assert.isTrue(delivered.text.startsWith(author!.stored_prefix)); + assert.equal(delivered.text.slice(author!.stored_prefix.length), "Review the fix."); + assert.lengthOf(yield* Ref.get(f.commands), 1); + }).pipe(Effect.provide(base)), +); diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.ts new file mode 100644 index 0000000000000..9ba5cbb91ae3b --- /dev/null +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.ts @@ -0,0 +1,203 @@ +import { CommandId, ThreadId, type OrchestrationV2ServerCommand } from "@t3tools/contracts"; +import { CrewSeatWorkspace, crewDeliveryContextPrefix } from "@t3tools/contracts/j5"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as KeyedLock from "@t3tools/shared/KeyedLock"; + +import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts"; +import { CommandReceiptStoreV2 } from "../../orchestration-v2/CommandReceiptStore.ts"; +import * as Crews from "./AgentCrewInstanceService.ts"; +import * as ReadChanges from "./ReadChanges.ts"; +import { participantIdForThread } from "./HomeRegistrar.ts"; +import { crewContextText } from "./spawnIds.ts"; + +class CrewSeatWorkspaceNotReadyError extends Orchestrator.OrchestratorDispatchError.extend( + "CrewSeatWorkspaceNotReadyError", +)({ threadId: ThreadId }) { + override get message(): string { + return "This Crew seat's worktree is not ready. Retry workspace preparation in its thread before sending more work."; + } +} +const isWorkspaceNotReady = Schema.is(CrewSeatWorkspaceNotReadyError); + +const Roster = Schema.fromJsonString( + Schema.Array( + Schema.Struct({ + seat: Schema.String, + participantId: Schema.String, + agentDisplayName: Schema.String, + reason: Schema.NullOr(Schema.String), + }), + ), +); +const encodeRoster = Schema.encodeSync(Roster); +const isOrchestratorError = Schema.is(Orchestrator.OrchestratorV2Error); +const decodeRoster = Schema.decodeUnknownEffect(Roster); +const decodeWorkspace = Schema.decodeUnknownEffect(Schema.fromJsonString(CrewSeatWorkspace)); +const line = (value: string) => value.replace(/\s+/g, " ").replace(/<\//g, "<\\/").trim(); + +interface SeatContextRow { + readonly first_turn_text: string; + readonly workspace: string; + readonly delivered_roster: string | null; + readonly pending_command_id: string | null; + readonly pending_roster: string | null; + readonly pending_message_id: string | null; + readonly pending_prefix: string | null; +} + +/** All message entry points meet here, before upstream commits the assignment and starts work. */ +export const layer = Layer.effect( + Orchestrator.OrchestratorV2, + Effect.gen(function* () { + const inner = yield* Orchestrator.OrchestratorV2; + const sql = yield* SqlClient.SqlClient; + const crews = yield* Crews.AgentCrewInstanceService; + const receipts = yield* CommandReceiptStoreV2; + const changes = yield* ReadChanges.ReadChanges; + const locks = yield* KeyedLock.make(); + + const acknowledge = ( + threadId: string, + roster: string | null, + messageId: string | null, + prefix: string, + ) => + sql.withTransaction( + Effect.gen(function* () { + if (prefix !== "" && messageId !== null) + yield* sql` + UPDATE j5_a2a_message_author SET stored_prefix = ${prefix} || stored_prefix + WHERE thread_id = ${threadId} AND message_id = ${messageId} + `; + yield* sql` + UPDATE j5_crew_seat_context SET delivered_roster = ${roster}, + pending_command_id = NULL, pending_roster = NULL, pending_message_id = NULL, + pending_prefix = NULL WHERE thread_id = ${threadId} + `; + }), + ); + + const dispatch: Orchestrator.OrchestratorV2["Service"]["dispatch"] = (command) => { + if (command.type !== "message.dispatch") return inner.dispatch(command); + return locks.withLock( + command.threadId, + Effect.gen(function* () { + const rows = yield* sql` + SELECT * FROM j5_crew_seat_context WHERE thread_id = ${command.threadId} + `; + const context = rows[0]; + if (context === undefined) return yield* inner.dispatch(command); + // A dispatch may have committed before the process stopped, leaving only this bookkeeping owed. + let deliveredRoster = context.delivered_roster; + if (context.pending_command_id !== null) { + const receipt = yield* receipts.getByCommandId( + CommandId.make(context.pending_command_id), + ); + if (Option.isSome(receipt) && receipt.value.status === "accepted") { + deliveredRoster = context.pending_roster; + yield* acknowledge( + command.threadId, + deliveredRoster, + context.pending_message_id, + context.pending_prefix ?? "", + ); + if (context.delivered_roster === null) yield* changes.notify("crew", "fleet"); + } + } + const replay = yield* receipts.getByCommandId(command.commandId); + if (Option.isSome(replay)) return yield* inner.dispatch(command); + const membership = yield* crews.findMembership(participantIdForThread(command.threadId)); + if (membership === null) return yield* inner.dispatch(command); + const crew = yield* crews.read(membership.crewInstanceId); + if (crew === null) return yield* inner.dispatch(command); + const roster = crew.members.map((member) => ({ + seat: member.seatName, + participantId: member.participantId, + agentDisplayName: member.agentId ?? "custom", + reason: member.reason, + })); + const rosterJson = encodeRoster(roster); + let prefix = ""; + if (deliveredRoster === null) { + prefix = context.first_turn_text.replace( + /[\s\S]*?<\/j5_crew_context>/, + () => + crewContextText({ + displayName: crew.displayName, + instanceId: crew.id, + seatName: membership.seatName, + captainParticipantId: crew.captainParticipantId, + roster, + }), + ); + } else { + const previous = yield* decodeRoster(deliveredRoster); + const joined = roster.filter( + (member) => !previous.some((old) => old.participantId === member.participantId), + ); + const left = previous.filter( + (member) => !roster.some((current) => current.participantId === member.participantId), + ); + const describe = (member: (typeof Roster.Type)[number]) => + `${line(member.seat)}: participant_id=${member.participantId} responsibility=${line(member.reason ?? "")}`; + if (joined.length > 0 || left.length > 0) + prefix = [ + "", + ...joined.map((member) => `joined: ${describe(member)}`), + ...left.map((member) => `left: ${describe(member)}`), + "", + ].join("\n"); + } + const workspace = yield* decodeWorkspace(context.workspace); + if (deliveredRoster !== null && workspace.type === "worktree") { + const shell = yield* inner.getThreadShell(command.threadId); + if (shell !== null && shell.worktreePath === null) { + const projection = yield* inner.getThreadRecords(command.threadId, ["runs"]); + if (!projection.runs.some((run) => run.status === "preparing")) { + return yield* new CrewSeatWorkspaceNotReadyError({ + threadId: command.threadId, + commandId: command.commandId, + commandType: command.type, + }); + } + } + } + if (deliveredRoster === rosterJson) return yield* inner.dispatch(command); + prefix = crewDeliveryContextPrefix(prefix); + const prepared: OrchestrationV2ServerCommand = { + ...command, + text: prefix === "" ? command.text : `${prefix}${command.text}`, + ...(deliveredRoster === null && workspace.type === "worktree" + ? { dispatchMode: { type: "defer_start" as const, workspaceStrategy: workspace } } + : {}), + }; + yield* sql` + UPDATE j5_crew_seat_context SET pending_command_id = ${command.commandId}, + pending_roster = ${rosterJson}, pending_message_id = ${command.messageId}, + pending_prefix = ${prefix} WHERE thread_id = ${command.threadId} + `; + // Acceptance owns this context even if provider startup fails; retries keep the stored message. + const result = yield* inner.dispatch(prepared); + yield* acknowledge(command.threadId, rosterJson, command.messageId, prefix); + if (deliveredRoster === null) yield* changes.notify("crew", "fleet"); + return result; + }).pipe( + Effect.mapError((cause) => + isOrchestratorError(cause) || isWorkspaceNotReady(cause) + ? cause + : new Orchestrator.OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause, + }), + ), + ), + ); + }; + return Orchestrator.OrchestratorV2.of({ ...inner, dispatch }); + }), +).pipe(Layer.provide(Crews.layer), Layer.provide(ReadChanges.layer)); diff --git a/apps/server/src/j5/a2a/CrewLaunchReporter.test.ts b/apps/server/src/j5/a2a/CrewLaunchReporter.test.ts index fc7de8decaf89..15da5bbb47bf6 100644 --- a/apps/server/src/j5/a2a/CrewLaunchReporter.test.ts +++ b/apps/server/src/j5/a2a/CrewLaunchReporter.test.ts @@ -940,3 +940,28 @@ it.effect( }).pipe(Effect.provide(layer)); }).pipe(Effect.scoped), ); + +it.effect("reports created seats waiting for work immediately, including after a restart", () => + Effect.gen(function* () { + const f = yield* fixture; + const id = "proposal:waiting"; + const roster = [seat("builder", "scout"), seat("reviewer", "critic")]; + yield* f.approvedLaunch({ id, requested: roster, approved: roster }); + yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + for (const entry of roster) + yield* sql` + INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace) + VALUES (${crewSeatThreadId(id, entry.seat)}, 'approved context', '{"type":"shared"}') + `; + yield* (yield* CrewLaunchReporter).reconcile; + const reports = yield* f.reports(); + assert.lengthOf(reports, 1); + assert.include(reports[0]!, "2 created and waiting for work"); + assert.include(reports[0]!, "start=waiting"); + assert.notInclude(reports[0]!, "seat_pending:"); + assert.notInclude(reports[0]!, "unconfirmed"); + assert.notInclude(reports[0]!, "Your crew is running."); + }).pipe(Effect.provide(f.layer)); + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/j5/a2a/CrewLaunchReporter.ts b/apps/server/src/j5/a2a/CrewLaunchReporter.ts index e17d792ef1c41..ccd3975eca34d 100644 --- a/apps/server/src/j5/a2a/CrewLaunchReporter.ts +++ b/apps/server/src/j5/a2a/CrewLaunchReporter.ts @@ -45,10 +45,9 @@ import { getThreadProjectionIfPresent } from "./threadProjectionReads.ts"; export const CREW_LAUNCH_REPORT_WINDOW_MS = 60_000; /** - * The launch report: the one notice a Captain gets for an approval, posted when every seat this - * proposal launched has produced provider activity or ended, or the window closed. Dispatching a brief commits intent only; before this, "your crew is running" was - * said the moment the briefs were dispatched, and two seats that died on a signed-out provider - * arrived later as finishes with no reason (Jackson's dogfood, 2026-09-17). + * The one notice a Captain gets for an approval. Waiting seats are reported immediately from + * their creation facts. An owed report from before deferred activation still measures its + * dispatched briefs against provider activity, completion, or the confirmation window. */ export interface CrewLaunchReporterShape { /** @@ -251,14 +250,21 @@ const makeLayer = (daemon: boolean) => return; } const projection = yield* getThreadProjectionIfPresent(threads, seat.threadId); + const member = launch.instance.members.find( + (candidate) => candidate.threadId === seat.threadId, + ); launch.verdicts.set( seat.seatName, projection === null ? { kind: "not_created", detail: NOT_CREATED_DETAIL } - : verdictFor( - projection.runs.find((candidate) => isFirstTurnRun(seat, candidate)), - projection, - ), + : member?.notStarted === true + ? { kind: "waiting" } + : verdictFor( + member?.notStarted === false + ? projection.runs.toSorted((a, b) => a.ordinal - b.ordinal)[0] + : projection.runs.find((candidate) => isFirstTurnRun(seat, candidate)), + projection, + ), ); }); diff --git a/apps/server/src/j5/a2a/CrewLaunchService.test.ts b/apps/server/src/j5/a2a/CrewLaunchService.test.ts index eef5d11725a84..9b84cbfc1eb2e 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.test.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.test.ts @@ -1,3 +1,4 @@ +import * as SqlClient from "effect/sql/SqlClient"; import { assert, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { @@ -63,6 +64,13 @@ import type { ThreadLaunchInput } from "../../orchestration-v2/ThreadLaunchServi import type { SpawnWorkspaceChoice } from "./spawnWorkspace.ts"; import { ParticipantId, LedgerProjectId } from "./contracts.ts"; +const savedBriefs = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + return yield* sql<{ readonly thread_id: string; readonly first_turn_text: string }>` + SELECT thread_id, first_turn_text FROM j5_crew_seat_context ORDER BY rowid + `; +}); + const projectId = LedgerProjectId.make("ledger:crew-launch"); const captainThread = ThreadId.make("thread:captain"); const captainId = ParticipantId.make("agent:captain"); @@ -264,7 +272,7 @@ const dependencies = ( Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed(providers) }), ); -it.effect("launches an approved roster whole, records it, briefs each seat, then adds a seat", () => +it.effect("creates approved seats and additions without starting turns", () => Effect.gen(function* () { const { context, commands, captain } = yield* fixture; const codex = provider("codex", "codex", [ @@ -355,9 +363,13 @@ it.effect("launches an approved roster whole, records it, briefs each seat, then const captured = yield* Ref.get(commands); assert.deepStrictEqual( captured.map((command) => command.type), - ["thread.create", "thread.create", "message.dispatch", "message.dispatch"], + ["thread.create", "thread.create"], ); - const builderBrief = captured[2]; + const builderBrief = { + type: "message.dispatch", + text: (yield* savedBriefs)[0]!.first_turn_text, + }; + assert.isTrue(instance.members.every((member) => member.notStarted)); if (builderBrief?.type === "message.dispatch") { assert.include(builderBrief.text, "your_seat: builder"); assert.include(builderBrief.text, `captain_participant_id: ${captainId}`); @@ -390,7 +402,13 @@ it.effect("launches an approved roster whole, records it, briefs each seat, then ["sentry", 2], ], ); - const sentryBrief = (yield* Ref.get(commands)).at(-1); + assert.isTrue( + (yield* Ref.get(commands)).every((command) => command.type !== "message.dispatch"), + ); + const sentryBrief = { + type: "message.dispatch", + text: (yield* savedBriefs).at(-1)!.first_turn_text, + }; if (sentryBrief?.type === "message.dispatch") { assert.include(sentryBrief.text, "your_seat: sentry"); assert.include(sentryBrief.text, "- builder: participant_id="); @@ -468,16 +486,13 @@ it.effect( assert.deepStrictEqual(created.modelSelection, captain.thread.modelSelection); assert.equal(created.runtimeMode, "full-access"); } - const brief = captured.find( - (command) => - command.type === "message.dispatch" && command.text.includes("your_seat: scribe"), - ); - assert.equal(brief?.type, "message.dispatch"); - if (brief?.type === "message.dispatch") { - assert.include(brief.text, "\nWrite the running notes."); - assert.notInclude(brief.text, ""); - assert.include(brief.text, "persona=custom"); - } + assert.isFalse(captured.some((command) => command.type === "message.dispatch")); + const brief = (yield* savedBriefs).find((row) => + row.first_turn_text.includes("your_seat: scribe"), + )!.first_turn_text; + assert.include(brief, "\nWrite the running notes."); + assert.notInclude(brief, ""); + assert.include(brief, "persona=custom"); // A persona Captain runs under its persona's policy (workspace write, auto-accept-edits here) // and has the person supervising it; its custom seat still defaults to Full access. @@ -1546,18 +1561,10 @@ it.effect( (yield* crews.read(launched.instance.id))!.members.map((member) => member.seatName), ["builder", "sentry"], ); - // Only the seats that exist got a brief, and their roster names only each other. - const briefs = (yield* Ref.get(unit.commands)).flatMap((command) => - command.type === "message.dispatch" ? [command] : [], - ); - assert.sameMembers( - briefs.map((command) => command.threadId), - [unit.seatThread("trio", "builder"), unit.seatThread("trio", "sentry")], + assert.isFalse( + (yield* Ref.get(unit.commands)).some((command) => command.type === "message.dispatch"), ); - for (const brief of briefs) { - assert.include(brief.text, "- builder"); - assert.notInclude(brief.text, "- critic"); - } + assert.isTrue(launched.instance.members.every((member) => member.notStarted)); }).pipe(Effect.provide(unit.layer)); }).pipe(Effect.scoped), ); @@ -1858,8 +1865,9 @@ it.effect("records a playbook Crew's step owners and surfaces a taken step unwra ["helper", []], ], ); - const briefs = (yield* Ref.get(commands)).flatMap((command) => - command.type === "message.dispatch" ? [command.text] : [], + const briefs = (yield* savedBriefs).map((row) => row.first_turn_text); + assert.isFalse( + (yield* Ref.get(commands)).some((command) => command.type === "message.dispatch"), ); assert.include(briefs[0], "your_steps:\n- plan: Plan the release\n"); assert.include(briefs[1], "your_steps: none\n"); @@ -2083,21 +2091,13 @@ it.effect("launches each seat in the workspace it names, and refuses one git can assert.equal(scribe.worktreePath, captain.thread.worktreePath); assert.equal(scribe.branch, captain.thread.branch); } - // Only the new worktree waits on ThreadLaunch; the other two briefs start at once. - const briefs = captured.filter((command) => command.type === "message.dispatch"); - assert.sameMembers( - briefs.map((command) => command.threadId), - [threadOf("reviewer"), threadOf("scribe")], - ); - const [launch] = yield* Ref.get(launches); - assert.equal(launch?.threadId, threadOf("builder")); - assert.isTrue(launch?.reuseExistingThread); - assert.deepStrictEqual(launch?.workspaceStrategy, { - type: "worktree", - baseRef: "j5/main", - startFromOrigin: false, - }); - assert.include(launch?.initialMessage?.text, "your_seat: builder"); + assert.isFalse(captured.some((command) => command.type === "message.dispatch")); + assert.deepStrictEqual(yield* Ref.get(launches), []); + const sql = yield* SqlClient.SqlClient; + const contexts = yield* sql<{ readonly workspace: string }>` + SELECT workspace FROM j5_crew_seat_context WHERE thread_id = ${threadOf("builder")} + `; + assert.include(contexts[0]!.workspace, '"baseRef":"j5/main"'); }).pipe(Effect.provide(layerFor(repo))); }), ); diff --git a/apps/server/src/j5/a2a/CrewLaunchService.ts b/apps/server/src/j5/a2a/CrewLaunchService.ts index afe556f22fbf8..ed9c9c3276031 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.ts @@ -1,3 +1,4 @@ +import { CrewSeatWorkspace } from "@t3tools/contracts/j5"; import { describeCrewSeatRuntime, materializeCrewModelSelection, @@ -15,6 +16,8 @@ import * as Context from "effect/Context"; import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; import * as Layer from "effect/Layer"; import * as Result from "effect/Result"; @@ -56,7 +59,6 @@ import { spawnCrewInstanceId, spawnFirstTurnText, spawnHomeCommandId, - spawnMessageId, spawnPlacementCommandId, spawnThreadId, spawnTitle, @@ -159,9 +161,9 @@ export interface CrewAddSeatsInput { } /** - * How one approved seat's launch went: `created` when its thread, home, and brief all went out; + * How one approved seat's launch went: `created` when its thread and home exist and it is waiting for work; * `not_created` when its thread was never created, so its row is dropped and nothing can message - * it; `not_started` when the thread exists but its home or its brief did not go through. + * it; `not_started` when the thread exists but its home or placement did not go through. */ export type CrewSeatLaunchOutcome = | { readonly seatName: string; readonly kind: "created" } @@ -620,8 +622,8 @@ 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, so its in-flight refusal is not expected here; the brief takes the guard - // again once every seat exists. + // serialized, so its in-flight refusal is not expected here. Their first assignments arrive + // separately. const started = yield* Effect.result( spawnWorkspace.withSpawnStart( { @@ -641,8 +643,9 @@ export const layer = Layer.effect( return { outcomes, created }; }); - /** Brief every created seat, carrying on past one whose brief did not go out. */ - const startBriefs = Effect.fn("j5.a2a.crewLaunch.startBriefs")(function* ( + const sql = yield* SqlClient.SqlClient; + const encodeWorkspace = Schema.encodeEffect(Schema.fromJsonString(CrewSeatWorkspace)); + const prepareBriefs = Effect.fn("j5.a2a.crewLaunch.prepareBriefs")(function* ( captain: CrewCaptain, instance: AgentCrewInstance, planned: ReadonlyArray, @@ -652,12 +655,12 @@ export const layer = Layer.effect( const roster = instance.members.map((member) => ({ seat: member.seatName, participantId: member.participantId, + reason: member.reason, agentDisplayName: planned.find((entry) => entry.seat.name === member.seatName)?.agentDisplayName ?? member.agentId ?? "custom", })); - const failed = new Map(); for (const member of planned) { const text = spawnFirstTurnText({ brief, @@ -694,38 +697,17 @@ export const layer = Layer.effect( }, }, }); - const dispatched = yield* Effect.result( - spawnWorkspace.withSpawnStart( - { - stableInput: member.stableInput, - threadId: member.threadId, - }, - spawnWorkspace.startBrief({ - workspace: member.workspace, - stableInput: member.stableInput, - ledgerProjectId: captain.projectId, - projectId: captain.thread.projectId, - threadId: member.threadId, - title: spawnTitle(member.seat.name), - messageId: spawnMessageId(member.stableInput), - text, - modelSelection: member.modelSelection, - runtimeMode: member.runtimeMode, - interactionMode: captain.thread.interactionMode, - }), - ), - ); - if (Result.isFailure(dispatched)) - failed.set( - member.seat.name, - `starting its brief failed: ${detailOf(dispatched.failure)}`, - ); + const workspaceJson = yield* encodeWorkspace(member.workspace); + yield* sql` + INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace) + VALUES (${member.threadId}, ${text}, ${workspaceJson}) + ON CONFLICT (thread_id) DO NOTHING + `; } - return failed; }); /** - * Spawn and brief the reserved seats, then drop the rows of seats that were never created. + * Create the reserved seats with their approved context, then drop seats that were never created. * Every seat is attempted; the outcomes say what became of each. */ const spawnAndBrief = Effect.fn("j5.a2a.crewLaunch.spawnAndBrief")(function* ( @@ -736,6 +718,17 @@ export const layer = Layer.effect( playbook: CrewLaunchPlaybook | null, addition: boolean, ) { + yield* prepareBriefs(captain, instance, planned, brief, playbook).pipe( + Effect.mapError( + (cause) => + new CrewLaunchOperationError({ + phase: "prepare seat context", + seatName: null, + createdSeats: [], + cause, + }), + ), + ); const spawned = yield* spawnSeats(captain, planned); const notCreated = spawned.outcomes.flatMap((outcome) => outcome.kind === "not_created" ? [outcome.seatName] : [], @@ -752,17 +745,7 @@ export const layer = Layer.effect( }), ), ); - const current = (yield* crews.read(instance.id).pipe(Effect.orElseSucceed(() => null))) ?? { - ...instance, - members: instance.members.filter((member) => !notCreated.includes(member.seatName)), - }; - const briefFailures = yield* startBriefs(captain, current, spawned.created, brief, playbook); - const seats = spawned.outcomes.map((outcome): CrewSeatLaunchOutcome => { - const briefFailure = briefFailures.get(outcome.seatName); - return outcome.kind === "created" && briefFailure !== undefined - ? { seatName: outcome.seatName, kind: "not_started", detail: briefFailure } - : outcome; - }); + const seats = spawned.outcomes; const outcomes = (kind: CrewSeatLaunchOutcome["kind"]) => seats.filter((seat) => seat.kind === kind).length; yield* recordAnalytics("j5.crew.launched", { @@ -777,7 +760,13 @@ export const layer = Layer.effect( notCreated: outcomes("not_created"), notStarted: outcomes("not_started"), }); - return { instance: current, seats } satisfies CrewLaunchResult; + return { + instance: (yield* crews.read(instance.id).pipe(Effect.orElseSucceed(() => null))) ?? { + ...instance, + members: instance.members.filter((member) => !notCreated.includes(member.seatName)), + }, + seats, + } satisfies CrewLaunchResult; }); const launch: CrewLaunchServiceShape["launch"] = (input) => @@ -841,7 +830,7 @@ export const layer = Layer.effect( false, ); }).pipe((launch) => - // One unit step from the record through the briefs, so a unit archive waits for every + // One unit step from the record through creation, so a unit archive waits for every // seat to exist before it reads the roster. crews.serialize( spawnCrewInstanceId({ diff --git a/apps/server/src/j5/a2a/CrewProposalService.test.ts b/apps/server/src/j5/a2a/CrewProposalService.test.ts index df5fb2db3d6d1..42d17cd0cf7e5 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.test.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.test.ts @@ -21,6 +21,7 @@ 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 * as SqlClient from "effect/sql/SqlClient"; import { SqlError, UnknownError } from "effect/sql/SqlError"; import { stringify } from "yaml"; @@ -1830,7 +1831,7 @@ const proposeRelease = ( }); it.effect( - "records a playbook Crew on its proposal, instance, and members, and briefs each seat", + "records a playbook Crew on its proposal, instance, and members, and saves each seat introduction", () => Effect.gen(function* () { const { layer, workspaceRoot, commands } = yield* playbookFixture; @@ -1884,11 +1885,20 @@ it.effect( ["builder", ["build"]], ], ); - const brief = (yield* Ref.get(commands)).find( - (command) => command.type === "message.dispatch", + const sql = yield* SqlClient.SqlClient; + const plannerThread = instance.members.find( + ({ seatName }) => seatName === "planner", + )!.threadId; + const [brief] = yield* sql<{ first_turn_text: string }>` + SELECT first_turn_text FROM j5_crew_seat_context WHERE thread_id = ${plannerThread} + `; + assert.isFalse( + (yield* Ref.get(commands)).some( + (command) => command.type === "message.dispatch" && command.threadId === plannerThread, + ), ); assert.include( - brief?.type === "message.dispatch" ? brief.text : "", + brief!.first_turn_text, "\nplaybook: release (Release)\nyour_steps:\n- plan: Plan\n", ); }).pipe(Effect.provide(layer)); @@ -2208,11 +2218,18 @@ it.effect("a Crew whose playbook file is gone still takes a seat that claims no ["helper", []], ], ); - const brief = (yield* Ref.get(commands)).findLast( - (command) => command.type === "message.dispatch", + const sql = yield* SqlClient.SqlClient; + const helperThread = members.find(({ seatName }) => seatName === "helper")!.threadId; + const [brief] = yield* sql<{ first_turn_text: string }>` + SELECT first_turn_text FROM j5_crew_seat_context WHERE thread_id = ${helperThread} + `; + assert.isFalse( + (yield* Ref.get(commands)).some( + (command) => command.type === "message.dispatch" && command.threadId === helperThread, + ), ); assert.include( - brief?.type === "message.dispatch" ? brief.text : "", + brief!.first_turn_text, "\nplaybook: release (release)\nyour_steps: none\n", ); }).pipe(Effect.provide(layer)); @@ -2431,11 +2448,17 @@ it.effect( const builderThread = instance.members.find( ({ seatName }) => seatName === "builder", )!.threadId; - const builderBrief = (yield* Ref.get(commands)).find( - (command) => command.type === "message.dispatch" && command.threadId === builderThread, + const sql = yield* SqlClient.SqlClient; + const [builderBrief] = yield* sql<{ first_turn_text: string }>` + SELECT first_turn_text FROM j5_crew_seat_context WHERE thread_id = ${builderThread} + `; + assert.isFalse( + (yield* Ref.get(commands)).some( + (command) => command.type === "message.dispatch" && command.threadId === builderThread, + ), ); assert.include( - builderBrief?.type === "message.dispatch" ? builderBrief.text : "", + builderBrief!.first_turn_text, "your_steps:\n- build: Build\n- release: Release\n", ); diff --git a/apps/server/src/j5/a2a/CrewSeatPreparation.ts b/apps/server/src/j5/a2a/CrewSeatPreparation.ts new file mode 100644 index 0000000000000..ff481cf75224a --- /dev/null +++ b/apps/server/src/j5/a2a/CrewSeatPreparation.ts @@ -0,0 +1,50 @@ +import { CommandId, RunId, ThreadId, type OrchestrationV2Run } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; +import { ThreadLaunchService } from "../../orchestration-v2/ThreadLaunchService.ts"; +import { readEventStoreHighWater } from "./eventStoreHighWater.ts"; + +/** A waiting seat's first assignment uses upstream's durable worktree preparation path. */ +export const layer = Layer.effectDiscard( + Effect.gen(function* () { + const threads = yield* ThreadManagementService; + const launcher = yield* ThreadLaunchService; + const sql = yield* SqlClient.SqlClient; + const prepare = (run: OrchestrationV2Run) => + run.status !== "preparing" + ? Effect.void + : Effect.gen(function* () { + const rows = + yield* sql`SELECT thread_id FROM j5_crew_seat_context WHERE thread_id = ${run.threadId}`; + if (rows.length === 0) return; + yield* launcher.prepareRun({ + threadId: run.threadId, + runId: run.id, + commandId: CommandId.make(`command:j5:crew-seat-prepare:${run.id}`), + }); + }); + const afterSequence = yield* readEventStoreHighWater("J5 crew seat preparation"); + const rows = yield* sql<{ readonly thread_id: string; readonly run_id: string }>` + SELECT run.thread_id, run.run_id FROM orchestration_v2_projection_runs AS run + JOIN j5_crew_seat_context AS context ON context.thread_id = run.thread_id + WHERE run.status = 'preparing' + `; + for (const row of rows) { + const projection = yield* threads.getThreadRecords(ThreadId.make(row.thread_id), ["runs"], { + runIds: [RunId.make(row.run_id)], + }); + for (const run of projection.runs) yield* prepare(run); + } + yield* threads.streamStoredEventsFrom({ afterSequence }).pipe( + Stream.runForEach((stored) => + stored.event.type === "run.created" ? prepare(stored.event.payload) : Effect.void, + ), + Effect.tapError((cause) => Effect.logError("J5 crew seat preparation failed", { cause })), + Effect.forkScoped, + ); + }), +); diff --git a/apps/server/src/j5/a2a/Migrations.test.ts b/apps/server/src/j5/a2a/Migrations.test.ts index e157b67721afb..10d14adc98763 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -140,6 +140,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () { migration_id: 46, name: "LocalDeliveryOrder" }, { migration_id: 47, name: "RequestReplay" }, { migration_id: 48, name: "CrewApprovalMode" }, + { migration_id: 49, name: "CrewSeatActivation" }, ]); assert.deepStrictEqual( migrationEntries.map(([id, name]) => [id, name]), @@ -192,6 +193,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () [46, "LocalDeliveryOrder"], [47, "RequestReplay"], [48, "CrewApprovalMode"], + [49, "CrewSeatActivation"], ], ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), diff --git a/apps/server/src/j5/a2a/Migrations.ts b/apps/server/src/j5/a2a/Migrations.ts index cad75964dbc95..aa49915559adf 100644 --- a/apps/server/src/j5/a2a/Migrations.ts +++ b/apps/server/src/j5/a2a/Migrations.ts @@ -49,6 +49,7 @@ import Migration0045 from "./migrations/045_McpClientApprovers.ts"; import Migration0046 from "./migrations/046_LocalDeliveryOrder.ts"; import Migration0047 from "./migrations/047_RequestReplay.ts"; import Migration0048 from "./migrations/048_CrewApprovalMode.ts"; +import Migration0049 from "./migrations/049_CrewSeatActivation.ts"; export const J5_A2A_MIGRATIONS_TABLE = "j5_a2a_migrations"; @@ -108,6 +109,7 @@ export const migrationEntries = [ [46, "LocalDeliveryOrder", Migration0046], [47, "RequestReplay", Migration0047], [48, "CrewApprovalMode", Migration0048], + [49, "CrewSeatActivation", Migration0049], ] as const; const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/j5/a2a/crewGateNotice.ts b/apps/server/src/j5/a2a/crewGateNotice.ts index b51551f44df48..9f03224f1e94d 100644 --- a/apps/server/src/j5/a2a/crewGateNotice.ts +++ b/apps/server/src/j5/a2a/crewGateNotice.ts @@ -13,6 +13,7 @@ import { formatRunFailureField } from "./runFailures.ts"; * created, which is not on the roster and cannot be messaged. */ export type SeatStartVerdict = + | { readonly kind: "waiting" } | { readonly kind: "started" } | { readonly kind: "failed"; @@ -148,7 +149,12 @@ export const crewLaunchReportText = (input: { ); const pending = [...verdicts].filter(([, verdict]) => verdict.kind === "pending"); const windowSeconds = Math.round(input.windowMs / 1000); - const launch = `launch: ${started} started, ${failed.length} failed, ${notCreated.length} not created, ${pending.length} start unconfirmed after ${windowSeconds}s`; + const waiting = [...verdicts].filter(([, verdict]) => verdict.kind === "waiting").length; + const launchCounts = `launch: ${waiting > 0 ? `${waiting} created and waiting for work, ` : ""}${started} started, ${failed.length} failed, ${notCreated.length} not created, ${pending.length} start unconfirmed after ${windowSeconds}s`; + const launch = + waiting > 0 && pending.length === 0 + ? `launch: ${waiting} created and waiting for work, ${started} started, ${failed.length} failed, ${notCreated.length} not created` + : launchCounts; const failedLines = failed.map(([seat, verdict]) => verdict.kind === "not_started" ? `seat_failed: ${seat} | not_started | ${reportField(verdict.detail)}` @@ -200,7 +206,11 @@ export const crewLaunchReportText = (input: { prose.push( `${pending.length} ${pending.length === 1 ? "seat has" : "seats have"} no confirmed provider activity after ${windowSeconds}s; its first turn may still be queued, and you will hear from it when it finishes.`, ); - if (failed.length === 0 && notCreated.length === 0 && pending.length === 0) + if (waiting > 0) + prose.push( + "Send each member its first assignment with j5_send_message when it has work; the first delivery includes the shared brief and current roster. Reuse finished members for follow-up work in the same thread.", + ); + if (waiting === 0 && failed.length === 0 && notCreated.length === 0 && pending.length === 0) prose.push( "Your crew is running. Each seat has your brief and this roster; coordinate with j5_send_message, and ask the user through the inbox for decisions you cannot make from the brief.", ); diff --git a/apps/server/src/j5/a2a/crewMembershipsRead.ts b/apps/server/src/j5/a2a/crewMembershipsRead.ts index 4b70dc5789547..3fd839518d7e1 100644 --- a/apps/server/src/j5/a2a/crewMembershipsRead.ts +++ b/apps/server/src/j5/a2a/crewMembershipsRead.ts @@ -34,7 +34,12 @@ export const projectCrewMemberships = ( ? instance.members.find((candidate) => candidate.threadId === threadId) : undefined; if (seat !== undefined) - member = { kind: "member", seat: seat.seatName, crew: crewRef(instance) }; + member = { + kind: "member", + seat: seat.seatName, + crew: crewRef(instance), + ...(seat.notStarted === undefined ? {} : { notStarted: seat.notStarted }), + }; if (instance.archivedAt === null && instance.captainParticipantId === participantId) commanded.push(crewRef(instance)); } diff --git a/apps/server/src/j5/a2a/fleetRead.ts b/apps/server/src/j5/a2a/fleetRead.ts index f372f71167a9b..e3fa1ea649f47 100644 --- a/apps/server/src/j5/a2a/fleetRead.ts +++ b/apps/server/src/j5/a2a/fleetRead.ts @@ -40,6 +40,7 @@ export const projectFleetProject = (input: { crewInstanceId: crew.id, crewName: crew.displayName, seat: member.seatName, + ...(member.notStarted === undefined ? {} : { notStarted: member.notStarted }), captainParticipantId: crew.captainParticipantId, }); } @@ -132,6 +133,7 @@ export const projectFleetProject = (input: { const steps = member.playbookStepIds ?? []; return { seat: member.seatName, + ...(member.notStarted === undefined ? {} : { notStarted: member.notStarted }), agentId: member.agentId, participantId: member.participantId, addedVersion: member.addedVersion, diff --git a/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index d809a58a4aab7..dae1e4d5bece1 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -561,10 +561,10 @@ 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. By default the user reviews and edits the roster in this thread, then approves or declines. If Auto-approve new Crews is on for your project, the proposed roster launches immediately with no approval card. The result says whether it is open or approved; the launch report arrives here once startup is confirmed or fails. Each seat keeps its configured access and tool approvals, 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 tool 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. By default the user reviews and edits the roster in this thread, then approves or declines. If Auto-approve new Crews is on for your project, the proposed roster is created immediately with no approval card. The result says whether it is open or approved; the launch report arrives here once creation finishes or fails. Approval creates seats without starting turns. Send each member its first assignment when it has work; reuse finished members for follow-up work in the same thread. Each seat keeps its configured access and tool approvals, 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 tool 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 = - "Add one seat directly to a running crew you command when the work needs expertise the roster lacks. No human approval is needed, regardless of Auto-approve new Crews. Give a seat name, a persona id from j5_list_personas or required instructions for a custom seat, a reason identifying the missing expertise, and its workspace (the same choices as j5_propose_crew). Custom seats inherit your model selection and run with full-access unless you set model_selection or runtime_mode; saved personas use their own configuration. Optionally give a brief; otherwise the seat gets the Crew's brief. On a playbook Crew, steps may claim only unowned step ids from j5_playbook_read. The result returns the updated roster or refuses the seat with its name and reason; startup is reported separately here. Each member's configured access still controls tool approvals. Captain-only: a member sends the concern 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. Works under every approval policy, including approval policy never."; + "Add one seat directly to a running crew you command when the work needs expertise the roster lacks. No human approval is needed, regardless of Auto-approve new Crews. Give a seat name, a persona id from j5_list_personas or required instructions for a custom seat, a reason identifying the missing expertise, and its workspace (the same choices as j5_propose_crew). Custom seats inherit your model selection and run with full-access unless you set model_selection or runtime_mode; saved personas use their own configuration. Optionally give a brief; otherwise the seat gets the Crew's brief. On a playbook Crew, steps may claim only unowned step ids from j5_playbook_read. The result returns the updated roster or refuses the seat with its name and reason; creation is reported separately here. The new member waits for its first assignment; send it with j5_send_message when the work is ready. Each member's configured access still controls tool approvals. Captain-only: a member sends the concern 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. 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."; diff --git a/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts new file mode 100644 index 0000000000000..1e834bfb5b883 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts @@ -0,0 +1,52 @@ +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Schema from "effect/Schema"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import { runJ5A2AMigrations } from "../Migrations.ts"; + +const decodeRoster = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Array(Schema.Struct({ seat: Schema.String, reason: Schema.String })), + ), +); + +it.effect( + "existing members retain their observed roster and are not introduced again after migration", + () => + Effect.gen(function* () { + yield* runJ5A2AMigrations({ toMigrationInclusive: 47 }); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO j5_a2a_project_ledger (project_id, created_at) VALUES ('project:test', '2026-10-27')`; + yield* sql`INSERT INTO j5_agent_crew_instance + (id, project_id, captain_participant_id, captain_thread_id, display_name, brief, version, created_at) + VALUES ('crew:test', 'project:test', 'agent:captain', 'thread:captain', 'Crew', 'Brief', 1, '2026-10-27')`; + for (const [ordinal, name] of ["builder", "reviewer"].entries()) + yield* sql` + INSERT INTO j5_agent_crew_member + (crew_instance_id, seat_name, agent_id, participant_id, thread_id, ordinal, added_version, reason) + VALUES ('crew:test', ${name}, NULL, ${`agent:${name}`}, ${`thread:${name}`}, ${ordinal}, 1, ${`Responsibility of ${name}`}) + `; + yield* runJ5A2AMigrations(); + yield* runJ5A2AMigrations(); + const contexts = yield* sql<{ + readonly delivered_roster: string; + readonly first_turn_text: string; + }>` + SELECT delivered_roster, first_turn_text FROM j5_crew_seat_context + `; + assert.lengthOf(contexts, 2); + for (const row of contexts) { + assert.equal(row.first_turn_text, ""); + const roster = yield* decodeRoster(row.delivered_roster); + assert.sameMembers( + roster.map((member) => member.seat), + ["builder", "reviewer"], + ); + assert.include( + roster.map((member) => member.reason), + "Responsibility of builder", + ); + } + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); diff --git a/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.ts b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.ts new file mode 100644 index 0000000000000..b71390015c865 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.ts @@ -0,0 +1,27 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql` + CREATE TABLE j5_crew_seat_context ( + thread_id TEXT PRIMARY KEY, + first_turn_text TEXT NOT NULL, + workspace TEXT NOT NULL, + delivered_roster TEXT, + pending_command_id TEXT, + pending_message_id TEXT, + pending_prefix TEXT, + pending_roster TEXT + ) + `; + yield* sql` + INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace, delivered_roster) + SELECT member.thread_id, '', '{"type":"shared"}', ( + SELECT json_group_array(json_object( + 'seat', roster.seat_name, 'participantId', roster.participant_id, + 'agentDisplayName', coalesce(roster.agent_id, 'custom'), 'reason', roster.reason + )) FROM j5_agent_crew_member AS roster WHERE roster.crew_instance_id = member.crew_instance_id + ) FROM j5_agent_crew_member AS member + `; +}); diff --git a/apps/server/src/j5/a2a/runtimeLayer.ts b/apps/server/src/j5/a2a/runtimeLayer.ts index 4b126b62c27dc..0802e26fb238f 100644 --- a/apps/server/src/j5/a2a/runtimeLayer.ts +++ b/apps/server/src/j5/a2a/runtimeLayer.ts @@ -1,3 +1,4 @@ +import * as CrewSeatPreparation from "./CrewSeatPreparation.ts"; import * as SpawnAgentService from "./SpawnAgentService.ts"; import * as Layer from "effect/Layer"; import { layerEventSink as OrchestrationV2EventSinkLayerLive } from "../../orchestration-v2/runtimeLayer.ts"; @@ -211,6 +212,7 @@ export const makeJ5A2AAuxiliaryLayer = ( Layer.provide(artifactWorkspaceLayer), ); const runtimeWithoutClientReads = Layer.mergeAll( + CrewSeatPreparation.layer, playbookStoreLayer, playbookCrewRelayProvided, agentHandoffNudgeWorkerProvided, diff --git a/apps/server/src/j5/a2a/spawnIds.ts b/apps/server/src/j5/a2a/spawnIds.ts index 9f69e3a2f1872..152150f27b858 100644 --- a/apps/server/src/j5/a2a/spawnIds.ts +++ b/apps/server/src/j5/a2a/spawnIds.ts @@ -76,6 +76,7 @@ export interface CrewBriefContext { readonly seat: string; readonly participantId: string; readonly agentDisplayName: string; + readonly reason?: string | null; }>; /** The playbook the Crew follows and the steps this seat owns, with live titles. */ readonly playbook?: @@ -90,6 +91,17 @@ export interface CrewBriefContext { /** A title on one line that cannot close the block it is written into. */ const briefLine = (text: string) => text.replace(/\s+/g, " ").trim().replace(/<\//g, "<\\/"); +export const crewContextText = (crew: CrewBriefContext) => { + // Roster and identity are measured platform facts; wiring text is the user's content, verbatim. + const roster = crew.roster + .map( + (member) => + `- ${member.seat}${member.seat === crew.seatName ? " (you)" : ""}: participant_id=${member.participantId} persona=${briefLine(member.agentDisplayName)} responsibility=${briefLine(member.reason ?? "")}`, + ) + .join("\n"); + return `\nPlatform-provided crew facts:\ncrew: ${crew.displayName}\ncrew_instance_id: ${crew.instanceId}\nyour_seat: ${crew.seatName}\ncaptain_participant_id: ${crew.captainParticipantId}\nroster:\n${roster}\n`; +}; + // The web timeline parses the identity block and the trailing brief // (apps/web/src/j5/a2a/SpawnBrief.tsx) to attribute the message to its spawner; // keep the two in step. @@ -114,14 +126,7 @@ export const spawnFirstTurnText = (input: { const brief = `\n${input.brief}\n`; if (input.crew === undefined) return `${identity}\n\n${brief}`; const crew = input.crew; - // Roster and identity are measured platform facts; wiring text is the user's content, verbatim. - const roster = crew.roster - .map( - (member) => - `- ${member.seat}${member.seat === crew.seatName ? " (you)" : ""}: participant_id=${member.participantId} persona=${member.agentDisplayName}`, - ) - .join("\n"); - const crewContext = `\nPlatform-provided crew facts:\ncrew: ${crew.displayName}\ncrew_instance_id: ${crew.instanceId}\nyour_seat: ${crew.seatName}\ncaptain_participant_id: ${crew.captainParticipantId}\nroster:\n${roster}\n`; + const crewContext = crewContextText(crew); const seatInstructions = crew.seatInstructions === undefined ? [] diff --git a/apps/server/src/j5/a2a/spawnedChildrenRead.ts b/apps/server/src/j5/a2a/spawnedChildrenRead.ts index d605fc6ea98b0..0063a874833ec 100644 --- a/apps/server/src/j5/a2a/spawnedChildrenRead.ts +++ b/apps/server/src/j5/a2a/spawnedChildrenRead.ts @@ -53,6 +53,7 @@ export const projectSpawnedChildren = ( crewInstanceId: crew.id, crewName: crew.displayName, seat: member.seatName, + ...(member.notStarted === undefined ? {} : { notStarted: member.notStarted }), }); } const entries: Array = []; diff --git a/apps/server/src/j5/test-support/threadLaunchHarness.ts b/apps/server/src/j5/test-support/threadLaunchHarness.ts index 5ee6449e403d8..6aeb59bed6ba6 100644 --- a/apps/server/src/j5/test-support/threadLaunchHarness.ts +++ b/apps/server/src/j5/test-support/threadLaunchHarness.ts @@ -1,3 +1,4 @@ +import * as CrewDeliveryContext from "../a2a/CrewDeliveryContext.ts"; import * as ProjectCloneTracker from "../../project/ProjectCloneTracker.ts"; import * as WorktreeSetupTracker from "../../project/WorktreeSetupTracker.ts"; import * as TerminalManager from "../../terminal/Manager.ts"; @@ -65,6 +66,7 @@ const adapter = { } as ProviderAdapter.ProviderAdapterV2["Service"]; export interface HarnessOptions { + readonly crewDeliveryContext?: boolean; readonly createWorktree?: GitWorkflow.GitWorkflowService["Service"]["createWorktree"]; readonly fetchRemote?: GitWorkflow.GitWorkflowService["Service"]["fetchRemote"]; readonly renameBranch?: GitWorkflow.GitWorkflowService["Service"]["renameBranch"]; @@ -78,12 +80,20 @@ export interface HarnessOptions { export function makeHarness(options: HarnessOptions = {}) { const database = SqlitePersistenceMemory; const registry = ProviderAdapterRegistry.layerFromAdapters([adapter]); - const orchestrator = ProviderReplayHarness.layerWithRegistry( + const baseOrchestrator = ProviderReplayHarness.layerWithRegistry( { name: "thread-launch" }, registry, { databaseLayer: database, runEffectWorker: false }, ); const receipts = CommandReceiptStore.layer.pipe(Layer.provide(database)); + const orchestrator = + options.crewDeliveryContext === true + ? CrewDeliveryContext.layer.pipe( + Layer.provideMerge(baseOrchestrator), + Layer.provide(receipts), + Layer.provide(database), + ) + : baseOrchestrator; const threadManagement = ThreadManagement.layer.pipe( Layer.provide(orchestrator), Layer.provide(ServerSettings.layerTest(options.serverSettings)), @@ -177,6 +187,7 @@ export function makeHarness(options: HarnessOptions = {}) { Layer.provide(Layer.mergeAll(threadManagement, projectedProjects, externalServices)), ); return { + orchestrator, layer: Layer.mergeAll(launch, threadManagement, titleRegeneration, outbox, database), /** The faked project, git, and setup services plus the receipt store ThreadLaunch reads. */ services: Layer.mergeAll(externalServices, receipts), diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index f97f44d70469f..82282352571c6 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -1,3 +1,4 @@ +import * as CrewDeliveryContext from "../j5/a2a/CrewDeliveryContext.ts"; import * as UsageLimitRecoveryWorker from "./UsageLimitRecoveryWorker.ts"; import * as Scheduler from "../scheduling/Scheduler.ts"; import { layer as j5ThreadLineageLayer } from "../j5/a2a/ThreadLineage.ts"; @@ -225,7 +226,7 @@ const layerRunFinalizationServiceProvided = RunFinalizationService.layer.pipe( ), ); -const layerOrchestratorProvided = Orchestrator.layer.pipe( +const layerCrewOrchestratorBase = Orchestrator.layer.pipe( Layer.provide( Layer.mergeAll( layerCheckpointServiceProvided, @@ -250,6 +251,11 @@ const layerOrchestratorProvided = Orchestrator.layer.pipe( ), ); +const layerOrchestratorProvided = CrewDeliveryContext.layer.pipe( + Layer.provide(layerCrewOrchestratorBase), + Layer.provide(layerCommandReceiptStoreProvided), +); + const layerAgentSessionImporterProvided = AgentSessionImporter.layer.pipe( Layer.provide( Layer.mergeAll( diff --git a/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx b/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx index 82626751af2a2..c1e5cbae87d6d 100644 --- a/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx +++ b/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx @@ -1,3 +1,4 @@ +import { crewDeliveryContextPrefix } from "@t3tools/contracts/j5"; import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; import { renderToStaticMarkup } from "react-dom/server"; import { describe, expect, it } from "vite-plus/test"; @@ -832,3 +833,12 @@ describe("history recorded before the j5_ prefix", () => { ).toMatchObject({ kind: "human", exchange: "expects-reply" }); }); }); + +it("preserves an activating assignment's sender and reply obligation beneath Crew context", () => { + const original = presentThreadA2ADelivery({ message: message({ text: peerRaw }) }); + const text = crewDeliveryContextPrefix("Approved Crew context") + peerRaw; + expect(presentThreadA2ADelivery({ message: message({ text }) })).toEqual({ + ...original, + rawEnvelope: text, + }); +}); diff --git a/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx b/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx index adbb8cd66d7f0..2ed87aed341b3 100644 --- a/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx +++ b/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx @@ -1,4 +1,5 @@ import { useAtomValue } from "@effect/atom-react"; +import { crewDeliveryAssignment } from "@t3tools/contracts/j5"; import { renderSharedConversationNote } from "../sharing/SharedConversationCards"; import { Tooltip, TooltipTrigger, TooltipPopup } from "../../components/ui/tooltip"; import { observeResize } from "~/lib/observeResize"; @@ -362,8 +363,9 @@ export function presentThreadA2ADelivery( const { message } = input; if (!isThreadA2ADeliveryMessage(message)) return null; + const assignment = crewDeliveryAssignment(message.text); if (message.createdBy === "agent") { - const peer = parseAgentAuthoredEnvelope(message.text); + const peer = parseAgentAuthoredEnvelope(assignment); if (peer) { const sender = presentParticipantIdentity({ participantId: peer.senderId, @@ -384,7 +386,7 @@ export function presentThreadA2ADelivery( }; } } else if (message.createdBy === "user") { - const human = parseHumanEnvelope(message.text); + const human = parseHumanEnvelope(assignment); if (human) { return { kind: "human", @@ -396,7 +398,7 @@ export function presentThreadA2ADelivery( }; } } else if (message.createdBy === "system") { - const silence = parseSilenceEnvelope(message.text); + const silence = parseSilenceEnvelope(assignment); if (silence) { return { kind: "silence", diff --git a/apps/web/src/j5/crew/crewNotices.logic.test.ts b/apps/web/src/j5/crew/crewNotices.logic.test.ts index 2f0e9c778d42b..464a3e59c3738 100644 --- a/apps/web/src/j5/crew/crewNotices.logic.test.ts +++ b/apps/web/src/j5/crew/crewNotices.logic.test.ts @@ -609,3 +609,15 @@ it("counts all approved members from old gate notices while retaining launch fai expect(crewNoticeLines(notice!).map((line) => line.seat)).toEqual(["builder", "tester"]); expect(isHiddenCrewNotice(message)).toBe(false); }); + +it("presents created waiting seats without claiming they started", () => { + const text = approvedGate + .replace("thread_id=thread:b", "thread_id=thread:b start=waiting") + .replace("thread_id=thread:c", "thread_id=thread:c start=waiting"); + const notice = presentCrewNotice({ role: "user", createdBy: "system", text }); + expect(notice?.kind).toBe("gate"); + if (notice?.kind !== "gate") return; + expect(notice.roster.map((seat) => seat.start)).toEqual(["waiting", "waiting"]); + expect(crewApprovalSummary(notice)).toBe("Crew approved · 2 members"); + expect(crewNoticeLines(notice)).toEqual([]); +}); diff --git a/apps/web/src/j5/crew/crewNotices.logic.ts b/apps/web/src/j5/crew/crewNotices.logic.ts index d30442d733132..c952427869849 100644 --- a/apps/web/src/j5/crew/crewNotices.logic.ts +++ b/apps/web/src/j5/crew/crewNotices.logic.ts @@ -14,7 +14,7 @@ export interface CrewNoticeMessage { readonly createdBy?: unknown; } -export type SeatStart = "started" | "failed" | "pending"; +export type SeatStart = "waiting" | "started" | "failed" | "pending"; export interface CrewRosterSeat { readonly seat: string; @@ -88,7 +88,7 @@ export type CrewNoticePresentation = const GATE_BLOCK = /^\n([\s\S]*?)\n<\/j5_crew_gate>/; const ROSTER_LINE = - /^- ([^:]+): participant_id=(\S+) persona=(\S*) thread_id=(\S+)(?: start=(started|failed|pending))?( \(new\))?$/; + /^- ([^:]+): participant_id=(\S+) persona=(\S*) thread_id=(\S+)(?: start=(started|failed|pending|waiting))?( \(new\))?$/; // Decode after parsing: provider diagnostics cannot create fields or terminate tagged blocks. const decodeFailureField = (value: string) => @@ -102,7 +102,9 @@ const field = (block: string, name: string) => const fields = (block: string, name: string) => [...block.matchAll(new RegExp(`^${name}: (.*)$`, "gm"))].map((match) => match[1]!.trim()); const seatStart = (value: string | undefined): SeatStart | null => - value === "started" || value === "failed" || value === "pending" ? value : null; + value === "waiting" || value === "started" || value === "failed" || value === "pending" + ? value + : null; const parseGate = (text: string): CrewNoticePresentation | null => { const match = GATE_BLOCK.exec(text); diff --git a/apps/web/src/j5/crew/crewState.test.ts b/apps/web/src/j5/crew/crewState.test.ts index 88a77a04d07a3..feb5b19b05980 100644 --- a/apps/web/src/j5/crew/crewState.test.ts +++ b/apps/web/src/j5/crew/crewState.test.ts @@ -56,6 +56,18 @@ describe("crew state", () => { expect(classifyCrewSeat(seat())).toBe("idle"); }); + it("counts not-started seats separately and treats lifecycle overrides like idle seats", () => { + const waiting = seat({ notStarted: true }); + expect(classifyCrewSeat(waiting)).toBe("not-started"); + expect(classifyCrewSeat(seat())).toBe("idle"); + expect(formatCrewStateSummary(summarizeCrewState([waiting, seat()]))).toBe("1 not started"); + expect(crewHasRunningSeat(summarizeCrewState([waiting]))).toBe(false); + expect(classifyCrewSeat({ ...waiting, archivedAt: "2026-10-27" })).toBe("archived"); + expect(classifyCrewSeat({ ...waiting, settledOverride: "settled" })).toBe("settled"); + expect(classifyCrewSeat({ ...waiting, settledOverride: "active" })).toBe("not-started"); + expect(classifyCrewSeat({ ...waiting, runtime: { status: "running" } })).toBe("running"); + }); + it("summarizes a Crew and formats only the states worth saying", () => { const summary = summarizeCrewState([ seat({ runtime: { status: "running" }, updatedAt: "2026-09-14T12:00:00.000Z" }), @@ -72,6 +84,7 @@ describe("crew state", () => { failed: 1, "needs-you": 1, settled: 1, + "not-started": 0, idle: 1, archived: 0, unknown: 1, diff --git a/apps/web/src/j5/crew/crewState.ts b/apps/web/src/j5/crew/crewState.ts index 033dcdaf8339f..129b1b1347f12 100644 --- a/apps/web/src/j5/crew/crewState.ts +++ b/apps/web/src/j5/crew/crewState.ts @@ -5,6 +5,7 @@ import { /** The seat facts a Crew summary reads; every field is something the client already holds. */ export interface CrewSeatThread { + readonly notStarted?: boolean; readonly runtime?: Pick | null; readonly hasPendingApprovals: boolean; readonly hasPendingUserInput: boolean; @@ -19,6 +20,7 @@ export type CrewSeatState = | "failed" | "needs-you" | "settled" + | "not-started" | "idle" | "archived" | "unknown"; @@ -51,7 +53,7 @@ export const classifyCrewSeat = (thread: CrewSeatThread | undefined): CrewSeatSt (thread.settledOverride !== "active" && thread.settledAt != null) ) return "settled"; - return "idle"; + return thread.notStarted === true ? "not-started" : "idle"; }; /** @@ -77,6 +79,7 @@ export const summarizeCrewState = ( failed: 0, "needs-you": 0, settled: 0, + "not-started": 0, idle: 0, archived: 0, unknown: 0, @@ -98,6 +101,7 @@ const LABELS: ReadonlyArray = [ ["failed", "failed"], ["needs-you", "needs you"], ["settled", "settled"], + ["not-started", "not started"], ["unknown", "unknown"], ]; diff --git a/apps/web/src/j5/fleet/FleetFacts.tsx b/apps/web/src/j5/fleet/FleetFacts.tsx index 5c75b27686e5b..a543cdaa0b6ce 100644 --- a/apps/web/src/j5/fleet/FleetFacts.tsx +++ b/apps/web/src/j5/fleet/FleetFacts.tsx @@ -357,9 +357,12 @@ function FleetFactDetailContent({ export function FleetFactCells({ environmentId, agent, + notStarted = false, }: { readonly environmentId: EnvironmentId; readonly agent: FleetAgent; + /** A Crew seat that was created and has not accepted its first assignment has no runtime to report. */ + readonly notStarted?: boolean; }) { const key = fleetAgentKey(environmentId, agent.participantId); const facts = useAtomValue(fleetAgentFactsAtom(key)); @@ -380,7 +383,13 @@ export function FleetFactCells({ : undefined } > - {runtime === undefined ? "?" : } + {notStarted ? ( + "Not started" + ) : runtime === undefined ? ( + "?" + ) : ( + + )} {!live ? (stale) : null} {facts?.asks === undefined ? ( diff --git a/apps/web/src/j5/fleet/FleetPage.tsx b/apps/web/src/j5/fleet/FleetPage.tsx index 224c51689b9c6..5d69f0da43762 100644 --- a/apps/web/src/j5/fleet/FleetPage.tsx +++ b/apps/web/src/j5/fleet/FleetPage.tsx @@ -749,7 +749,11 @@ export function FleetRowItem( {/* A placement tree lives in one project, so only its root names it. */} {props.row.depth === 0 ? : } - + diff --git a/apps/web/src/j5/threads/SpawnedChildren.tsx b/apps/web/src/j5/threads/SpawnedChildren.tsx index 0222c1cdda3b6..a3bc51904476d 100644 --- a/apps/web/src/j5/threads/SpawnedChildren.tsx +++ b/apps/web/src/j5/threads/SpawnedChildren.tsx @@ -283,8 +283,10 @@ function SpawnedChildGroupRows( {status === null ? ( - {(child.seat === null ? null : seatRunLabel(thread.runtime?.status)) ?? - "Idle"} + {child.seat?.notStarted + ? "Not started" + : ((child.seat === null ? null : seatRunLabel(thread.runtime?.status)) ?? + "Idle")} ) : ( <> diff --git a/apps/web/src/j5/threads/spawnedChildren.logic.ts b/apps/web/src/j5/threads/spawnedChildren.logic.ts index 9628b2476bd39..dfed12b3d94b4 100644 --- a/apps/web/src/j5/threads/spawnedChildren.logic.ts +++ b/apps/web/src/j5/threads/spawnedChildren.logic.ts @@ -32,7 +32,9 @@ export function selectSpawnedChildRows( .flatMap((child): Array> => { const thread = threadsById.get(child.threadId); if (thread === undefined) return child.seat === null ? [] : [{ child, thread }]; - return thread.archivedAt !== null ? [] : [{ child, thread }]; + return thread.archivedAt !== null + ? [] + : [{ child, thread: { ...thread, notStarted: child.seat?.notStarted ?? false } }]; }) .toSorted((left, right) => activityOf(right).localeCompare(activityOf(left))); } diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index 0cec9f192d4d1..aa2e5787a3b40 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -195,15 +195,15 @@ asked for. ### `j5_propose_crew` -**Description (contract):** "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 +**Description (contract):** "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 @@ -211,23 +211,24 @@ persona's steps, and propose a custom seat, noted in its reason, where a named p 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. By default the user reviews and edits the roster in this thread, then approves or declines. If -Auto-approve new Crews is on for your project, the proposed roster launches immediately with no +Auto-approve new Crews is on for your project, the proposed roster is created immediately with no approval card. The result says whether it is open or approved; the launch report arrives here once -startup is confirmed or fails. Each seat keeps its configured access and tool approvals, 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 tool works under every sandbox and -approval policy, including approval policy never; never refuse the brief because approvals are -disabled." +creation finishes or fails. Approval creates seats without starting turns. Send each member its +first assignment when it has work; reuse finished members for follow-up work in the same thread. +Each seat keeps its configured access and tool approvals, 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 tool works under every sandbox and approval policy, including +approval policy never; never refuse the brief because approvals are disabled." Published with `destructiveHint: true`: depending on the project setting, this call can launch agents immediately. | Input | Type | Required | Meaning | | ------------------- | ----------------------------------------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | string | yes | The Crew's display name | -| `brief` | string | yes | What every seat starts on, verbatim | +| `brief` | string | yes | The shared brief included with each seat's first assignment | | `seats` | 1–12 of `{seat, persona?, model_selection?, runtime_mode?, reason, instructions?, steps?, workspace}` | yes | Seat name, persona id from `j5_list_personas` (none for a custom seat), why, wiring, custom-seat runtime, the playbook step ids the seat owns, and where it works (the `j5_spawn_agent` workspace shape) | | `playbook` | string | no | A playbook name from `j5_playbook_list` in the Captain's workspace; the Crew follows it | | `client_request_id` | string | no | Supply and reuse to make retries safe | @@ -252,24 +253,25 @@ member records the step ids it owns, and each seat's first turn lists its steps gate inline above the Captain's composer unless Auto-approve new Crews is enabled for the Captain's project; approval spawns the approved roster (the human may have edited it) as Peer Agents under the caller, persona-backed where a seat names one, records the Crew snapshot with each member's reason (with human or automatic approval recorded), and posts -a `` launch report into the caller's thread once every seat has started or failed to start (or a minute has passed): the roster, what the user changed against the proposal, and per seat `start=started|failed|pending`, with a `seat_failed` line carrying the run's error (`not_started` when the seat's thread exists but its brief never went out) and a `seat_not_created` line for an approved seat whose thread was never created, which is left off the roster. A proposal resolves once: a seat that fails does not stop the others or reopen the gate. Declines post the decline at once. -Every seat names its workspace, with the same three choices as `j5_spawn_agent`, so there is no Captain-aware default (Jackson, 2026-10-03). Each seat's workspace resolves at preview against the Captain's repository, and the approval token binds it, as it binds the Captain's branch and worktree. Every preview also carries the Captain's current branch, the directory its branch picker searches, and its worktrees, for the roster card's editor; the branches themselves are searched live, so no list is capped. A seat the person adds starts in the Captain's checkout. A seat recorded before workspaces were required stays readable but is refused at preview and approval until one is chosen. A new-worktree seat's brief starts once ThreadLaunch has prepared it, as for `j5_spawn_agent`, so the launch report may read `pending` for a seat whose setup outlasts the report's minute, and a failed preparation arrives as that seat's failure. +a `` launch report into the caller's thread immediately after creation: the roster, what the user changed against the proposal, and per seat `start=waiting|started|failed|pending`, with a `seat_failed` line carrying the run's error (`not_started` when the seat's thread exists but registration failed) and a `seat_not_created` line for an approved seat whose thread was never created, which is left off the roster. A proposal resolves once: a seat that fails does not stop the others or reopen the gate. Declines post the decline at once. +Every seat names its workspace, with the same three choices as `j5_spawn_agent`, so there is no Captain-aware default (Jackson, 2026-10-03). Each seat's workspace resolves at preview against the Captain's repository, and the approval token binds it, as it binds the Captain's branch and worktree. Every preview also carries the Captain's current branch, the directory its branch picker searches, and its worktrees, for the roster card's editor; the branches themselves are searched live, so no list is capped. A seat the person adds starts in the Captain's checkout. A seat recorded before workspaces were required stays readable but is refused at preview and approval until one is chosen. New and added seats wait for their first assignment. A direct chat message, participant message, or playbook handoff activates the seat with its approved instructions and shared brief, the current roster with responsibilities and participant ids, and the assignment with its envelope and reply obligation intact. A new-worktree seat prepares its workspace before running that assignment; failed preparation is reported as a seat failure. New Crews require human approval by default. **Settings → Agent Setup → Crews → Auto-approve new Crews** skips that gate, off by default and overridable per project. The server reads the Captain's project setting only for a new request; changing it leaves existing Crews and open proposals alone. Automatic approval launches the proposed configuration through the same provider, workspace, capacity, and persona checks. Tool approvals still follow each seat's access. The persisted proposal and launch report distinguish automatic approval from a human decision. ### `j5_request_crew_member` -**Description (contract):** "Add one seat directly to a running crew you command when the work needs -expertise the roster lacks. No human approval is needed, regardless of Auto-approve new Crews. Give -a seat name, a persona id from j5_list_personas or required instructions for a custom seat, a reason -identifying the missing expertise, and its workspace (the same choices as j5_propose_crew). Custom -seats inherit your model selection and run with full-access unless you set model_selection or +**Description (contract):** "Add one seat directly to a running crew you command when the work needs expertise the roster +lacks. No human approval is needed, regardless of Auto-approve new Crews. Give a seat name, a +persona id from j5_list_personas or required instructions for a custom seat, a reason identifying +the missing expertise, and its workspace (the same choices as j5_propose_crew). Custom seats +inherit your model selection and run with full-access unless you set model_selection or runtime_mode; saved personas use their own configuration. Optionally give a brief; otherwise the seat gets the Crew's brief. On a playbook Crew, steps may claim only unowned step ids from j5_playbook_read. The result returns the updated roster or refuses the seat with its name and -reason; startup is reported separately here. Each member's configured access still controls tool -approvals. Captain-only: a member sends the concern 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. -Works under every approval policy, including approval policy never." +reason; creation is reported separately here. The new member waits for its first assignment; send +it with j5_send_message when the work is ready. Each member's configured access still controls +tool approvals. Captain-only: a member sends the concern 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. Works under every approval policy, including approval policy never." | Input | Type | Required | Meaning | | --------------------------------- | -------------- | -------- | --------------------------------------------------------------------------- | @@ -399,7 +401,7 @@ run; `j5_stop_crew` doesn't, and unarchiving doesn't restart it. 5. A `j5_send_message` to the caller itself is refused with an error naming the caller's own id. 6. `j5_list_participants` marks the caller's row `self`, reports a person's row as unable to receive a plain message and able to be asked, and omits provider Subagents. 7. `j5_spawn_agent` refuses a call that omits provider, model, or reasoning, refuses a choice outside the Role's allowlist with an error naming the Role, and refuses a caller that sits in a Crew with an error naming escalation to its Captain. -8. A spawned agent's first turn contains its own participant id and project. +8. A spawned agent's first turn contains its own participant id and project. A Crew seat receives its approved instructions, shared brief, current roster with responsibilities and participant ids, and any playbook or handoff obligation on its first assignment; the assignment keeps its own envelope and reply obligation. Later assignments reuse the same thread without repeating that introduction. Started members receive net roster changes at the top of their next delivery, without a separate turn. 9. `j5_stop_agent` and `t3_thread_organize` act on one target; neither cascades. `j5_stop_agent` reaches an agent in any project on this server, and refuses a target that runs with broader permission modes than the caller unless the caller is that seat's Captain. A stopped run is never resumed after a server restart, even when restart continuation is enabled. 10. `t3_thread_organize` archives and restores any thread in the environment that upstream's access check lets the caller act on. Archive closes Exchanges through the shared reactor without a confirmation-token exchange or interrupting an existing run; human archive warnings remain. 11. `j5_clear_own_ask` closes only an Exchange the caller opened and records the closure as sender-cleared. diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index 93539251ee7fc..44d5f80844f97 100644 --- a/docs/j5/product/features/crews.md +++ b/docs/j5/product/features/crews.md @@ -57,19 +57,19 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif ### The unit -6. Approval spawns every seat as a Peer Agent placed under the Captain and records the roster snapshot with each member's reason (human or automatic approval is recorded); a proposal resolves once, so a second approval spawns nothing and a decision that races another device's on the same gate is refused rather than undoing it. The Captain is told by one launch report, posted once every seat has produced provider activity, completed, or failed (or a minute has passed without confirmation), naming what the person changed against the proposal and each seat's outcome with the run's error; a seat whose provider is signed out is refused at spawn with that reason, before anything is created. +6. Approval creates every seat as a Peer Agent placed under the Captain and records the roster snapshot with each member's reason (human or automatic approval is recorded); it starts no turns. A proposal resolves once, so a second approval creates nothing and a decision racing another device's answer is refused. The Captain receives one launch report immediately after creation, naming the person's changes, each created seat as waiting for work, and any creation failures. A seat whose provider is signed out is refused before creation. The first participant message, direct chat message, or playbook step activates a waiting seat with its approved instructions and shared brief, the roster at activation including responsibilities and participant ids, and the assignment with its envelope and reply obligation intact. 7. An approval launches once. A failure before any seat spawns (the Crew or the approval could not be recorded) leaves the gate open to approve again; once seats start spawning, a seat that fails does not stop the others, and the launch report names every approved seat, including one whose thread was never created. A seat that was never created is not on the roster; the Captain asks for it again with `j5_request_crew_member`. 8. A Crew lives in exactly one project and renders as one node under its Captain with its members beneath it. 9. Every member can message any participant; the Crew's contact with the person goes through the inbox or its Captain rather than chat — a plain send to the person is refused by the [human-ask rule](../a2a/agent-tools.md), so a seat reaches the person only with an ask that lands in the Inbox or a reply on an open Exchange. A live Crew seat's pending provider approvals that the provider can still take are listed in the Inbox with their Crew and seat, counted on the bell, and answerable there; the seat's own thread still shows them too, so either place may answer. The Captain's approvals and questions, and approvals a seat can no longer take, are not listed. A live seat's pending native question that can still take an answer is listed as an Inbox link and counted on the bell; it is answered in the original thread, and the link disappears when resolved. A seat asks its Captain rather than the person: Claude and Codex seats have no native question tool, and every seat is told to ask its Captain with `j5_send_message`; a harness that still lets a seat ask natively shows the question in the seat's thread and notifies its Captain. The Captain may answer through upstream's pending-request tools when its modes allow and the answer follows the brief or the person's instructions; otherwise it asks the person to answer in the seat's thread. Native questions are not Inbox Exchanges. An answer to a request already resolved elsewhere is refused and changes nothing. ### Growing -10. Only the Captain adds members, directly with a reason and assignment, regardless of the auto-approval setting. The same launch checks apply; successful additions append the seat and bump the snapshot version. The tool returns the updated roster or a refusal naming the seat and reason. No new addition request waits for a human; open legacy requests remain resolvable above their Captain's composer. +10. Only the Captain adds members, directly with a reason and assignment, regardless of the auto-approval setting. The same launch checks apply; successful additions create a waiting seat without a turn, append it to the roster, and bump the snapshot version. The tool returns the updated roster or a refusal naming the seat and reason. No new addition request waits for a human; open legacy requests remain resolvable above their Captain's composer. 11. A Crew holds at most twelve seats, counting open requests; a member's request is refused naming escalation to its Captain. ### Handoff artifacts -12. A seat whose definition declares an output artifact writes it as its handoff artifact in the project's artifacts; its first turn names the exact path. +12. A seat whose definition declares an output artifact writes it as its handoff artifact in the project's artifacts; its first turn names the exact path. The first assignment carries its playbook context and handoff obligation; a later assignment reuses the same thread and workspace without repeating its introduction. Members that finished remain available on the roster. Started members receive net roster changes, naming who joined or left and their responsibility, at the top of their next delivery. Waiting members receive the current roster with their first assignment. Roster changes alone start no turns, and availability produces no polling or acknowledgment turns. 13. When a seat finishes, the Captain receives a notice that leads with how the run ended and, for a failed run, carries the run's recorded error, then whether the seat's handoff artifact was written, missing, unavailable with the reason it can never be read, or never declared, a written handoff artifact riding inline when short and by path otherwise; a finish whose notice would repeat the seat's last one is silent, and a notice arriving while the Captain's turn runs folds into the seat notice already queued behind it rather than queuing another turn. 14. A seat that finishes without its handoff artifact is reminded once and is reported to its Captain on its next finished run whatever happened. @@ -84,11 +84,11 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif 18. J5 never settles a seat because its run finished; settling the Captain settles its seats; upstream's settle rules apply to every thread. 19. A Crew archives only as a unit; archiving never deletes a worktree, branch, or checkpoint; archiving with open Exchanges or running turns lists them seat by seat and requires a confirmation token. 20. A successor Crew starts from a new proposal and a fresh brief; nothing from the archived Crew's conversation, obligations, or asks is carried over automatically, and its brief, roster, ledger, and handoff artifacts stay readable: the Fleet page's Retired section lists retired Crews across projects, each naming its project, with a link to the Captain's thread while it is active (the ledger's home), the brief, the roster snapshot (seat, agent, why it joined, version), the version, and when it retired, and offers no action on them; a retired Crew comes back only with its Captain, when it retired because the Captain was archived (AC17); handoff artifacts stay on the Artifacts page. -21. A Crew stops as a unit: its Captain over `j5_stop_crew`, or the person from the Crew's Fleet header or the Captain's expander, interrupts every seat with a running turn; idle seats are untouched, nothing settles or is retired, and the result names each seat as interrupted, already idle, or archived. +21. A Crew stops as a unit: its Captain over `j5_stop_crew`, or the person from the Crew's Fleet header or the Captain's expander, interrupts every seat with a running turn; idle and not-started seats are untouched, nothing settles or is retired, and the result names each seat as interrupted, already idle, or archived. ### State -22. A Crew's row on the Fleet page and its Captain's expander in the sidebar summarize the seats' states from measured facts (running, failed, needing a person, settled, unknown); a seat's own row reads Failed, Interrupted, or Completed from its last run rather than Idle; idle seats are the unspoken default, and no state is inferred from silence. In the Captain's timeline, a roster approval shows “Crew approved · N members”, plus “· by ” in a shared conversation, where more than one person could have approved it; launch reports and finish notices otherwise show a line only for a seat that needs attention. A clean finish adds no line. +22. A Crew's Fleet row and Captain's expander summarize measured seat states, including Not started separately from idle, running, failed, needing a person, settled, and unknown. Not started means creation succeeded and no first assignment has been accepted. Stop, archive, settle, and unarchive treat waiting seats as idle seats. A failed last run reads as failed; nothing is inferred from silence. A seat with a finished run still reads Failed, Interrupted, or Completed. In the Captain's timeline, a roster approval shows “Crew approved · N members”, plus “· by ” in a shared conversation, where more than one person could have approved it; other notices show a line only for a seat that needs attention. A clean finish adds no line. ### Several people @@ -96,10 +96,10 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif ## Scenarios -- **A pull-request Crew.** In Billing Migration the user sends "Put together a crew to land the invoice-export PR: build, review, sit on CI." The Captain proposes Builder, Critic, and Sitter with a reason each; the user drops the Sitter, approves, and the two seats appear under the Captain with the brief and the roster. The Critic finishes and writes its ReviewHandoff into the project's artifacts; the Captain's thread receives the notice with the findings inline. (AC1, AC2, AC6, AC8, AC12, AC13) +- **A pull-request Crew.** In Billing Migration the user sends "Put together a crew to land the invoice-export PR: build, review, sit on CI." The Captain proposes Builder, Critic, and Sitter with a reason each; the user drops the Sitter, approves, and the two seats appear under the Captain as Not started. The Captain sends the Builder its assignment, then sends the Critic the review assignment when code is ready. Each receives the brief and current roster on activation. The Critic finishes and writes its ReviewHandoff into the project's artifacts; the Captain's thread receives the notice with the findings inline. (AC1, AC2, AC6, AC8, AC12, AC13) - **Two Crews at once.** In Website Redesign the user, mid-conversation with the agent that has been planning the launch, sends "Create a crew to migrate the blog to the new CMS" and then "Create another crew to rewrite the pricing page copy". The same thread proposes two rosters, each answered above its composer; both appear under the Captain's row as named groups, Blog Migration and Pricing Copy, each with its own toggle, state, and Stop. (AC1, AC2, AC15) - **More hands.** The Captain adds a Sitter for the CI failures directly; the seat joins at version 2. A signed-out provider instead refuses the named seat without adding it. A Builder trying to add a helper is refused and told to escalate to its Captain. (AC10, AC11) -- **A flaky launch.** One of three approved seats cannot be created when the user approves the roster. The other two start; the launch report says the third was never created and why, and the Captain asks for it again with `j5_request_crew_member`. (AC7) +- **A flaky launch.** One of three approved seats cannot be created when the user approves the roster. The other two wait for assignments; the launch report says the third was never created and why, and the Captain asks for it again with `j5_request_crew_member`. (AC7) - **Stop everything.** The Builder is heading down a path the person recognizes as wrong while the Critic is mid-review. The person clicks Stop crew on the Crew's Fleet header; both running turns end, the seats stay on the roster, and the Captain briefs them again. (AC21) - **A playbook-shaped Crew.** After talking through a change with the agent, the user sends "ok, lets create a crew to implement what we have discussed. Please use @playbook:release for this work." The agent reads the playbook and proposes a roster above its composer: "Follows playbook: Release", a planner seat and a builder seat each owning the steps that name them, the step that names no persona placed with the builder, and a stand-in custom seat for the turned-off reviewer persona, flagged as a swap. The user approves; the launch report names the playbook, the Captain starts it, and the first step reaches the planner seat. Asking for "the release playbook" by name does the same; a message that only mentions the playbook in passing gets an ordinary roster. (AC1, AC2, AC3, AC6) - **A poisoned Crew.** The Critic has gone wrong and confused its crewmates. The Captain asks to archive the Crew; the refusal lists two open asks and one running turn seat by seat with a token; the Captain confirms after checking with the user, writes a fresh brief from the surviving branch and handoff artifacts, and proposes a successor. (AC16, AC19, AC20) diff --git a/packages/contracts/src/j5.ts b/packages/contracts/src/j5.ts index 2e2b46ceba595..97ca0b2eab135 100644 --- a/packages/contracts/src/j5.ts +++ b/packages/contracts/src/j5.ts @@ -284,7 +284,12 @@ export type CrewRef = typeof CrewRef.Type; /** What a sidebar row needs: which Crew a thread sits in, or which Crews it commands. */ export const ThreadCrewMembership = Schema.Union([ - Schema.Struct({ kind: Schema.Literal("member"), seat: Schema.String, crew: CrewRef }), + Schema.Struct({ + kind: Schema.Literal("member"), + seat: Schema.String, + crew: CrewRef, + notStarted: Schema.optionalKey(Schema.Boolean), + }), Schema.Struct({ kind: Schema.Literal("captain"), crews: Schema.Array(CrewRef) }), ]); export type ThreadCrewMembership = typeof ThreadCrewMembership.Type; @@ -302,7 +307,12 @@ export const SpawnedChild = Schema.Struct({ threadId: ThreadId, participantId: Schema.String, seat: Schema.NullOr( - Schema.Struct({ crewInstanceId: Schema.String, crewName: Schema.String, seat: Schema.String }), + Schema.Struct({ + crewInstanceId: Schema.String, + crewName: Schema.String, + seat: Schema.String, + notStarted: Schema.optionalKey(Schema.Boolean), + }), ), }); export type SpawnedChild = typeof SpawnedChild.Type; @@ -388,6 +398,7 @@ export const FleetAgent = Schema.Struct({ crewInstanceId: Schema.String, crewName: Schema.String, seat: Schema.String, + notStarted: Schema.optionalKey(Schema.Boolean), captainParticipantId: Schema.String, }), ), @@ -1269,3 +1280,5 @@ export const J5ClientReadRpcGroup = RpcGroup.make( stream: true, }), ); + +export { crewDeliveryContextPrefix, crewDeliveryAssignment } from "./j5/crewDeliveryContext.ts"; diff --git a/packages/contracts/src/j5/crewDeliveryContext.ts b/packages/contracts/src/j5/crewDeliveryContext.ts new file mode 100644 index 0000000000000..32de8104ced88 --- /dev/null +++ b/packages/contracts/src/j5/crewDeliveryContext.ts @@ -0,0 +1,15 @@ +const OPEN = "\n"; +const CLOSE = "\n\n\n"; + +/** The assignment keeps its own envelope after the platform's Crew context. */ +export const crewDeliveryContextPrefix = (context: string) => + context === "" + ? "" + : `${OPEN}${context.replaceAll("", "<\\/j5_crew_delivery_context>")}${CLOSE}`; + +/** Call only on platform-owned delivery message ids; ordinary authored text stays literal. */ +export const crewDeliveryAssignment = (text: string) => { + if (!text.startsWith(OPEN)) return text; + const end = text.indexOf(CLOSE, OPEN.length); + return end < 0 ? text : text.slice(end + CLOSE.length); +}; diff --git a/packages/provider-core/src/j5/orchestrationInstructions.ts b/packages/provider-core/src/j5/orchestrationInstructions.ts index b6e2d7d9b74ce..fd4b656ef6592 100644 --- a/packages/provider-core/src/j5/orchestrationInstructions.ts +++ b/packages/provider-core/src/j5/orchestrationInstructions.ts @@ -20,7 +20,7 @@ ${AGENT_INVOCATION_INSTRUCTIONS} - A provider-native Subagent is child work created and owned inside one provider session. Use your provider's native Subagent mechanism when the user asks for a subagent, or when you want help the user does not need to see or message. J5 observes provider-native Subagents; the persona mention above instead creates a J5-owned delegated child. For cross-provider work that the user does not need to message directly, use \`delegate_task\`. Also use \`delegate_task\`, with that provider instance and model, for same-provider work when the native Subagent tool cannot run the chosen model. For a child task that needs a separate checkout, use \`delegate_task\` with \`isolation:"worktree"\` across any provider or model. It starts from the parent local commit and runs project setup; uncommitted edits are not copied. Do not treat a native tool's model list as the full list of available subagent models: use \`orchestrator_capabilities\` to discover the current provider/model IDs from the same live catalog as the composer, including configured custom models. - For every delegated review round, call \`delegate_task\` again. Include the original brief, prior findings, responses, and unresolved objections in each new task prompt. Track each round by its own \`taskId\`. Use a distinct \`clientRequestId\` per round, stable across retries of that round. - A Peer Agent is a full participant with its own top-level thread that the user can open and message. Use platform \`j5_spawn_agent\` when the user wants or would benefit from talking to the agent directly, including cross-provider work where the user needs a directly messageable participant. Its brief states the task and whether a reply is expected; when you need a reply, include what should come back in that brief instead of sending a follow-up ask. -- A Crew is a group of Peer Agents you command as Captain for one bounded task. Use \`j5_propose_crew\` when the user asks for a crew in ordinary chat or the work splits into distinct responsibilities that should run at once. Mix saved personas from \`j5_list_personas\` with custom seats: set persona for a saved persona, or omit it and provide task-specific instructions for a custom seat. Custom seats inherit your harness, model, and reasoning by default and run with full access unless you set \`runtime_mode\`; you can select their harness, model, reasoning, and access with \`model_selection\` (instanceId, model, options) and \`runtime_mode\` from \`orchestrator_capabilities\`. Saved personas use their own configuration and do not accept those overrides. The app shows the roster in your thread, with each seat's resolved provider, model, reasoning, and access, and it is approved, edited, or declined there. Approved seats spawn under you, and each seat's finish reaches you as a message. +- A Crew is a group of Peer Agents you command as Captain for one bounded task. Use \`j5_propose_crew\` when the user asks for a crew in ordinary chat or the work splits into distinct responsibilities that should run at once. Mix saved personas from \`j5_list_personas\` with custom seats: set persona for a saved persona, or omit it and provide task-specific instructions for a custom seat. Custom seats inherit your harness, model, and reasoning by default and run with full access unless you set \`runtime_mode\`; you can select their harness, model, reasoning, and access with \`model_selection\` (instanceId, model, options) and \`runtime_mode\` from \`orchestrator_capabilities\`. Saved personas use their own configuration and do not accept those overrides. The app shows the roster in your thread, with each seat's resolved provider, model, reasoning, and access, and it is approved, edited, or declined there. Approved seats are created under you without starting turns; send each member its first assignment when it has work, or hand it its first playbook step. Reuse finished members for follow-up work in the same thread; each seat's finish reaches you as a message. - Crew members, their Captain, and Captains of other crews can coordinate directly with \`j5_send_message\`: share findings, concerns, questions, evidence, and final results when they would change the other agent's work, grouped into one message rather than sent as each one happens. A busy receiver handles each message as its own turn after its current one ends. Do not wait for an artifact or a separate coordination approval. Return results in messages unless the user or a selected persona explicitly requires an artifact; that output requirement never blocks conversation. If a concern needs expertise missing from the roster, the member tells its Captain, and the Captain uses \`j5_request_crew_member\` with the crew_instance_id and a clear reason naming the concern and needed responsibility. The user approves additions in the existing inbox; continue the already-approved work and coordination while that request is pending. - Use \`j5_list_participants\` to resolve an already-addressable agent or a person. It lists the people who can write to your thread; where more than one can, it also lists everyone here, and an ask to everyone here reaches all of them and is closed by the first reply. Use \`j5_send_message\` without expect_reply for updates or results that need no response. Only for later work owed by an existing participant, use \`j5_send_message(..., expect_reply=true, intent="...")\` to open an Exchange. The reply arrives later as an incoming message; continue with other work instead of polling or holding a turn open to wait. Messages reach a supported active turn through provider steering; otherwise they queue for its next turn. - \`schedule_task\` creates persistent recurring work in the app scheduler. Pass \`schedule\` as a structured object, never as JSON text: \`{"type":"interval","everyMs":3600000}\` for an interval, or \`{"type":"fixed_time","timeOfDay":"09:00","weekdays":[1,2,3,4,5]}\` for a wall-clock schedule, or \`{"type":"webhook"}\` to run on each request to the returned \`webhookUrl\` (the run sees the request only through \`{{body.path}}\`-style placeholders in the prompt). By default runs return to the current thread, which suits orchestrating: each trigger arrives here and you delegate or dedupe; set \`bindToCurrentThread=false\` only when the user wants a fresh thread for every run. After scheduling a timer, report the returned cadence and next run time; for a webhook, report its \`webhookUrl\`, or say T3 Connect remote access is needed if it is missing. From 7d6017d14a31e62508228efbcd1cf28f4066453e Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 13:00:22 -0400 Subject: [PATCH 02/12] fix(j5): deliver Crew context when the assignment starts --- FORK.md | 9 +- .../CrewDeliveryContext.integration.test.ts | 109 ++++++++- .../src/j5/a2a/CrewDeliveryContext.test.ts | 221 +++++++++--------- apps/server/src/j5/a2a/CrewDeliveryContext.ts | 203 +++++----------- .../src/j5/a2a/CrewProposalService.test.ts | 1 - apps/server/src/j5/a2a/CrewTurnContext.ts | 153 ++++++++++++ apps/server/src/j5/a2a/Migrations.test.ts | 2 +- .../migrations/049_CrewSeatActivation.test.ts | 2 +- .../ProviderTurnStartService.test.ts | 56 ++++- .../ProviderTurnStartService.ts | 26 ++- .../src/orchestration-v2/runtimeLayer.ts | 2 + .../web/src/j5/a2a/ThreadA2ARenderer.test.tsx | 13 ++ apps/web/src/j5/a2a/ThreadA2ARenderer.tsx | 4 +- docs/j5/product/features/crews.md | 6 +- 14 files changed, 519 insertions(+), 288 deletions(-) create mode 100644 apps/server/src/j5/a2a/CrewTurnContext.ts diff --git a/FORK.md b/FORK.md index 5f3ba0f1d6b3d..9321dda4d813c 100644 --- a/FORK.md +++ b/FORK.md @@ -315,8 +315,6 @@ migrations after upstream migrations. 36. Provider event log file names: `apps/server/src/provider/EventNdjsonLogger.ts` `resolveThreadSegment` ends the segment with a twelve-character hash of the whole thread id whenever normalization shortened the id (a colon, a run of punctuation, or the eighty-character cap), because platform-spawned threads (Crew seats, Peer Agents) carry deterministic ids identical up to the cut and every seat of a Crew was landing in one log file. Only a bare uuid id, which normalization leaves untouched, keeps its plain name; ids with colons that were under the cap change name once on upgrade. One appended branch; `EventNdjsonLogger.test.ts` covers it. 37. The lone-seat archive guard (2026-09-17, Bryant's choice of the server dispatch handler over a client-side mirror or an after-the-fact reversal, after Jackson's review of PR #151): the `layer` of `apps/server/src/ws.ts` yields J5-owned `makeCrewSeatArchiveGuard` (`apps/server/src/j5/a2a/crewSeatArchiveGuard.ts`) once and passes it to `layerWsRpc`, which hands it to case 78's command admission, the one J5 call `dispatchCommand` carries. Every client door (web sidebar, mobile swipe, any future client) sends `thread.archive` and `thread.delete` through that one handler, so a live Crew's seat is refused there with a typed error whose message reaches the client as the dispatch error's detail; `j5_archive_crew` and the Captain cascade archive seats through the lifecycle service and never meet the guard. A Crew store that cannot be read lets the command through, because a refusal rests on a live fact, not an outage. The web keeps its pre-archive toast as the friendlier early message. -The same runtime composition wraps the orchestrator with `j5/a2a/CrewDeliveryContext.ts` (#745). Only Crew-seat message dispatches gain the approved first-turn context or net roster changes; direct chat, MCP messages, and playbook handoffs share this seam. J5 migration 48 owns the context and delivery bookkeeping. First assignments for new-worktree seats use upstream's `defer_start` workspace preparation; `j5/a2a/CrewSeatPreparation.ts` starts that preparation from persisted run events and resumes preparing seats on boot. Keep the decorator shared by all thread-management callers; do not move it into one transport. Ordinary threads and non-message commands retain upstream behavior. - 38. Fork placement: `orchestration-v2/runtimeLayer.ts` decorates the single `layerThreadManagementProvided` instance with J5 `ThreadLineage.ts`. It reaches both client intake and MCP. The decorator acts on `thread.fork` only. It registers the source if it has no home yet, then records the fork's home and its `forked-from` provenance in one transaction through the existing creation composition; existing placement policy makes the fork a sibling of its source. A Subagent source is not a participant, so its fork registers like any new thread and gets no placement. Replaying the original command repairs a placement that failed after the fork committed, without another fork. Merge-back passes straight through, and its tool is upstream's (case 2). Upstream dropped its same-project rule for thread tools: fork, merge-back and organize reach any thread in the environment, within the limits upstream's `McpToolAccess` checks, and J5 adds no project rule of its own (Jackson's 2026-10-08 decision 6). Creation-side placement and composition avoid a delivery-to-thread-management dependency cycle. J5 re-declares the fork, organize and queue-edit tools (case 2): fork to expose actionable placement errors, organize to apply the shared crew-seat guard before dispatch, queue edit to hold an agent to its own messages. Unit retirement continues through the internal archive service. Organize settles through upstream's `settleThread`, so a settle asked for during a running turn takes effect when the turn ends, and a Crew seat may settle itself (decision 12). All other adopted tool handlers use original upstream tool objects and handler layers. The queue's cancel, reorder and promote tools are upstream's (#136). Case 34's typed HTTP migration is tracked in #137. 39. The welcome wizard's "Providers" wording: `components/onboarding/WelcomeWizard.tsx` is upstream's file except for branding (case B: the app name and CLI command from `branding.ts`, and the plain header title in place of the T3 wordmark) and four wording edits that say providers where upstream says agents: the second stage's label in `ONBOARDING_STAGES` (`"Providers"`), the Connect stage's sentence ("We'll set up providers and projects on each"), and the file-header and step comments. J5 calls the runtimes providers and keeps "agent" for the threads a person directs. On every upstream advance, re-apply these four edits. The rest of this case is retired (2026-10-04, the Squadron fold, [#412](https://github.com/Jacksondr5/j5code/issues/412)): the wizard's fourth Squadron stage is removed, `apps/web/src/j5/onboarding/` is deleted, and `routes/welcome.tsx` carries only case 73's refusal of the wizard to anyone but a named Owner. Imported conversations register in their project like every other thread (case 10), and the server's assignment route is removed (case 9). @@ -485,6 +483,8 @@ The same runtime composition wraps the orchestrator with `j5/a2a/CrewDeliveryCon 88. Agent Setup and Crew approval settings ([#743](https://github.com/Jacksondr5/j5code/issues/743)): `packages/contracts/src/settings.ts` registers J5's `crewAutoApprove` boolean (default off) in server settings, patches, and project overrides. `apps/web/src/components/settings/settingsSearch.ts` renames the existing `/settings/personas` destination to Agent Setup and adds search terms and the scoped Crew setting target. `apps/mobile/src/features/settings/SettingsRouteScreen.tsx` and `apps/mobile/src/Stack.tsx` rename the existing Personas navigation entry and title to Agent Setup. Runtime behavior and the web sections stay in J5-owned files; mobile still exposes only the persona library. +89. Deferred Crew assignments ([#745](https://github.com/Jacksondr5/j5code/issues/745)): `orchestration-v2/runtimeLayer.ts` wraps the shared orchestrator with J5-owned `CrewDeliveryContext.ts` for first-assignment workspace preparation and guards, and supplies J5-owned `CrewTurnContext.ts` to provider turn start. `orchestration-v2/ProviderTurnStartService.ts` delegates the selected assignment's text to that service immediately around provider delivery. The service builds the approved introduction or net roster changes from the current roster, and records them only after the provider accepts the prompt. Editable messages and shared author prefixes stay unchanged, so queued edits, cancellations and reordering cannot consume context. Waiting seats whose Crew is retired fail visibly; a retained worktree guard applies even after retirement. J5 migration 49 owns the context, and `CrewSeatPreparation.ts` uses upstream's persisted preparation path. `orchestration-v2/ProviderTurnStartService.test.ts` exercises this hook on a retained native conversation with no history handoff, including provider-before-acknowledgment order. Non-Crew threads keep upstream delivery unchanged. On an advance, retain the hook at actual delivery after queue selection, shared by every provider and transport. + ## Pin and upstream advance runbook Current pin: `70d60e03a7a35c6fa131825bbfa05ec893e69912`, upstream's nightly tag `v0.1.1-nightly.20261017.3238` on `main` (frozen 2026-10-17). The previous pin was `29980a31409234b676f97bd477c4e46fdb61a929`, from upstream `main`. @@ -791,12 +791,13 @@ explicitly marked. | `packages/provider-pi/src/server/mcpExtensionSource.test.ts` | N | 8 | | `apps/server/src/orchestration-v2/ProviderTurnControlService.ts` | R | 26 | | `apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts` | A | N | -| `apps/server/src/orchestration-v2/ProviderTurnStartService.ts` | A | 30, N | +| `apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts` | N | 89 | +| `apps/server/src/orchestration-v2/ProviderTurnStartService.ts` | A | 30, N, 89 | | `apps/server/src/orchestration-v2/RunFinalizationService.ts` | R | 30 | | `apps/server/src/orchestration-v2/ThreadLaunchService.ts` | R | Saved-agent launch | | `apps/server/src/orchestration-v2/ThreadSearch.ts` | N | 86 | | `apps/server/src/orchestration-v2/runtimeLayer.test.ts` | R | 3 | -| `apps/server/src/orchestration-v2/runtimeLayer.ts` | R | 5, 21, 26, 30, 38, 86 | +| `apps/server/src/orchestration-v2/runtimeLayer.ts` | R | 5, 21, 26, 30, 38, 86, 89 | | `apps/server/src/os-jank.ts` | R | H | | `apps/server/src/persistence/Sqlite.test.ts` | R | 1 | | `apps/server/src/persistence/Sqlite.ts` | A | 1, 31 | diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts index 18602a90dc829..767c6482539dc 100644 --- a/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts @@ -1,3 +1,4 @@ +import * as CrewTurnContext from "./CrewTurnContext.ts"; import { assert, it } from "@effect/vitest"; import { CommandId, EventId, MessageId, ThreadId } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -42,6 +43,7 @@ it.effect( harness.layer, Crews.layer.pipe(Layer.provide(harness.layer)), ledgerLayer.pipe(Layer.provide(harness.layer)), + CrewTurnContext.layer.pipe(Layer.provide(harness.layer)), ); const layer = Preparation.layer.pipe( Layer.provideMerge(services), @@ -122,9 +124,9 @@ it.effect( yield* Deferred.await(checkoutStarted); const preparing = yield* threads.getThreadProjection(threadId); assert.equal(preparing.runs[0]!.status, "preparing"); - assert.include(preparing.messages[0]!.text, "Shared goal"); + assert.notInclude(preparing.messages[0]!.text, "Shared goal"); assert.isTrue(preparing.messages[0]!.text.endsWith("Review the code now.")); - assert.isFalse((yield* crews.read("crew:integration"))!.members[0]!.notStarted); + assert.isTrue((yield* crews.read("crew:integration"))!.members[0]!.notStarted); yield* threads.sendToThread({ projectId, threadId, @@ -159,7 +161,108 @@ it.effect( assert.equal(ready.thread.worktreePath, "/repo-worktrees/crew-reviewer"); assert.equal(harness.createWorktree.mock.calls[0]?.[0]?.baseRefName, "main"); assert.lengthOf(harness.createWorktree.mock.calls, 1); + const crewContext = yield* CrewTurnContext.CrewTurnContext; + assert.include( + yield* crewContext.deliver(threadId, ready.messages[0]!.text, Effect.succeed), + "Shared goal", + ); + yield* crews.addMembers("crew:integration", [ + { + seatName: "tester", + agentId: null, + threadId: ThreadId.make("thread:tester"), + participantId: participantIdForThread(ThreadId.make("thread:tester")), + reason: "Test the fix", + }, + ]); + const reordered = yield* threads.sendToThread({ + projectId, + threadId, + commandId: CommandId.make("command:queued-second"), + messageId: MessageId.make("message:queued-second"), + text: "Original second assignment", + attachments: [], + mode: "queue", + createdBy: "user", + creationSource: "web", + }); + const canceled = yield* threads.sendToThread({ + projectId, + threadId, + commandId: CommandId.make("command:queued-cancel"), + messageId: MessageId.make("message:queued-cancel"), + text: "Cancel this assignment", + attachments: [], + mode: "queue", + createdBy: "user", + creationSource: "web", + }); + yield* threads.dispatch({ + type: "queued-run.edit", + commandId: CommandId.make("command:edit-second"), + threadId, + runId: reordered.run.id, + text: "Edited second assignment", + }); + const firstQueued = ready.runs.find((run) => run.status === "queued")!; + yield* threads.dispatch({ + type: "queued-run.reorder", + commandId: CommandId.make("command:reorder-second"), + threadId, + runId: reordered.run.id, + beforeRunId: firstQueued.id, + }); + yield* threads.dispatch({ + type: "queued-run.cancel", + commandId: CommandId.make("command:cancel-third"), + threadId, + runId: canceled.run.id, + }); + const queuedAfterEdits = yield* threads.getThreadProjection(threadId); + assert.equal( + queuedAfterEdits.runs.find((run) => run.id === canceled.run.id)?.status, + "cancelled", + ); + assert.equal( + queuedAfterEdits.messages.find((message) => message.id === reordered.message.id)?.text, + "Edited second assignment", + ); const now = yield* DateTime.now; + yield* (yield* EventSinkV2).write({ + events: ready.runs + .filter((run) => run.status !== "queued") + .map((run) => ({ + id: EventId.make(`event:finish-active:${run.id}`), + type: "run.updated" as const, + threadId, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { + ...run, + status: "completed" as const, + completedAt: now, + queuePosition: null, + }, + })), + }); + yield* threads.dispatch({ + type: "queue.resume", + commandId: CommandId.make("command:resume-reordered"), + threadId, + }); + const selected = yield* threads.getThreadProjection(threadId); + assert.equal(selected.runs.find((run) => run.id === reordered.run.id)?.status, "starting"); + const nextText = selected.messages.find( + (message) => message.id === reordered.message.id, + )!.text; + const prompt = yield* crewContext.deliver(threadId, nextText, Effect.succeed); + assert.include(prompt, "joined: tester:"); + assert.isTrue(prompt.endsWith("Edited second assignment")); + assert.equal( + yield* crewContext.deliver(threadId, "Next assignment", Effect.succeed), + "Next assignment", + ); yield* (yield* EventSinkV2).write({ events: ready.runs.map((run) => ({ id: EventId.make(`event:finished:${run.id}`), @@ -190,7 +293,7 @@ it.effect( assert.equal(reused.message.text, "Review the revision."); assert.equal(reused.run.threadId, threadId); assert.equal(reused.projection.thread.worktreePath, ready.thread.worktreePath); - assert.lengthOf((yield* crews.read("crew:integration"))!.members, 1); + assert.lengthOf((yield* crews.read("crew:integration"))!.members, 2); assert.lengthOf(harness.createWorktree.mock.calls, 1); }).pipe(Effect.provide(layer)); }).pipe(Effect.scoped), diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts index ab511098c2b39..accf617ed9bb3 100644 --- a/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts @@ -1,3 +1,4 @@ +import * as CrewTurnContext from "./CrewTurnContext.ts"; import { assert, it } from "@effect/vitest"; import { CommandId, @@ -116,170 +117,160 @@ const fixture = Effect.gen(function* () { Effect.gen(function* () { return yield* (yield* Orchestrator.OrchestratorV2).dispatch(command); }); - return { sql, crews, commands, receipts, rejected, layer, send }; + const deliveryLayer = CrewTurnContext.layer; + const deliver = (text: string, fail = false) => + Effect.gen(function* () { + return yield* (yield* CrewTurnContext.CrewTurnContext).deliver(seatId, text, (prompt) => + fail ? Effect.fail("provider refused") : Effect.succeed(prompt), + ); + }).pipe(Effect.provide(deliveryLayer)); + return { sql, crews, commands, receipts, rejected, layer, send, deliver }; }); it.effect( - "a direct user message starts a seat with its approved brief, current roster and intact envelope", + "acceptance leaves context owed; provider delivery includes the current roster and original assignment", () => Effect.gen(function* () { const f = yield* fixture; + const command = assignment("direct", "user"); + yield* f.send(command).pipe(Effect.provide(f.layer)); + assert.isTrue((yield* f.crews.read("crew:test"))!.members[0]!.notStarted); + assert.deepStrictEqual((yield* Ref.get(f.commands))[0], command); yield* f.crews.addMembers("crew:test", [member("security")]); yield* f.crews.removeMembers("crew:test", ["builder"]); - const command = assignment("direct", "user"); + const prompt = yield* f.deliver(command.text); + assert.include(prompt, "\nShared goal\n"); + assert.include(prompt, "Review carefully."); + assert.include(prompt, "- security:"); + assert.notInclude(prompt, "- builder:"); + assert.isTrue(prompt.endsWith(command.text)); + assert.isFalse((yield* f.crews.read("crew:test"))!.members[0]!.notStarted); + }).pipe(Effect.provide(base)), +); + +it.effect( + "worktree assignments use durable preparation without storing context in editable text", + () => + Effect.gen(function* () { + const f = yield* fixture; + yield* f.sql`UPDATE j5_crew_seat_context SET workspace = '{"type":"worktree","baseRef":"j5/main"}'`; + const command = assignment("playbook", "system"); yield* f.send(command).pipe(Effect.provide(f.layer)); const [delivered] = yield* Ref.get(f.commands); - assert.equal(delivered?.type, "message.dispatch"); - if (delivered?.type !== "message.dispatch") return; - assert.include(delivered.text, "\nShared goal\n"); - assert.include(delivered.text, "Review carefully."); - assert.include( - delivered.text, - `- security: participant_id=${member("security").participantId} persona=custom responsibility=Responsibility of security`, - ); - assert.notInclude(delivered.text, "- builder:"); - assert.notInclude(delivered.text, ""); - assert.isTrue(delivered.text.endsWith(command.text)); - assert.equal(delivered.messageId, command.messageId); - assert.equal(delivered.senderThreadId, command.senderThreadId); - assert.equal(delivered.createdBy, "user"); - assert.isFalse((yield* f.crews.read("crew:test"))!.members[0]!.notStarted); + if (delivered?.type !== "message.dispatch") return assert.fail("missing assignment"); + assert.deepStrictEqual(delivered.dispatchMode, { + type: "defer_start", + workspaceStrategy: { type: "worktree", baseRef: "j5/main" }, + }); + assert.equal(delivered.text, command.text); }).pipe(Effect.provide(base)), ); -it.effect("playbook deliveries activate a new-worktree seat through durable preparation", () => +it.effect("provider refusal keeps the introduction and roster changes owed", () => Effect.gen(function* () { const f = yield* fixture; - yield* f.sql`UPDATE j5_crew_seat_context SET workspace = '{"type":"worktree","baseRef":"j5/main"}'`; - yield* f - .send({ ...assignment("playbook", "system"), text: "\nDo the review" }) - .pipe(Effect.provide(f.layer)); - const [delivered] = yield* Ref.get(f.commands); - if (delivered?.type !== "message.dispatch") return assert.fail("missing assignment"); - assert.deepStrictEqual(delivered.dispatchMode, { - type: "defer_start", - workspaceStrategy: { type: "worktree", baseRef: "j5/main" }, - }); - assert.include(delivered.text, "Shared goal"); - assert.isTrue(delivered.text.endsWith("\nDo the review")); + assert.equal((yield* f.deliver("first", true).pipe(Effect.result))._tag, "Failure"); + assert.include(yield* f.deliver("retry"), ""); + yield* f.crews.addMembers("crew:test", [member("security")]); + yield* f.crews.removeMembers("crew:test", ["builder"]); + yield* f.deliver("refused update", true).pipe(Effect.result); + const prompt = yield* f.deliver("accepted update"); + assert.include(prompt, "joined: security:"); + assert.include(prompt, "left: builder:"); + assert.notInclude(prompt, "spawner_brief"); + assert.equal(yield* f.deliver("later"), "later"); }).pipe(Effect.provide(base)), ); -it.effect("finished members get only their next assignment and net roster changes, once", () => - Effect.gen(function* () { - const f = yield* fixture; - yield* Effect.gen(function* () { - yield* f.send(assignment("first")); +it.effect( + "queued edits, cancellation and reordering cannot consume or reorder roster changes", + () => + Effect.gen(function* () { + const f = yield* fixture; + yield* f.deliver("first"); yield* f.crews.addMembers("crew:test", [member("temporary")]); + yield* f.send(assignment("queued-first")).pipe(Effect.provide(f.layer)); yield* f.crews.removeMembers("crew:test", ["temporary", "builder"]); yield* f.crews.addMembers("crew:test", [member("security")]); - assert.lengthOf(yield* Ref.get(f.commands), 1); - yield* f.send(assignment("second")); - yield* f.send(assignment("third")); - yield* f.send(assignment("third")); - }).pipe(Effect.provide(f.layer)); - const delivered = (yield* Ref.get(f.commands)).filter( - (command) => command.type === "message.dispatch", - ); - assert.lengthOf(delivered, 3); - assert.isTrue( - delivered[1]!.text.startsWith("\n"), - ); - assert.include(delivered[1]!.text, "joined: security:"); - assert.include(delivered[1]!.text, "left: builder:"); - assert.notInclude(delivered[1]!.text, "temporary"); - assert.notInclude(delivered[1]!.text, "spawner_brief"); - assert.equal(delivered[2]!.text, assignment("third").text); - }).pipe(Effect.provide(base)), -); - -it.effect("concurrent first assignments introduce a seat only once", () => - Effect.gen(function* () { - const f = yield* fixture; - yield* Effect.all([f.send(assignment("one")), f.send(assignment("two"))], { - concurrency: "unbounded", - }).pipe(Effect.provide(f.layer)); - const commands = (yield* Ref.get(f.commands)).filter( - (command) => command.type === "message.dispatch", - ); - assert.lengthOf( - commands.filter((command) => command.text.includes("")), - 1, - ); - assert.lengthOf(commands, 2); - }).pipe(Effect.provide(base)), -); - -it.effect("a rejected assignment leaves the introduction owed to the next assignment", () => - Effect.gen(function* () { - const f = yield* fixture; - f.rejected.add("command:refused"); - yield* Effect.gen(function* () { - yield* f.send(assignment("refused")).pipe(Effect.result); - yield* f.crews.addMembers("crew:test", [member("security")]); - yield* f.send(assignment("accepted")); - }).pipe(Effect.provide(f.layer)); - const [delivered] = yield* Ref.get(f.commands); - if (delivered?.type !== "message.dispatch") return assert.fail("missing assignment"); - assert.include(delivered.text, ""); - assert.include(delivered.text, "- security:"); - }).pipe(Effect.provide(base)), + yield* f.send(assignment("queued-second")).pipe(Effect.provide(f.layer)); + // The provider sees whichever editable message upstream selects, not acceptance order. + const prompt = yield* f.deliver("edited second assignment promoted first"); + assert.include(prompt, "joined: security:"); + assert.include(prompt, "left: builder:"); + assert.notInclude(prompt, "temporary"); + assert.isTrue(prompt.endsWith("edited second assignment promoted first")); + assert.equal(yield* f.deliver("remaining assignment"), "remaining assignment"); + }).pipe(Effect.provide(base)), ); it.effect( - "a committed first assignment is recovered after a crash without repeating its introduction", + "an archived waiting seat cannot bypass workspace preparation when independently reopened", () => Effect.gen(function* () { const f = yield* fixture; - // Simulate the cut between the orchestration commit and J5's delivered-roster write. - yield* f.sql`UPDATE j5_crew_seat_context SET pending_command_id = 'command:first', pending_roster = '[]'`; - f.receipts.set("command:first", { status: "accepted" } as CommandReceiptV2); - yield* f.send(assignment("later")).pipe(Effect.provide(f.layer)); - const [delivered] = yield* Ref.get(f.commands); - if (delivered?.type !== "message.dispatch") return assert.fail("missing assignment"); - assert.notInclude(delivered.text, ""); - assert.include(delivered.text, ""); + yield* f.sql`UPDATE j5_crew_seat_context SET workspace = '{"type":"worktree","baseRef":"main"}'`; + yield* f.crews.markArchived("crew:test", "2026-10-27T13:00:00Z"); + const result = yield* f + .send(assignment("after-archive")) + .pipe(Effect.result, Effect.provide(f.layer)); + assert.equal(result._tag, "Failure"); + assert.lengthOf(yield* Ref.get(f.commands), 0); + assert.equal((yield* f.deliver("bypass", false).pipe(Effect.result))._tag, "Failure"); }).pipe(Effect.provide(base)), ); it.effect( - "follow-up work is refused after a worktree preparation failed instead of running in the project root", + "a retired started seat still cannot run in the project root after worktree failure", () => Effect.gen(function* () { const f = yield* fixture; yield* f.sql`UPDATE j5_crew_seat_context SET delivered_roster = '[]', workspace = '{"type":"worktree","baseRef":"main"}'`; + yield* f.crews.markArchived("crew:test", "2026-10-27T13:00:00Z"); const result = yield* f .send(assignment("after-failed-preparation")) .pipe(Effect.result, Effect.provide(f.layer)); assert.equal(result._tag, "Failure"); - if (result._tag === "Failure") - assert.include(result.failure.message, "Retry workspace preparation"); assert.lengthOf(yield* Ref.get(f.commands), 0); }).pipe(Effect.provide(base)), ); it.effect( - "direct human assignments keep their author attribution and displayed words after activation and replay", + "direct human assignments preserve author prefixes without any author write or subscription invalidation", () => Effect.gen(function* () { const f = yield* fixture; const authorPrefix = "[Message from Bryant (owner)]\n\n"; const command = { ...assignment("authored", "user"), text: authorPrefix + "Review the fix." }; - yield* f.sql`INSERT INTO j5_a2a_message_author - (thread_id, message_id, person_id, display_name, level, stored_prefix, created_at) + yield* f.sql`INSERT INTO j5_a2a_message_author (thread_id, message_id, person_id, display_name, level, stored_prefix, created_at) VALUES (${seatId}, ${command.messageId}, 'human:owner', 'Bryant', 'owner', ${authorPrefix}, '2026-10-27T12:00:00Z')`; - yield* Effect.gen(function* () { - yield* f.send(command); - yield* f.send(command); - }).pipe(Effect.provide(f.layer)); - const [author] = yield* f.sql<{ readonly stored_prefix: string; readonly person_id: string }>` - SELECT stored_prefix, person_id FROM j5_a2a_message_author WHERE message_id = ${command.messageId} - `; - const [delivered] = yield* Ref.get(f.commands); - if (delivered?.type !== "message.dispatch") return assert.fail("missing assignment"); - assert.equal(author!.person_id, "human:owner"); - assert.isTrue(delivered.text.startsWith(author!.stored_prefix)); - assert.equal(delivered.text.slice(author!.stored_prefix.length), "Review the fix."); - assert.lengthOf(yield* Ref.get(f.commands), 1); + yield* f.send(command).pipe(Effect.provide(f.layer)); + const prompt = yield* f.deliver(command.text); + const [author] = yield* f.sql<{ + readonly stored_prefix: string; + }>`SELECT stored_prefix FROM j5_a2a_message_author WHERE message_id = ${command.messageId}`; + assert.equal(author!.stored_prefix, authorPrefix); + assert.isTrue(prompt.endsWith(command.text)); + assert.deepStrictEqual((yield* Ref.get(f.commands))[0], command); }).pipe(Effect.provide(base)), ); + +it.effect("an accepted command still replays after its waiting Crew retires", () => + Effect.gen(function* () { + const f = yield* fixture; + const command = assignment("replay"); + yield* f.send(command).pipe(Effect.provide(f.layer)); + yield* f.crews.markArchived("crew:test", "2026-10-27T13:00:00Z"); + yield* f.send(command).pipe(Effect.provide(f.layer)); + assert.lengthOf(yield* Ref.get(f.commands), 1); + }).pipe(Effect.provide(base)), +); + +it.effect("a retired member that already started continues as a plain agent", () => + Effect.gen(function* () { + const f = yield* fixture; + yield* f.deliver("first"); + yield* f.crews.markArchived("crew:test", "2026-10-27T13:00:00Z"); + yield* f.send(assignment("after-retirement")).pipe(Effect.provide(f.layer)); + assert.equal(yield* f.deliver("new assignment"), "new assignment"); + }).pipe(Effect.provide(base)), +); diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.ts index 9ba5cbb91ae3b..c2b6bd0ada7e0 100644 --- a/apps/server/src/j5/a2a/CrewDeliveryContext.ts +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.ts @@ -1,5 +1,5 @@ -import { CommandId, ThreadId, type OrchestrationV2ServerCommand } from "@t3tools/contracts"; -import { CrewSeatWorkspace, crewDeliveryContextPrefix } from "@t3tools/contracts/j5"; +import { ThreadId } from "@t3tools/contracts"; +import { CrewSeatWorkspace } from "@t3tools/contracts/j5"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -10,9 +10,7 @@ import * as KeyedLock from "@t3tools/shared/KeyedLock"; import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts"; import { CommandReceiptStoreV2 } from "../../orchestration-v2/CommandReceiptStore.ts"; import * as Crews from "./AgentCrewInstanceService.ts"; -import * as ReadChanges from "./ReadChanges.ts"; import { participantIdForThread } from "./HomeRegistrar.ts"; -import { crewContextText } from "./spawnIds.ts"; class CrewSeatWorkspaceNotReadyError extends Orchestrator.OrchestratorDispatchError.extend( "CrewSeatWorkspaceNotReadyError", @@ -21,173 +19,78 @@ class CrewSeatWorkspaceNotReadyError extends Orchestrator.OrchestratorDispatchEr return "This Crew seat's worktree is not ready. Retry workspace preparation in its thread before sending more work."; } } -const isWorkspaceNotReady = Schema.is(CrewSeatWorkspaceNotReadyError); -const Roster = Schema.fromJsonString( - Schema.Array( - Schema.Struct({ - seat: Schema.String, - participantId: Schema.String, - agentDisplayName: Schema.String, - reason: Schema.NullOr(Schema.String), - }), - ), -); -const encodeRoster = Schema.encodeSync(Roster); -const isOrchestratorError = Schema.is(Orchestrator.OrchestratorV2Error); -const decodeRoster = Schema.decodeUnknownEffect(Roster); -const decodeWorkspace = Schema.decodeUnknownEffect(Schema.fromJsonString(CrewSeatWorkspace)); -const line = (value: string) => value.replace(/\s+/g, " ").replace(/<\//g, "<\\/").trim(); - -interface SeatContextRow { - readonly first_turn_text: string; - readonly workspace: string; - readonly delivered_roster: string | null; - readonly pending_command_id: string | null; - readonly pending_roster: string | null; - readonly pending_message_id: string | null; - readonly pending_prefix: string | null; +class CrewSeatInactiveError extends Orchestrator.OrchestratorDispatchError.extend( + "CrewSeatInactiveError", +)({ threadId: ThreadId }) { + override get message(): string { + return "Restore this waiting member's Crew before sending its first assignment."; + } } -/** All message entry points meet here, before upstream commits the assignment and starts work. */ +const decodeWorkspace = Schema.decodeUnknownEffect(Schema.fromJsonString(CrewSeatWorkspace)); +const isDispatchError = Schema.is( + Schema.Union([ + Orchestrator.OrchestratorV2Error, + CrewSeatWorkspaceNotReadyError, + CrewSeatInactiveError, + ]), +); + +/** Workspace preparation belongs to acceptance; Crew context belongs to provider delivery. */ export const layer = Layer.effect( Orchestrator.OrchestratorV2, Effect.gen(function* () { const inner = yield* Orchestrator.OrchestratorV2; const sql = yield* SqlClient.SqlClient; - const crews = yield* Crews.AgentCrewInstanceService; const receipts = yield* CommandReceiptStoreV2; - const changes = yield* ReadChanges.ReadChanges; + const crews = yield* Crews.AgentCrewInstanceService; const locks = yield* KeyedLock.make(); - - const acknowledge = ( - threadId: string, - roster: string | null, - messageId: string | null, - prefix: string, - ) => - sql.withTransaction( - Effect.gen(function* () { - if (prefix !== "" && messageId !== null) - yield* sql` - UPDATE j5_a2a_message_author SET stored_prefix = ${prefix} || stored_prefix - WHERE thread_id = ${threadId} AND message_id = ${messageId} - `; - yield* sql` - UPDATE j5_crew_seat_context SET delivered_roster = ${roster}, - pending_command_id = NULL, pending_roster = NULL, pending_message_id = NULL, - pending_prefix = NULL WHERE thread_id = ${threadId} - `; - }), - ); - const dispatch: Orchestrator.OrchestratorV2["Service"]["dispatch"] = (command) => { if (command.type !== "message.dispatch") return inner.dispatch(command); return locks.withLock( command.threadId, Effect.gen(function* () { - const rows = yield* sql` - SELECT * FROM j5_crew_seat_context WHERE thread_id = ${command.threadId} - `; - const context = rows[0]; + if (Option.isSome(yield* receipts.getByCommandId(command.commandId))) + return yield* inner.dispatch(command); + const [context] = yield* sql<{ + readonly workspace: string; + readonly delivered_roster: string | null; + }>` + SELECT workspace, delivered_roster FROM j5_crew_seat_context WHERE thread_id = ${command.threadId} + `; if (context === undefined) return yield* inner.dispatch(command); - // A dispatch may have committed before the process stopped, leaving only this bookkeeping owed. - let deliveredRoster = context.delivered_roster; - if (context.pending_command_id !== null) { - const receipt = yield* receipts.getByCommandId( - CommandId.make(context.pending_command_id), - ); - if (Option.isSome(receipt) && receipt.value.status === "accepted") { - deliveredRoster = context.pending_roster; - yield* acknowledge( - command.threadId, - deliveredRoster, - context.pending_message_id, - context.pending_prefix ?? "", - ); - if (context.delivered_roster === null) yield* changes.notify("crew", "fleet"); - } - } - const replay = yield* receipts.getByCommandId(command.commandId); - if (Option.isSome(replay)) return yield* inner.dispatch(command); - const membership = yield* crews.findMembership(participantIdForThread(command.threadId)); - if (membership === null) return yield* inner.dispatch(command); - const crew = yield* crews.read(membership.crewInstanceId); - if (crew === null) return yield* inner.dispatch(command); - const roster = crew.members.map((member) => ({ - seat: member.seatName, - participantId: member.participantId, - agentDisplayName: member.agentId ?? "custom", - reason: member.reason, - })); - const rosterJson = encodeRoster(roster); - let prefix = ""; - if (deliveredRoster === null) { - prefix = context.first_turn_text.replace( - /[\s\S]*?<\/j5_crew_context>/, - () => - crewContextText({ - displayName: crew.displayName, - instanceId: crew.id, - seatName: membership.seatName, - captainParticipantId: crew.captainParticipantId, - roster, - }), - ); - } else { - const previous = yield* decodeRoster(deliveredRoster); - const joined = roster.filter( - (member) => !previous.some((old) => old.participantId === member.participantId), - ); - const left = previous.filter( - (member) => !roster.some((current) => current.participantId === member.participantId), - ); - const describe = (member: (typeof Roster.Type)[number]) => - `${line(member.seat)}: participant_id=${member.participantId} responsibility=${line(member.reason ?? "")}`; - if (joined.length > 0 || left.length > 0) - prefix = [ - "", - ...joined.map((member) => `joined: ${describe(member)}`), - ...left.map((member) => `left: ${describe(member)}`), - "", - ].join("\n"); + if ( + context.delivered_roster === null && + (yield* crews.findMembership(participantIdForThread(command.threadId))) === null + ) { + return yield* new CrewSeatInactiveError({ + threadId: command.threadId, + commandId: command.commandId, + commandType: command.type, + }); } const workspace = yield* decodeWorkspace(context.workspace); - if (deliveredRoster !== null && workspace.type === "worktree") { - const shell = yield* inner.getThreadShell(command.threadId); - if (shell !== null && shell.worktreePath === null) { - const projection = yield* inner.getThreadRecords(command.threadId, ["runs"]); - if (!projection.runs.some((run) => run.status === "preparing")) { - return yield* new CrewSeatWorkspaceNotReadyError({ - threadId: command.threadId, - commandId: command.commandId, - commandType: command.type, - }); - } - } + if (workspace.type !== "worktree") return yield* inner.dispatch(command); + const shell = yield* inner.getThreadShell(command.threadId); + if (shell === null || shell.worktreePath !== null) return yield* inner.dispatch(command); + const projection = yield* inner.getThreadRecords(command.threadId, ["runs"]); + if (projection.runs.some((run) => run.status === "preparing")) + return yield* inner.dispatch(command); + if (projection.runs.length > 0 || context.delivered_roster !== null) { + return yield* new CrewSeatWorkspaceNotReadyError({ + threadId: command.threadId, + commandId: command.commandId, + commandType: command.type, + }); } - if (deliveredRoster === rosterJson) return yield* inner.dispatch(command); - prefix = crewDeliveryContextPrefix(prefix); - const prepared: OrchestrationV2ServerCommand = { + return yield* inner.dispatch({ ...command, - text: prefix === "" ? command.text : `${prefix}${command.text}`, - ...(deliveredRoster === null && workspace.type === "worktree" - ? { dispatchMode: { type: "defer_start" as const, workspaceStrategy: workspace } } - : {}), - }; - yield* sql` - UPDATE j5_crew_seat_context SET pending_command_id = ${command.commandId}, - pending_roster = ${rosterJson}, pending_message_id = ${command.messageId}, - pending_prefix = ${prefix} WHERE thread_id = ${command.threadId} - `; - // Acceptance owns this context even if provider startup fails; retries keep the stored message. - const result = yield* inner.dispatch(prepared); - yield* acknowledge(command.threadId, rosterJson, command.messageId, prefix); - if (deliveredRoster === null) yield* changes.notify("crew", "fleet"); - return result; + dispatchMode: { type: "defer_start", workspaceStrategy: workspace }, + }); }).pipe( Effect.mapError((cause) => - isOrchestratorError(cause) || isWorkspaceNotReady(cause) + isDispatchError(cause) ? cause : new Orchestrator.OrchestratorDispatchError({ commandId: command.commandId, @@ -200,4 +103,4 @@ export const layer = Layer.effect( }; return Orchestrator.OrchestratorV2.of({ ...inner, dispatch }); }), -).pipe(Layer.provide(Crews.layer), Layer.provide(ReadChanges.layer)); +).pipe(Layer.provide(Crews.layer)); diff --git a/apps/server/src/j5/a2a/CrewProposalService.test.ts b/apps/server/src/j5/a2a/CrewProposalService.test.ts index 42d17cd0cf7e5..ca977b5416857 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.test.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.test.ts @@ -21,7 +21,6 @@ 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 * as SqlClient from "effect/sql/SqlClient"; import { SqlError, UnknownError } from "effect/sql/SqlError"; import { stringify } from "yaml"; diff --git a/apps/server/src/j5/a2a/CrewTurnContext.ts b/apps/server/src/j5/a2a/CrewTurnContext.ts new file mode 100644 index 0000000000000..2f129026a0bfc --- /dev/null +++ b/apps/server/src/j5/a2a/CrewTurnContext.ts @@ -0,0 +1,153 @@ +import { ThreadId } from "@t3tools/contracts"; +import { crewDeliveryAssignment, crewDeliveryContextPrefix } from "@t3tools/contracts/j5"; +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 * as Crews from "./AgentCrewInstanceService.ts"; +import * as ReadChanges from "./ReadChanges.ts"; +import { participantIdForThread } from "./HomeRegistrar.ts"; +import { crewContextText } from "./spawnIds.ts"; + +class CrewTurnContextError extends Schema.TaggedError()( + "CrewTurnContextError", + { + threadId: ThreadId, + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message() { + return "Cannot deliver this Crew seat's context. Restore its Crew before starting a waiting member."; + } +} + +const isCrewTurnContextError = Schema.is(CrewTurnContextError); + +export class CrewTurnContext extends Context.Service< + CrewTurnContext, + { + readonly deliver: ( + threadId: ThreadId, + text: string, + send: (text: string) => Effect.Effect, + ) => Effect.Effect; + } +>()("t3/j5/a2a/CrewTurnContext") {} + +const Roster = Schema.fromJsonString( + Schema.Array( + Schema.Struct({ + seat: Schema.String, + participantId: Schema.String, + agentDisplayName: Schema.String, + reason: Schema.NullOr(Schema.String), + }), + ), +); +const encodeRoster = Schema.encodeSync(Roster); +const decodeRoster = Schema.decodeUnknownEffect(Roster); +const line = (value: string) => value.replace(/\s+/g, " ").replace(/<\//g, "<\\/").trim(); + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const crews = yield* Crews.AgentCrewInstanceService; + const changes = yield* ReadChanges.ReadChanges; + const prepare = Effect.fn("j5.crewTurnContext.prepare")(function* (threadId: ThreadId) { + return yield* Effect.gen(function* () { + const [context] = yield* sql<{ + readonly first_turn_text: string; + readonly delivered_roster: string | null; + }>` + SELECT first_turn_text, delivered_roster FROM j5_crew_seat_context WHERE thread_id = ${threadId} + `; + if (context === undefined) return null; + const membership = yield* crews.findMembership(participantIdForThread(threadId)); + if (membership === null) { + if (context.delivered_roster === null) return yield* new CrewTurnContextError({ threadId }); + return null; + } + const crew = yield* crews.read(membership.crewInstanceId); + if (crew === null) return yield* new CrewTurnContextError({ threadId }); + const roster = crew.members.map((member) => ({ + seat: member.seatName, + participantId: member.participantId, + agentDisplayName: member.agentId ?? "custom", + reason: member.reason, + })); + const rosterJson = encodeRoster(roster); + let prefix = ""; + if (context.delivered_roster === null) { + prefix = context.first_turn_text.replace( + /[\s\S]*?<\/j5_crew_context>/, + () => + crewContextText({ + displayName: crew.displayName, + instanceId: crew.id, + seatName: membership.seatName, + captainParticipantId: crew.captainParticipantId, + roster, + }), + ); + } else { + const previous = yield* decodeRoster(context.delivered_roster); + const joined = roster.filter( + (member) => !previous.some((old) => old.participantId === member.participantId), + ); + const left = previous.filter( + (member) => !roster.some((current) => current.participantId === member.participantId), + ); + const describe = (member: (typeof Roster.Type)[number]) => + `${line(member.seat)}: participant_id=${member.participantId} responsibility=${line(member.reason ?? "")}`; + if (joined.length > 0 || left.length > 0) + prefix = [ + "", + ...joined.map((member) => `joined: ${describe(member)}`), + ...left.map((member) => `left: ${describe(member)}`), + "", + ].join("\n"); + } + + return { + prefix: crewDeliveryContextPrefix(prefix), + delivered: sql` + UPDATE j5_crew_seat_context SET delivered_roster = ${rosterJson}, + pending_command_id = NULL, pending_roster = NULL, pending_message_id = NULL, pending_prefix = NULL + WHERE thread_id = ${threadId} + `.pipe( + Effect.andThen(changes.notify("crew", "fleet")), + Effect.asVoid, + Effect.mapError((cause) => new CrewTurnContextError({ threadId, cause })), + ), + }; + }).pipe( + Effect.mapError((cause) => + isCrewTurnContextError(cause) ? cause : new CrewTurnContextError({ threadId, cause }), + ), + ); + }); + const deliver = ( + threadId: ThreadId, + text: string, + send: (text: string) => Effect.Effect, + ) => + Effect.gen(function* () { + const context = yield* prepare(threadId); + if (context === null) return yield* send(text); + const result = yield* send(`${context.prefix}${crewDeliveryAssignment(text)}`); + // The provider accepted the prompt; bookkeeping failure must not fail its running turn. + yield* context.delivered.pipe( + Effect.catch((cause) => + Effect.logWarning("Failed to record delivered Crew context", { threadId, cause }), + ), + ); + return result; + }); + return CrewTurnContext.of({ deliver }); +}); + +export const layer = Layer.effect(CrewTurnContext, make).pipe( + Layer.provide(Crews.layer), + Layer.provide(ReadChanges.layer), +); diff --git a/apps/server/src/j5/a2a/Migrations.test.ts b/apps/server/src/j5/a2a/Migrations.test.ts index 10d14adc98763..64bd7ef76f419 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -1442,7 +1442,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, 47, 48, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, ], ); const memberColumns = yield* sql<{ readonly name: string }>` diff --git a/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts index 1e834bfb5b883..d4698ceaa18b3 100644 --- a/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts +++ b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts @@ -15,7 +15,7 @@ it.effect( "existing members retain their observed roster and are not introduced again after migration", () => Effect.gen(function* () { - yield* runJ5A2AMigrations({ toMigrationInclusive: 47 }); + yield* runJ5A2AMigrations({ toMigrationInclusive: 48 }); const sql = yield* SqlClient.SqlClient; yield* sql`INSERT INTO j5_a2a_project_ledger (project_id, created_at) VALUES ('project:test', '2026-10-27')`; yield* sql`INSERT INTO j5_agent_crew_instance diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 660c595c5f983..c2ab2e4a441f0 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -1,3 +1,4 @@ +import * as CrewTurnContext from "../j5/a2a/CrewTurnContext.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it, vi } from "vite-plus/test"; import { it as effectIt } from "@effect/vitest"; @@ -1096,6 +1097,8 @@ const makeCodexResumeSchemaFailure = Effect.fn("makeCodexResumeSchemaFailure")(f * start writes is applied to one projection, as the store would. */ function makeNativeResumeHarness(input: { + readonly crewDelivery?: CrewTurnContext.CrewTurnContext["Service"]; + readonly keepNativeThread?: boolean; readonly text?: string; readonly resumeThread: ( ids: NativeResumeIds, @@ -1141,7 +1144,10 @@ function makeNativeResumeHarness(input: { projection = ProjectionStore.applyToProjection(projection, event); } }; - const resumeThread = vi.fn(() => input.resumeThread(ids)); + const resumeThread = vi.fn(() => + input.keepNativeThread === true ? Effect.succeed(providerThread) : input.resumeThread(ids), + ); + const nativeStartTurn = vi.fn((_turn: ProviderAdapter.ProviderAdapterV2TurnInput) => Effect.void); const ensureThread = vi.fn( (_load: { readonly existingProviderThread?: { readonly nativeThreadRef: unknown } }) => Effect.succeed({ @@ -1149,7 +1155,9 @@ function makeNativeResumeHarness(input: { nativeThreadRef: { ...nativeThreadRef, nativeId: "native-replacement" }, }), ); - const startRootRun = vi.fn(() => Effect.void); + const startRootRun = vi.fn< + (input: RunExecutionService.RunExecutionServiceV2StartRootRunInput) => Effect.Effect + >(() => Effect.void); const projectionRead = () => Effect.sync(() => ({ ...projection, @@ -1160,6 +1168,11 @@ function makeNativeResumeHarness(input: { ), })); const layer = ProviderTurnStart.layer.pipe( + Layer.provide( + input.crewDelivery === undefined + ? Layer.empty + : Layer.succeed(CrewTurnContext.CrewTurnContext, input.crewDelivery), + ), Layer.provide( Layer.mergeAll( Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({ @@ -1223,6 +1236,7 @@ function makeNativeResumeHarness(input: { }, resumeThread, ensureThread, + startTurn: nativeStartTurn, } as never), }), Layer.mock(ProviderAuthService.ProviderAuthService)({ @@ -1242,6 +1256,7 @@ function makeNativeResumeHarness(input: { resumeThread, ensureThread, startRootRun, + nativeStartTurn, events, projection: () => projection, start: (options?: { readonly willRetry: boolean }) => @@ -1496,3 +1511,40 @@ effectIt.effect("reports a start failure to the run watchdog without replacing i ); }), ); + +effectIt.effect( + "delivers Crew context without a history handoff and acknowledges after provider acceptance", + () => + Effect.gen(function* () { + const order: string[] = []; + const harness = makeNativeResumeHarness({ + text: "Review the code.", + keepNativeThread: true, + resumeThread: () => Effect.die("retained native conversation"), + crewDelivery: { + deliver: (_threadId, text, send) => + Effect.gen(function* () { + order.push("context"); + const result = yield* send(`Crew introduction\n\n${text}`); + order.push("accepted"); + return result; + }), + }, + }); + harness.nativeStartTurn.mockImplementation(() => + Effect.sync(() => { + order.push("provider"); + }), + ); + yield* harness.start(); + expect(harness.projection().contextHandoffs).toEqual([]); + const requested = harness.startRootRun.mock.calls[0]![0]; + yield* requested.session.startTurn({ + message: { text: "Review the code.", attachments: [] }, + } as never); + expect(harness.nativeStartTurn.mock.calls[0]![0].message.text).toBe( + "Crew introduction\n\nReview the code.", + ); + expect(order).toEqual(["context", "provider", "accepted"]); + }), +); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 12e81109584c2..d76e3a4dc8de9 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1,3 +1,4 @@ +import * as CrewTurnContext from "../j5/a2a/CrewTurnContext.ts"; import { modelSelectionsEqual } from "@t3tools/shared/model"; import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; import { @@ -116,6 +117,7 @@ export const layer: Layer.Layer< ProviderTurnStartServiceV2, Effect.gen(function* () { const eventSink = yield* EventSink.EventSinkV2; + const crewTurnContext = yield* Effect.serviceOption(CrewTurnContext.CrewTurnContext); const queuedRunWatchdog = yield* QueuedRunWatchdog; const contextHandoffService = yield* ContextHandoffService.ContextHandoffServiceV2; const idAllocator = yield* IdAllocator.IdAllocatorV2; @@ -1132,9 +1134,10 @@ export const layer: Layer.Layer< !coveredItemIds.has(item.id) && historicalMessage(item) !== null, ); - const startWithHandoffs = ( + const startAssignmentWithHandoffs = ( turnInput: Parameters[0], - compact = false, + compact: boolean, + assignment: string, ) => Effect.gen(function* () { const retryHandoff = @@ -1167,7 +1170,7 @@ export const layer: Layer.Layer< return handoffBudget({ tokenCap, modelContextWindow, - userText: restartNote === "" ? userText : `${restartNote}\n\n${userText}`, + userText: restartNote === "" ? assignment : `${restartNote}\n\n${assignment}`, attachments: message.attachments, providerThread: budgetProviderThread, nativeContextEstimate: @@ -1216,7 +1219,7 @@ export const layer: Layer.Layer< ...(noteContinuation ? promptedInput : turnInput), message: { ...turnInput.message, - text: context === "" ? userText : `${context}\n\nUser message:\n${userText}`, + text: context === "" ? assignment : `${context}\n\nUser message:\n${assignment}`, }, }).pipe( // A pending marker would make the next turn abandon this native @@ -1243,7 +1246,17 @@ export const layer: Layer.Layer< }), ), ); - }).pipe( + }); + const startWithHandoffs = ( + turnInput: Parameters[0], + compact = false, + ) => + (Option.isSome(crewTurnContext) + ? crewTurnContext.value.deliver(projection.thread.id, userText, (assignment) => + startAssignmentWithHandoffs(turnInput, compact, assignment), + ) + : startAssignmentWithHandoffs(turnInput, compact, userText) + ).pipe( Effect.mapError((cause) => cause._tag === "ProviderAdapterTurnStartError" ? cause @@ -1260,7 +1273,8 @@ export const layer: Layer.Layer< effectiveHandoffs.length === 0 && missedItems.length === 0 && restartNote === "" && - !noteContinuation + !noteContinuation && + Option.isNone(crewTurnContext) ? session : makeDeliverySession(session, startWithHandoffs); return runExecution.startRootRun({ diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 82282352571c6..b7bb4acc5f12d 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -1,3 +1,4 @@ +import * as CrewTurnContext from "../j5/a2a/CrewTurnContext.ts"; import * as CrewDeliveryContext from "../j5/a2a/CrewDeliveryContext.ts"; import * as UsageLimitRecoveryWorker from "./UsageLimitRecoveryWorker.ts"; import * as Scheduler from "../scheduling/Scheduler.ts"; @@ -171,6 +172,7 @@ const layerRunExecutionServiceProvided = RunExecutionService.layer.pipe( ); const layerProviderTurnStartServiceProvided = ProviderTurnStartService.layer.pipe( + Layer.provide(CrewTurnContext.layer), Layer.provide( Layer.mergeAll( layerContextHandoffServiceProvided, diff --git a/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx b/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx index c1e5cbae87d6d..ccccf8e02a3fa 100644 --- a/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx +++ b/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx @@ -842,3 +842,16 @@ it("preserves an activating assignment's sender and reply obligation beneath Cre rawEnvelope: text, }); }); + +describe("Crew context in queued envelopes", () => { + it("keeps the sender and preview body when an older delivery carries Crew context", () => { + const wrapped = crewDeliveryContextPrefix("private Crew context") + peerRaw; + expect( + formatThreadA2AQueuedDelivery(wrapped, new Map([["agent:delivery-sender", "Alice"]])), + ).toEqual({ + label: "From Alice — Please verify the worker.", + tooltipParticipantId: null, + }); + expect(participantIdsForThreadA2AEnvelope(wrapped)).toEqual(["agent:delivery-sender"]); + }); +}); diff --git a/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx b/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx index 2ed87aed341b3..e4b383920fbf8 100644 --- a/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx +++ b/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx @@ -452,7 +452,7 @@ export function formatThreadA2AQueuedDelivery( text: string, participantLabels: ReadonlyMap, ): { readonly label: string; readonly tooltipParticipantId: string | null } | null { - const peer = parseAgentAuthoredEnvelope(text); + const peer = parseAgentAuthoredEnvelope(crewDeliveryAssignment(text)); if (peer === null) return null; const sender = presentParticipantIdentity({ participantId: peer.senderId, participantLabels }); const firstLine = peer.body.split("\n")[0]?.trim() ?? ""; @@ -463,7 +463,7 @@ export function formatThreadA2AQueuedDelivery( } export function participantIdsForThreadA2AEnvelope(text: string): ReadonlyArray { - const peer = parseAgentAuthoredEnvelope(text); + const peer = parseAgentAuthoredEnvelope(crewDeliveryAssignment(text)); return peer === null ? [] : [peer.senderId]; } diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index 44d5f80844f97..07bfde5a672b9 100644 --- a/docs/j5/product/features/crews.md +++ b/docs/j5/product/features/crews.md @@ -11,7 +11,7 @@ Complex work needs a group of agents with defined jobs working together with a h ## Definition -A **Crew** is a group of agents launched as a unit from a **roster its Captain proposes, approved by the person by default**, composed for the brief in front of it. Nobody writes a Crew file in advance. The person asks the agent in an ordinary conversation to compose a Crew (web and desktop). The agent uses the conversation as context, keeps its current persona, model, and policy, and proposes the team before starting its work. There is no Crew slash command. No dedicated Captain agent exists; the agent that proposes becomes the Captain. It proposes a roster — a name, the brief every seat will start on, and a responsibility with a reason and instructions for each member. Saved personas are optional templates; a roster can mix them with custom members. A seat may name no persona at all: a **custom seat**, named and briefed by the Captain or the person, defaults to the Captain's provider, model, and reasoning but to Full access, with harness, model, reasoning, and access editable before approval, so a Crew need not fit a mold anyone saved before (Jackson and Bryant, 2026-09-17). The Captain's access is never carried: a seat nobody configured would otherwise stop for approvals in a thread the person is not watching (Jackson, 2026-09-26). Its instructions are required at every door, since nothing else defines it. By default the proposal is a **human gate**, answered inline above the Captain's composer and never on the Inbox bell. **Settings → Agent Setup → Crews → Auto-approve new Crews** skips that gate when enabled for the Captain's project; it is off by default with project overrides. The setting is read for each new request, and changes leave existing Crews and open proposals alone. The Captain is the thread the person watches, so its own tool approvals and questions are answered inline there too. A seat runs out of view, so its provider tool approvals are answered from the Inbox (Jackson, 2026-09-26). A seat has no native question tool: when it needs a decision it asks its Captain with `j5_send_message`, and the Captain answers, or asks the person with its own question tool, inline in the Captain thread (Jackson, 2026-09-26). Claude seats run without `AskUserQuestion` and Codex seats without `request_user_input`; Cursor exposes no structured native question tool. Other harnesses keep their native tools and the standing rule to ask the Captain. If a seat still raises a native question, its Captain receives a queued notice naming the question and its thread. The person also sees a link in the Inbox to answer in the seat's original question form (Bryant, 2026-10-19). The person may drop seats, select personas from the library, or create custom seats with names, instructions, and runtime settings. Every proposed or manually added member uses the same editor before approval. Saved personas supply defaults; the person may override harness, model, reasoning, and access for this member without changing the saved definition. Approval spawns every seat as a Peer Agent placed under the Captain, with a persona assignment only when the seat names a saved definition, records the roster snapshot (the _Manifest_ in implementation vocabulary: name, brief, members with each one's reason and version), and tells the Captain how the launch went once every seat has opened its first turn or failed to: one **launch report** naming what the person changed against the proposal and, per seat, started, failed with the run's error, or startup still unconfirmed after a minute. Dispatching a brief commits intent, not a running seat, so nothing is said before that (Jackson's dogfood, 2026-09-17). A decline is told at once. Each seat's first turn carries the platform's identity facts, the crew context and roster, any seat instructions, a handoff artifact obligation when its definition declares one, and the brief. +A **Crew** is a group of agents formed as a unit from a **roster its Captain proposes, approved by the person by default**, composed for the brief in front of it. Nobody writes a Crew file in advance. The person asks the agent in an ordinary conversation to compose a Crew (web and desktop). The agent uses the conversation as context, keeps its current persona, model, and policy, and proposes the team before starting its work. There is no Crew slash command. No dedicated Captain agent exists; the agent that proposes becomes the Captain. It proposes a roster — a name, the brief every seat will start on, and a responsibility with a reason and instructions for each member. Saved personas are optional templates; a roster can mix them with custom members. A seat may name no persona at all: a **custom seat**, named and briefed by the Captain or the person, defaults to the Captain's provider, model, and reasoning but to Full access, with harness, model, reasoning, and access editable before approval, so a Crew need not fit a mold anyone saved before (Jackson and Bryant, 2026-09-17). The Captain's access is never carried: a seat nobody configured would otherwise stop for approvals in a thread the person is not watching (Jackson, 2026-09-26). Its instructions are required at every door, since nothing else defines it. By default the proposal is a **human gate**, answered inline above the Captain's composer and never on the Inbox bell. **Settings → Agent Setup → Crews → Auto-approve new Crews** skips that gate when enabled for the Captain's project; it is off by default with project overrides. The setting is read for each new request, and changes leave existing Crews and open proposals alone. The Captain is the thread the person watches, so its own tool approvals and questions are answered inline there too. A seat runs out of view, so its provider tool approvals are answered from the Inbox (Jackson, 2026-09-26). A seat has no native question tool: when it needs a decision it asks its Captain with `j5_send_message`, and the Captain answers, or asks the person with its own question tool, inline in the Captain thread (Jackson, 2026-09-26). Claude seats run without `AskUserQuestion` and Codex seats without `request_user_input`; Cursor exposes no structured native question tool. Other harnesses keep their native tools and the standing rule to ask the Captain. If a seat still raises a native question, its Captain receives a queued notice naming the question and its thread. The person also sees a link in the Inbox to answer in the seat's original question form (Bryant, 2026-10-19). The person may drop seats, select personas from the library, or create custom seats with names, instructions, and runtime settings. Every proposed or manually added member uses the same editor before approval. Saved personas supply defaults; the person may override harness, model, reasoning, and access for this member without changing the saved definition. Approval creates every seat as a Peer Agent placed under the Captain, with a persona assignment only when the seat names a saved definition, and records the roster snapshot (the _Manifest_ in implementation vocabulary: name, brief, members with each one's reason and version). It starts no provider turns. The Captain receives a creation report naming what the person changed and which seats were created or failed. A decline is told at once. Each seat's first delivered assignment carries the platform's identity facts, the current Crew context and roster, any seat instructions, a handoff artifact obligation when its definition declares one, and the approved brief. **Captains add members directly.** When the work needs expertise the roster lacks, the Captain adds one seat with a reason and optional brief. No human approval is needed, regardless of the auto-approval setting. The same launch checks apply; the tool returns the updated roster or a refusal naming the member and reason, and the launch report follows. A Crew holds at most **twelve seats**, counting open legacy requests. Members escalate staffing needs to their Captain. Pending addition requests from before this change remain approvable or declinable above their Captain's composer and stay off the Inbox and its bell. @@ -69,7 +69,7 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif ### Handoff artifacts -12. A seat whose definition declares an output artifact writes it as its handoff artifact in the project's artifacts; its first turn names the exact path. The first assignment carries its playbook context and handoff obligation; a later assignment reuses the same thread and workspace without repeating its introduction. Members that finished remain available on the roster. Started members receive net roster changes, naming who joined or left and their responsibility, at the top of their next delivery. Waiting members receive the current roster with their first assignment. Roster changes alone start no turns, and availability produces no polling or acknowledgment turns. +12. A seat whose definition declares an output artifact writes it as its handoff artifact in the project's artifacts; its first turn names the exact path. The first assignment carries its playbook context and handoff obligation; a later assignment reuses the same thread and workspace without repeating its introduction. Members that finished remain available on the roster. Started members receive net roster changes, naming who joined or left and their responsibility, at the top of their next delivery. Waiting members receive the current roster with their first assignment. Context is attached at provider delivery, after queued edits, cancellations, and reordering; a rejected provider start leaves it owed. A waiting member whose Crew retired must have its Crew restored before starting, and a worktree seat cannot fall back to the project root. Roster changes alone start no turns, and availability produces no polling or acknowledgment turns. 13. When a seat finishes, the Captain receives a notice that leads with how the run ended and, for a failed run, carries the run's recorded error, then whether the seat's handoff artifact was written, missing, unavailable with the reason it can never be read, or never declared, a written handoff artifact riding inline when short and by path otherwise; a finish whose notice would repeat the seat's last one is silent, and a notice arriving while the Captain's turn runs folds into the seat notice already queued behind it rather than queuing another turn. 14. A seat that finishes without its handoff artifact is reminded once and is reported to its Captain on its next finished run whatever happened. @@ -88,7 +88,7 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif ### State -22. A Crew's Fleet row and Captain's expander summarize measured seat states, including Not started separately from idle, running, failed, needing a person, settled, and unknown. Not started means creation succeeded and no first assignment has been accepted. Stop, archive, settle, and unarchive treat waiting seats as idle seats. A failed last run reads as failed; nothing is inferred from silence. A seat with a finished run still reads Failed, Interrupted, or Completed. In the Captain's timeline, a roster approval shows “Crew approved · N members”, plus “· by ” in a shared conversation, where more than one person could have approved it; other notices show a line only for a seat that needs attention. A clean finish adds no line. +22. A Crew's Fleet row and Captain's expander summarize measured seat states, including Not started separately from idle, running, failed, needing a person, settled, and unknown. Not started means creation succeeded and the provider has not accepted its first assignment. Stop, archive, settle, and unarchive treat waiting seats as idle seats. A failed last run reads as failed; nothing is inferred from silence. A seat with a finished run still reads Failed, Interrupted, or Completed. In the Captain's timeline, a roster approval shows “Crew approved · N members”, plus “· by ” in a shared conversation, where more than one person could have approved it; other notices show a line only for a seat that needs attention. A clean finish adds no line. ### Several people From 3b53dc98a8d1c467021859926eec7b24f0f658b6 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Wed, 28 Oct 2026 10:21:25 -0400 Subject: [PATCH 03/12] fix(j5): Crew context follows what the provider actually received (#745) Record a seat's context as delivered only when the provider took the send, so a start stopped or superseded before startTurn leaves it owed. A steered message to a busy seat now carries the current context too. The full introduction is sent again when the provider conversation it reached is replaced (model or provider switch, lost native session). Threads that are not Crew seats skip the Crew path entirely again. Drops the four unused pending_* columns from migration 49. Co-Authored-By: Claude Sonnet 5.5 --- .../CrewDeliveryContext.integration.test.ts | 32 ++- .../src/j5/a2a/CrewDeliveryContext.test.ts | 157 +++++++++++-- apps/server/src/j5/a2a/CrewDeliveryContext.ts | 25 +- apps/server/src/j5/a2a/CrewTurnContext.ts | 111 +++++++-- .../migrations/049_CrewSeatActivation.test.ts | 11 +- .../a2a/migrations/049_CrewSeatActivation.ts | 5 +- .../ProviderTurnControlService.test.ts | 147 ++++++++++++ .../ProviderTurnControlService.ts | 7 +- .../ProviderTurnStartService.test.ts | 217 ++++++++++++++++-- .../ProviderTurnStartService.ts | 20 +- .../src/orchestration-v2/runtimeLayer.ts | 1 + .../contracts/src/j5/crewDeliveryContext.ts | 15 -- 12 files changed, 654 insertions(+), 94 deletions(-) delete mode 100644 packages/contracts/src/j5/crewDeliveryContext.ts diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts index 767c6482539dc..645785bb9c421 100644 --- a/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts @@ -162,10 +162,27 @@ it.effect( assert.equal(harness.createWorktree.mock.calls[0]?.[0]?.baseRefName, "main"); assert.lengthOf(harness.createWorktree.mock.calls, 1); const crewContext = yield* CrewTurnContext.CrewTurnContext; - assert.include( - yield* crewContext.deliver(threadId, ready.messages[0]!.text, Effect.succeed), - "Shared goal", - ); + const promptFor = (text: string) => + Effect.gen(function* () { + let prompt = ""; + yield* crewContext.deliver( + { + threadId, + providerThread: { + id: "provider-thread:crew-reviewer", + nativeThreadRef: null, + } as never, + text, + }, + (sent) => + Effect.sync(() => { + prompt = sent; + return true; + }), + ); + return prompt; + }); + assert.include(yield* promptFor(ready.messages[0]!.text), "Shared goal"); yield* crews.addMembers("crew:integration", [ { seatName: "tester", @@ -256,13 +273,10 @@ it.effect( const nextText = selected.messages.find( (message) => message.id === reordered.message.id, )!.text; - const prompt = yield* crewContext.deliver(threadId, nextText, Effect.succeed); + const prompt = yield* promptFor(nextText); assert.include(prompt, "joined: tester:"); assert.isTrue(prompt.endsWith("Edited second assignment")); - assert.equal( - yield* crewContext.deliver(threadId, "Next assignment", Effect.succeed), - "Next assignment", - ); + assert.equal(yield* promptFor("Next assignment"), "Next assignment"); yield* (yield* EventSinkV2).write({ events: ready.runs.map((run) => ({ id: EventId.make(`event:finished:${run.id}`), diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts index accf617ed9bb3..7b66a9b93d55f 100644 --- a/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts @@ -91,6 +91,7 @@ const fixture = Effect.gen(function* () { const commands = yield* Ref.make>([]); const receipts = new Map(); const rejected = new Set(); + let receiptReads = 0; const dependencies = Layer.mergeAll( Layer.mock(Orchestrator.OrchestratorV2)({ getThreadShell: () => Effect.succeed({ worktreePath: null } as never), @@ -109,7 +110,11 @@ const fixture = Effect.gen(function* () { }), }), Layer.mock(CommandReceiptStoreV2)({ - getByCommandId: (id) => Effect.succeed(Option.fromNullishOr(receipts.get(id))), + getByCommandId: (id) => + Effect.sync(() => { + receiptReads += 1; + return Option.fromNullishOr(receipts.get(id)); + }), }), ); const layer = DeliveryContext.layer.pipe(Layer.provide(dependencies)); @@ -118,13 +123,58 @@ const fixture = Effect.gen(function* () { return yield* (yield* Orchestrator.OrchestratorV2).dispatch(command); }); const deliveryLayer = CrewTurnContext.layer; - const deliver = (text: string, fail = false) => + const providerThread = (native: string) => + ({ + id: "provider-thread:reviewer", + nativeThreadRef: { driver: "codex", nativeId: native, strength: "strong" }, + }) as never; + /** The prompt the provider received, or null when the send reported it never happened. */ + const deliver = ( + text: string, + options: { readonly fail?: boolean; readonly sent?: boolean; readonly native?: string } = {}, + ) => Effect.gen(function* () { - return yield* (yield* CrewTurnContext.CrewTurnContext).deliver(seatId, text, (prompt) => - fail ? Effect.fail("provider refused") : Effect.succeed(prompt), + let prompt: string | null = null; + yield* (yield* CrewTurnContext.CrewTurnContext).deliver( + { threadId: seatId, providerThread: providerThread(options.native ?? "native-1"), text }, + (sent) => + options.fail === true + ? Effect.fail("provider refused") + : Effect.sync(() => { + if (options.sent !== false) prompt = sent; + return options.sent !== false; + }), ); + return prompt as string | null; + }).pipe(Effect.provide(deliveryLayer)); + const steer = (text: string, options: { readonly fail?: boolean } = {}) => + Effect.gen(function* () { + const steered: string[] = []; + const session = (yield* CrewTurnContext.CrewTurnContext).steering({ + steerTurn: (input) => + options.fail === true + ? Effect.die("provider refused") + : Effect.sync(() => void steered.push(input.message.text)), + }); + yield* session.steerTurn({ + threadId: seatId, + providerThread: providerThread("native-1"), + message: { text }, + } as never); + return steered[0] ?? null; }).pipe(Effect.provide(deliveryLayer)); - return { sql, crews, commands, receipts, rejected, layer, send, deliver }; + return { + sql, + crews, + commands, + receipts, + receiptReads: () => receiptReads, + rejected, + layer, + send, + deliver, + steer, + }; }); it.effect( @@ -138,7 +188,7 @@ it.effect( assert.deepStrictEqual((yield* Ref.get(f.commands))[0], command); yield* f.crews.addMembers("crew:test", [member("security")]); yield* f.crews.removeMembers("crew:test", ["builder"]); - const prompt = yield* f.deliver(command.text); + const prompt = (yield* f.deliver(command.text))!; assert.include(prompt, "\nShared goal\n"); assert.include(prompt, "Review carefully."); assert.include(prompt, "- security:"); @@ -169,12 +219,12 @@ it.effect( it.effect("provider refusal keeps the introduction and roster changes owed", () => Effect.gen(function* () { const f = yield* fixture; - assert.equal((yield* f.deliver("first", true).pipe(Effect.result))._tag, "Failure"); - assert.include(yield* f.deliver("retry"), ""); + assert.equal((yield* f.deliver("first", { fail: true }).pipe(Effect.result))._tag, "Failure"); + assert.include((yield* f.deliver("retry"))!, ""); yield* f.crews.addMembers("crew:test", [member("security")]); yield* f.crews.removeMembers("crew:test", ["builder"]); - yield* f.deliver("refused update", true).pipe(Effect.result); - const prompt = yield* f.deliver("accepted update"); + yield* f.deliver("refused update", { fail: true }).pipe(Effect.result); + const prompt = (yield* f.deliver("accepted update"))!; assert.include(prompt, "joined: security:"); assert.include(prompt, "left: builder:"); assert.notInclude(prompt, "spawner_brief"); @@ -194,7 +244,7 @@ it.effect( yield* f.crews.addMembers("crew:test", [member("security")]); yield* f.send(assignment("queued-second")).pipe(Effect.provide(f.layer)); // The provider sees whichever editable message upstream selects, not acceptance order. - const prompt = yield* f.deliver("edited second assignment promoted first"); + const prompt = (yield* f.deliver("edited second assignment promoted first"))!; assert.include(prompt, "joined: security:"); assert.include(prompt, "left: builder:"); assert.notInclude(prompt, "temporary"); @@ -215,7 +265,7 @@ it.effect( .pipe(Effect.result, Effect.provide(f.layer)); assert.equal(result._tag, "Failure"); assert.lengthOf(yield* Ref.get(f.commands), 0); - assert.equal((yield* f.deliver("bypass", false).pipe(Effect.result))._tag, "Failure"); + assert.equal((yield* f.deliver("bypass").pipe(Effect.result))._tag, "Failure"); }).pipe(Effect.provide(base)), ); @@ -244,7 +294,7 @@ it.effect( yield* f.sql`INSERT INTO j5_a2a_message_author (thread_id, message_id, person_id, display_name, level, stored_prefix, created_at) VALUES (${seatId}, ${command.messageId}, 'human:owner', 'Bryant', 'owner', ${authorPrefix}, '2026-10-27T12:00:00Z')`; yield* f.send(command).pipe(Effect.provide(f.layer)); - const prompt = yield* f.deliver(command.text); + const prompt = (yield* f.deliver(command.text))!; const [author] = yield* f.sql<{ readonly stored_prefix: string; }>`SELECT stored_prefix FROM j5_a2a_message_author WHERE message_id = ${command.messageId}`; @@ -274,3 +324,84 @@ it.effect("a retired member that already started continues as a plain agent", () assert.equal(yield* f.deliver("new assignment"), "new assignment"); }).pipe(Effect.provide(base)), ); + +it.effect("a send that never happened leaves the introduction and roster changes owed", () => + Effect.gen(function* () { + const f = yield* fixture; + assert.isNull(yield* f.deliver("stopped before the provider", { sent: false })); + const [owed] = yield* f.sql<{ + readonly delivered_roster: string | null; + }>`SELECT delivered_roster FROM j5_crew_seat_context WHERE thread_id = ${seatId}`; + assert.isNull(owed!.delivered_roster); + assert.include((yield* f.deliver("retry"))!, ""); + yield* f.crews.addMembers("crew:test", [member("security")]); + assert.isNull(yield* f.deliver("superseded", { sent: false })); + assert.include((yield* f.deliver("retry"))!, "joined: security:"); + }).pipe(Effect.provide(base)), +); + +it.effect("the introduction is sent again only when the provider conversation changes", () => + Effect.gen(function* () { + const f = yield* fixture; + assert.include((yield* f.deliver("first", { native: "native-1" }))!, ""); + assert.equal( + yield* f.deliver("same conversation", { native: "native-1" }), + "same conversation", + ); + yield* f.crews.addMembers("crew:test", [member("security")]); + const replaced = (yield* f.deliver("after fallback", { native: "native-2" }))!; + assert.include(replaced, "\nShared goal\n"); + assert.include(replaced, "Review carefully."); + assert.include(replaced, "- security:"); + assert.notInclude(replaced, "joined:"); + assert.equal( + yield* f.deliver("replaced conversation", { native: "native-2" }), + "replaced conversation", + ); + }).pipe(Effect.provide(base)), +); + +it.effect("a migrated seat has no introduction to send again", () => + Effect.gen(function* () { + const f = yield* fixture; + yield* f.deliver("first", { native: "native-1" }); + yield* f.sql`UPDATE j5_crew_seat_context SET delivered_conversation = NULL, first_turn_text = ''`; + assert.equal(yield* f.deliver("one", { native: "native-1" }), "one"); + assert.equal(yield* f.deliver("two", { native: "native-2" }), "two"); + }).pipe(Effect.provide(base)), +); + +it.effect("steering a busy seat carries the roster change and records it only once accepted", () => + Effect.gen(function* () { + const f = yield* fixture; + yield* f.deliver("first"); + yield* f.crews.addMembers("crew:test", [member("security")]); + yield* f.steer("refused", { fail: true }).pipe(Effect.exit); + const steered = (yield* f.steer("steer the builder"))!; + assert.include(steered, "joined: security:"); + assert.isTrue(steered.endsWith("steer the builder")); + assert.equal(yield* f.steer("again"), "again"); + }).pipe(Effect.provide(base)), +); + +it.effect( + "authored text is delivered byte for byte, even when it begins with the context marker", + () => + Effect.gen(function* () { + const f = yield* fixture; + const authored = + "\nmine\n\n\nPlease review."; + assert.isTrue((yield* f.deliver(authored))!.endsWith(authored)); + assert.equal(yield* f.deliver(authored), authored); + }).pipe(Effect.provide(base)), +); + +it.effect("a thread that is not a Crew seat is dispatched untouched, without a receipt read", () => + Effect.gen(function* () { + const f = yield* fixture; + const command = { ...assignment("plain"), threadId: ThreadId.make("thread:plain") }; + yield* f.send(command).pipe(Effect.provide(f.layer)); + assert.deepStrictEqual((yield* Ref.get(f.commands))[0], command); + assert.equal(f.receiptReads(), 0); + }).pipe(Effect.provide(base)), +); diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.ts index c2b6bd0ada7e0..c8364aa8dc07a 100644 --- a/apps/server/src/j5/a2a/CrewDeliveryContext.ts +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.ts @@ -46,9 +46,11 @@ export const layer = Layer.effect( const receipts = yield* CommandReceiptStoreV2; const crews = yield* Crews.AgentCrewInstanceService; const locks = yield* KeyedLock.make(); - const dispatch: Orchestrator.OrchestratorV2["Service"]["dispatch"] = (command) => { - if (command.type !== "message.dispatch") return inner.dispatch(command); - return locks.withLock( + type Dispatch = Orchestrator.OrchestratorV2["Service"]["dispatch"]; + const dispatchToSeat = ( + command: Extract[0], { type: "message.dispatch" }>, + ) => + locks.withLock( command.threadId, Effect.gen(function* () { if (Option.isSome(yield* receipts.getByCommandId(command.commandId))) @@ -100,6 +102,23 @@ export const layer = Layer.effect( ), ), ); + const dispatch: Dispatch = (command) => { + if (command.type !== "message.dispatch") return inner.dispatch(command); + // Seat contexts are written when a Crew launches, before any message reaches the seat, so + // an ordinary thread skips the lock and the receipt read. + return sql`SELECT 1 AS present FROM j5_crew_seat_context WHERE thread_id = ${command.threadId}`.pipe( + Effect.mapError( + (cause) => + new Orchestrator.OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause, + }), + ), + Effect.flatMap((seat) => + seat.length === 0 ? inner.dispatch(command) : dispatchToSeat(command), + ), + ); }; return Orchestrator.OrchestratorV2.of({ ...inner, dispatch }); }), diff --git a/apps/server/src/j5/a2a/CrewTurnContext.ts b/apps/server/src/j5/a2a/CrewTurnContext.ts index 2f129026a0bfc..5f87141db2860 100644 --- a/apps/server/src/j5/a2a/CrewTurnContext.ts +++ b/apps/server/src/j5/a2a/CrewTurnContext.ts @@ -1,5 +1,5 @@ -import { ThreadId } from "@t3tools/contracts"; -import { crewDeliveryAssignment, crewDeliveryContextPrefix } from "@t3tools/contracts/j5"; +import { type OrchestrationV2ProviderThread, ThreadId } from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -25,17 +25,49 @@ class CrewTurnContextError extends Schema.TaggedError()( const isCrewTurnContextError = Schema.is(CrewTurnContextError); +export interface CrewDelivery { + readonly threadId: ThreadId; + /** The provider conversation about to receive the text; a new one needs the introduction again. */ + readonly providerThread: Pick; + readonly text: string; +} + export class CrewTurnContext extends Context.Service< CrewTurnContext, { - readonly deliver: ( - threadId: ThreadId, - text: string, - send: (text: string) => Effect.Effect, - ) => Effect.Effect; + /** Whether the thread is a Crew seat. Every other thread skips this service. */ + readonly isSeat: (threadId: ThreadId) => Effect.Effect; + /** + * Sends the text with the seat's current Crew context in front. `send` answers whether the + * provider took the text; only then is the context recorded as delivered, so a send that + * never happened (stopped, superseded) leaves it owed for the next one. + */ + readonly deliver: ( + delivery: CrewDelivery, + send: (text: string) => Effect.Effect, + ) => Effect.Effect; + /** A steered message reaches a busy seat with the same context a fresh turn would carry. */ + readonly steering: (session: { + readonly steerTurn: ProviderAdapter.ProviderAdapterV2SessionRuntime["steerTurn"]; + }) => { + readonly steerTurn: ( + input: ProviderAdapter.ProviderAdapterV2SteerInput, + ) => Effect.Effect; + }; } >()("t3/j5/a2a/CrewTurnContext") {} +const DELIVERY_OPEN = "\n"; +const DELIVERY_CLOSE = "\n\n\n"; +/** Keeps the platform's context apart from the assignment that follows it. */ +const deliveryContext = (context: string) => + context === "" + ? "" + : `${DELIVERY_OPEN}${context.replaceAll("", "<\\/j5_crew_delivery_context>")}${DELIVERY_CLOSE}`; + +const conversationOf = (providerThread: CrewDelivery["providerThread"]) => + `${providerThread.id}:${providerThread.nativeThreadRef?.nativeId ?? ""}`; + const Roster = Schema.fromJsonString( Schema.Array( Schema.Struct({ @@ -54,13 +86,17 @@ const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const crews = yield* Crews.AgentCrewInstanceService; const changes = yield* ReadChanges.ReadChanges; - const prepare = Effect.fn("j5.crewTurnContext.prepare")(function* (threadId: ThreadId) { + const prepare = Effect.fn("j5.crewTurnContext.prepare")(function* (delivery: CrewDelivery) { + const { threadId } = delivery; + const conversation = conversationOf(delivery.providerThread); return yield* Effect.gen(function* () { const [context] = yield* sql<{ readonly first_turn_text: string; readonly delivered_roster: string | null; + readonly delivered_conversation: string | null; }>` - SELECT first_turn_text, delivered_roster FROM j5_crew_seat_context WHERE thread_id = ${threadId} + SELECT first_turn_text, delivered_roster, delivered_conversation + FROM j5_crew_seat_context WHERE thread_id = ${threadId} `; if (context === undefined) return null; const membership = yield* crews.findMembership(participantIdForThread(threadId)); @@ -78,7 +114,14 @@ const make = Effect.gen(function* () { })); const rosterJson = encodeRoster(roster); let prefix = ""; - if (context.delivered_roster === null) { + // A conversation the introduction never reached (first turn, or the provider rebuilt it + // from history after a model switch or lost session) gets it whole. A seat from before + // conversations were recorded has none stored and is not introduced again. + const introduce = + context.delivered_roster === null || + (context.delivered_conversation !== null && + context.delivered_conversation !== conversation); + if (introduce) { prefix = context.first_turn_text.replace( /[\s\S]*?<\/j5_crew_context>/, () => @@ -110,10 +153,10 @@ const make = Effect.gen(function* () { } return { - prefix: crewDeliveryContextPrefix(prefix), + prefix: deliveryContext(prefix), delivered: sql` - UPDATE j5_crew_seat_context SET delivered_roster = ${rosterJson}, - pending_command_id = NULL, pending_roster = NULL, pending_message_id = NULL, pending_prefix = NULL + UPDATE j5_crew_seat_context + SET delivered_roster = ${rosterJson}, delivered_conversation = ${conversation} WHERE thread_id = ${threadId} `.pipe( Effect.andThen(changes.notify("crew", "fleet")), @@ -127,24 +170,46 @@ const make = Effect.gen(function* () { ), ); }); - const deliver = ( - threadId: ThreadId, - text: string, - send: (text: string) => Effect.Effect, + const isSeat = (threadId: ThreadId) => + sql`SELECT 1 AS present FROM j5_crew_seat_context WHERE thread_id = ${threadId}`.pipe( + Effect.map((rows) => rows.length > 0), + Effect.mapError((cause) => new CrewTurnContextError({ threadId, cause })), + ); + const deliver = ( + delivery: CrewDelivery, + send: (text: string) => Effect.Effect, ) => Effect.gen(function* () { - const context = yield* prepare(threadId); - if (context === null) return yield* send(text); - const result = yield* send(`${context.prefix}${crewDeliveryAssignment(text)}`); + const context = yield* prepare(delivery); + if (context === null) return yield* send(delivery.text); + const sent = yield* send(`${context.prefix}${delivery.text}`); + if (!sent) return false; // The provider accepted the prompt; bookkeeping failure must not fail its running turn. yield* context.delivered.pipe( Effect.catch((cause) => - Effect.logWarning("Failed to record delivered Crew context", { threadId, cause }), + Effect.logWarning("Failed to record delivered Crew context", { + threadId: delivery.threadId, + cause, + }), ), ); - return result; + return true; }); - return CrewTurnContext.of({ deliver }); + const steering: CrewTurnContext["Service"]["steering"] = (session) => ({ + steerTurn: (input) => + deliver( + { + threadId: input.threadId, + providerThread: input.providerThread, + text: input.message.text, + }, + (text) => + session + .steerTurn({ ...input, message: { ...input.message, text } }) + .pipe(Effect.as(true)), + ).pipe(Effect.asVoid), + }); + return CrewTurnContext.of({ isSeat, deliver, steering }); }); export const layer = Layer.effect(CrewTurnContext, make).pipe( diff --git a/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts index d4698ceaa18b3..645c468c7ddd7 100644 --- a/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts +++ b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts @@ -32,12 +32,14 @@ it.effect( const contexts = yield* sql<{ readonly delivered_roster: string; readonly first_turn_text: string; + readonly delivered_conversation: string | null; }>` - SELECT delivered_roster, first_turn_text FROM j5_crew_seat_context + SELECT delivered_roster, first_turn_text, delivered_conversation FROM j5_crew_seat_context `; assert.lengthOf(contexts, 2); for (const row of contexts) { assert.equal(row.first_turn_text, ""); + assert.isNull(row.delivered_conversation); const roster = yield* decodeRoster(row.delivered_roster); assert.sameMembers( roster.map((member) => member.seat), @@ -48,5 +50,12 @@ it.effect( "Responsibility of builder", ); } + const columns = yield* sql<{ readonly name: string }>` + SELECT name FROM pragma_table_info('j5_crew_seat_context') ORDER BY cid + `; + assert.deepStrictEqual( + columns.map((column) => column.name), + ["thread_id", "first_turn_text", "workspace", "delivered_roster", "delivered_conversation"], + ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.ts b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.ts index b71390015c865..c349b32a0f36d 100644 --- a/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.ts +++ b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.ts @@ -9,10 +9,7 @@ export default Effect.gen(function* () { first_turn_text TEXT NOT NULL, workspace TEXT NOT NULL, delivered_roster TEXT, - pending_command_id TEXT, - pending_message_id TEXT, - pending_prefix TEXT, - pending_roster TEXT + delivered_conversation TEXT ) `; yield* sql` diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index b60c4215853bb..fa120b27b718c 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -1,6 +1,7 @@ import { assert, it } from "@effect/vitest"; import { type ModelSelection, + MessageId, NodeId, type OrchestrationV2ProviderThread, type OrchestrationV2ThreadProjection, @@ -20,7 +21,17 @@ import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; +import * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; + +import * as Crews from "../j5/a2a/AgentCrewInstanceService.ts"; +import * as CrewTurnContext from "../j5/a2a/CrewTurnContext.ts"; +import { participantIdForThread } from "../j5/a2a/HomeRegistrar.ts"; +import { A2ALedger, layer as ledgerLayer } from "../j5/a2a/LedgerService.ts"; +import { runJ5A2AMigrations } from "../j5/a2a/Migrations.ts"; +import { LedgerProjectId } from "../j5/a2a/contracts.ts"; +import { spawnFirstTurnText } from "../j5/a2a/spawnIds.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -328,3 +339,139 @@ it.effect( assert.equal(interrupted?.nativeThreadRef?.nativeId, "native-thread:restart-session"); }), ); + +const crewDatabase = NodeSqliteClient.layer({ filename: ":memory:" }); +const crewServices = Layer.mergeAll( + crewDatabase, + Crews.layer.pipe(Layer.provide(crewDatabase)), + ledgerLayer.pipe(Layer.provide(crewDatabase)), +); + +it.effect("steering a busy Crew seat carries the roster change made while it worked", () => + Effect.gen(function* () { + yield* runJ5A2AMigrations(); + const sql = yield* SqlClient.SqlClient; + const crews = yield* Crews.AgentCrewInstanceService; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:crew-builder"); + const captainThreadId = ThreadId.make("thread:crew-captain"); + const sessionId = ProviderSessionId.make("provider-session:crew-builder"); + const providerThreadId = ProviderThreadId.make("provider-thread:crew-builder"); + const providerTurnId = ProviderTurnId.make("provider-turn:crew-builder"); + const attemptId = RunAttemptId.make("run-attempt:crew-builder"); + const providerThread: OrchestrationV2ProviderThread = { + id: providerThreadId, + driver, + providerInstanceId, + providerSessionId: sessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: "native-thread:crew-builder", strength: "strong" }, + nativeConversationHeadRef: null, + status: "active", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }; + const base = makeProjection({ now, threadId, providerThread, providerTurnId, attemptId }); + const message = { + id: MessageId.make("message:steer-builder"), + text: "Also cover the retry path.", + attachments: [], + createdBy: "agent", + creationSource: "mcp", + }; + const steered: Array = []; + const runtime = { + steerTurn: (input: ProviderAdapter.ProviderAdapterV2SteerInput) => + Effect.sync(() => void steered.push(input.message.text)), + } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime; + + const projectId = LedgerProjectId.make("project:crew-steer"); + yield* (yield* A2ALedger).ensureProject({ projectId, createdAt: "2026-10-27T12:00:00.000Z" }); + const seat = (seatName: string, id: ThreadId) => ({ + seatName, + agentId: null, + threadId: id, + participantId: participantIdForThread(id), + reason: `Responsibility of ${seatName}`, + }); + yield* crews.record({ + id: "crew:steer", + projectId, + captainThreadId, + captainParticipantId: participantIdForThread(captainThreadId), + displayName: "Steer crew", + brief: "Shared goal", + createdAt: "2026-10-27T12:00:00.000Z", + members: [seat("builder", threadId)], + }); + const text = spawnFirstTurnText({ + brief: "Shared goal", + participantId: participantIdForThread(threadId), + projectId, + projectTitle: "Project", + spawnedByParticipantId: participantIdForThread(captainThreadId), + crew: { + displayName: "Steer crew", + instanceId: "crew:steer", + seatName: "builder", + captainParticipantId: participantIdForThread(captainThreadId), + roster: [], + }, + }); + yield* sql`INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace) + VALUES (${threadId}, ${text}, '{"type":"shared"}')`; + // The builder's assignment started the turn that is still running. + yield* Effect.gen(function* () { + yield* (yield* CrewTurnContext.CrewTurnContext).deliver( + { threadId, providerThread, text: "Build the fix." }, + () => Effect.succeed(true), + ); + }).pipe(Effect.provide(CrewTurnContext.layer)); + yield* crews.addMembers("crew:steer", [ + seat("reviewer", ThreadId.make("thread:crew-reviewer")), + ]); + + const target = { + threadId, + providerSessionId: sessionId, + providerThreadId, + providerTurnId, + messageId: message.id, + }; + const layerControl = ProviderTurnControlService.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getProviderControlContext: () => + Effect.succeed({ + providerThread, + providerTurn: base.providerTurns[0], + attempt: base.attempts[0], + message, + run: { id: RunId.make("run:crew-builder") }, + } as never), + }), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ + get: () => Effect.succeed(Option.some(runtime)), + }), + ), + ), + Layer.provide(CrewTurnContext.layer), + ); + yield* Effect.gen(function* () { + const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2; + yield* control.steer(target); + yield* control.steer(target); + }).pipe(Effect.provide(layerControl)); + + assert.lengthOf(steered, 2); + assert.include(steered[0]!, "joined: reviewer: participant_id="); + assert.isTrue(steered[0]!.endsWith("Also cover the retry path.")); + assert.equal(steered[1], "Also cover the retry path."); + }).pipe(Effect.provide(crewServices)), +); diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts index 20c52901c3064..bcbe0bd05c339 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts @@ -17,6 +17,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as CrewTurnContext from "../j5/a2a/CrewTurnContext.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProviderSessionManager from "./ProviderSessionManager.ts"; @@ -90,6 +91,7 @@ export const layer: Layer.Layer< Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2; + const crewTurnContext = yield* Effect.serviceOption(CrewTurnContext.CrewTurnContext); const load = (input: { readonly threadId: ThreadId; @@ -356,7 +358,10 @@ export const layer: Layer.Layer< cause: "The persisted steering message or target run is missing.", }); } - yield* loaded.session.value + const session = Option.isSome(crewTurnContext) + ? crewTurnContext.value.steering(loaded.session.value) + : loaded.session.value; + yield* session .steerTurn({ threadId: input.threadId, runId: run.id, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index c2ab2e4a441f0..1a27a2fa50ce2 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -1,10 +1,19 @@ import * as CrewTurnContext from "../j5/a2a/CrewTurnContext.ts"; +import * as Crews from "../j5/a2a/AgentCrewInstanceService.ts"; +import { participantIdForThread } from "../j5/a2a/HomeRegistrar.ts"; +import { A2ALedger, layer as ledgerLayer } from "../j5/a2a/LedgerService.ts"; +import { runJ5A2AMigrations } from "../j5/a2a/Migrations.ts"; +import { LedgerProjectId } from "../j5/a2a/contracts.ts"; +import { spawnFirstTurnText } from "../j5/a2a/spawnIds.ts"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as SqlClient from "effect/sql/SqlClient"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it, vi } from "vite-plus/test"; import { it as effectIt } from "@effect/vitest"; import { CheckpointScopeId, ContextHandoffId, + EventId, MessageId, NodeId, ProviderSessionId, @@ -1099,6 +1108,8 @@ const makeCodexResumeSchemaFailure = Effect.fn("makeCodexResumeSchemaFailure")(f function makeNativeResumeHarness(input: { readonly crewDelivery?: CrewTurnContext.CrewTurnContext["Service"]; readonly keepNativeThread?: boolean; + /** Builds history handoffs with the real service instead of a canned summary. */ + readonly realHandoffs?: boolean; readonly text?: string; readonly resumeThread: ( ids: NativeResumeIds, @@ -1175,24 +1186,26 @@ function makeNativeResumeHarness(input: { ), Layer.provide( Layer.mergeAll( - Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({ - prepareProviderHandoff: (handoff) => - Effect.succeed({ - id: ContextHandoffId.make("handoff-native-resume-fallback"), - transferId: handoff.transferId, - threadId: handoff.threadId, - targetRunId: handoff.targetRunId, - fromProviderThreadIds: handoff.fromProviderThreadIds, - toProviderThreadId: handoff.toProviderThreadId, - coveredRunOrdinals: handoff.coveredRunOrdinals, - strategy: handoff.strategy, - status: "ready", - summaryMessageId: null, - summaryText: "summary", - createdByProviderInstanceId: handoff.toProviderInstanceId, - createdAt: handoff.createdAt, - } as never), - }), + input.realHandoffs === true + ? ContextHandoffService.layer.pipe(Layer.provide(IdAllocator.layer)) + : Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({ + prepareProviderHandoff: (handoff) => + Effect.succeed({ + id: ContextHandoffId.make("handoff-native-resume-fallback"), + transferId: handoff.transferId, + threadId: handoff.threadId, + targetRunId: handoff.targetRunId, + fromProviderThreadIds: handoff.fromProviderThreadIds, + toProviderThreadId: handoff.toProviderThreadId, + coveredRunOrdinals: handoff.coveredRunOrdinals, + strategy: handoff.strategy, + status: "ready", + summaryMessageId: null, + summaryText: "summary", + createdByProviderInstanceId: handoff.toProviderInstanceId, + createdAt: handoff.createdAt, + } as never), + }), Layer.mock(EventSink.EventSinkV2)({ write: ({ events: incoming }) => Effect.sync(() => { @@ -1258,6 +1271,21 @@ function makeNativeResumeHarness(input: { startRootRun, nativeStartTurn, events, + /** The person pressed Stop: the run is no longer the attempt that may reach the provider. */ + stop: () => { + const stopped = projection.runs.find((candidate) => candidate.id === run.id)!; + commit([ + { + id: EventId.make("event:stop-before-send"), + type: "run.updated", + threadId: projection.thread.id, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: projection.thread.updatedAt, + payload: { ...stopped, status: "interrupted" }, + } as OrchestrationV2DomainEvent, + ]); + }, projection: () => projection, start: (options?: { readonly willRetry: boolean }) => Effect.gen(function* () { @@ -1522,10 +1550,12 @@ effectIt.effect( keepNativeThread: true, resumeThread: () => Effect.die("retained native conversation"), crewDelivery: { - deliver: (_threadId, text, send) => + isSeat: () => Effect.succeed(true), + steering: (session) => session as never, + deliver: (delivery, send) => Effect.gen(function* () { order.push("context"); - const result = yield* send(`Crew introduction\n\n${text}`); + const result = yield* send(`Crew introduction\n\n${delivery.text}`); order.push("accepted"); return result; }), @@ -1548,3 +1578,150 @@ effectIt.effect( expect(order).toEqual(["context", "provider", "accepted"]); }), ); + +// The Crew seat context is real here: SQLite, the Crew service, and the real history handoff service. +const crewDatabase = NodeSqliteClient.layer({ filename: ":memory:" }); +const crewServices = Layer.mergeAll( + crewDatabase, + Crews.layer.pipe(Layer.provide(crewDatabase)), + ledgerLayer.pipe(Layer.provide(crewDatabase)), +); + +const recordSeat = (seatThreadId: ThreadId, options: { readonly seat?: boolean } = {}) => + Effect.gen(function* () { + yield* runJ5A2AMigrations(); + const sql = yield* SqlClient.SqlClient; + if (options.seat === false) return; + const projectId = LedgerProjectId.make("project:crew-start"); + const captainThreadId = ThreadId.make("thread:captain"); + yield* (yield* A2ALedger).ensureProject({ + projectId, + createdAt: "2026-10-27T12:00:00.000Z", + }); + yield* (yield* Crews.AgentCrewInstanceService).record({ + id: "crew:start", + projectId, + captainThreadId, + captainParticipantId: participantIdForThread(captainThreadId), + displayName: "Start crew", + brief: "Shared goal", + createdAt: "2026-10-27T12:00:00.000Z", + members: [ + { + seatName: "builder", + agentId: null, + threadId: seatThreadId, + participantId: participantIdForThread(seatThreadId), + reason: "Build the fix", + }, + ], + }); + const text = spawnFirstTurnText({ + brief: "Shared goal", + participantId: participantIdForThread(seatThreadId), + projectId, + projectTitle: "Project", + spawnedByParticipantId: participantIdForThread(captainThreadId), + crew: { + displayName: "Start crew", + instanceId: "crew:start", + seatName: "builder", + captainParticipantId: participantIdForThread(captainThreadId), + roster: [], + }, + }); + yield* sql`INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace) + VALUES (${seatThreadId}, ${text}, '{"type":"shared"}')`; + }); + +/** Starts one turn through the real seat context and sends the text the start requests. */ +const startCrewTurn = (input: { + readonly crewDelivery: CrewTurnContext.CrewTurnContext["Service"]; + readonly resumeGone?: boolean; + readonly stopBeforeSend?: boolean; +}) => + Effect.gen(function* () { + const harness = makeNativeResumeHarness({ + text: "Build the fix.", + crewDelivery: input.crewDelivery, + realHandoffs: true, + ...(input.resumeGone === true + ? { resumeThread: nativeThreadGone } + : { + keepNativeThread: true, + resumeThread: () => Effect.die("retained native conversation"), + }), + }); + yield* harness.start(); + if (input.stopBeforeSend === true) harness.stop(); + const requested = harness.startRootRun.mock.calls[0]![0]; + yield* requested.session.startTurn({ + message: { text: "Build the fix.", attachments: [] }, + } as never); + return { harness, requested, sent: harness.nativeStartTurn.mock.calls[0]?.[0].message.text }; + }); + +const seatThread = harnessThreadId(); +function harnessThreadId() { + return makeLocalCommandHarness({ text: "x", previousMessages: [] }).projection().thread.id; +} + +effectIt.effect("a Stop before the provider send leaves the Crew introduction owed", () => + Effect.gen(function* () { + yield* recordSeat(seatThread); + const crewDelivery = yield* CrewTurnContext.CrewTurnContext; + const stopped = yield* startCrewTurn({ crewDelivery, stopBeforeSend: true }); + expect(stopped.harness.nativeStartTurn).not.toHaveBeenCalled(); + const sql = yield* SqlClient.SqlClient; + const owed = yield* sql<{ + readonly delivered_roster: string | null; + }>`SELECT delivered_roster FROM j5_crew_seat_context WHERE thread_id = ${seatThread}`; + expect(owed[0]!.delivered_roster).toBeNull(); + const retry = yield* startCrewTurn({ crewDelivery }); + expect(retry.sent).toContain("\nShared goal\n"); + expect(retry.sent).toMatch(/Build the fix\.$/); + }).pipe( + Effect.provide( + Layer.mergeAll(crewServices, CrewTurnContext.layer.pipe(Layer.provide(crewServices))), + ), + ), +); + +effectIt.effect( + "the Crew introduction is sent again on a replaced provider conversation, not on an unchanged one", + () => + Effect.gen(function* () { + yield* recordSeat(seatThread); + const crewDelivery = yield* CrewTurnContext.CrewTurnContext; + const first = yield* startCrewTurn({ crewDelivery }); + expect(first.sent).toContain(""); + const unchanged = yield* startCrewTurn({ crewDelivery }); + expect(unchanged.sent).toBe("Build the fix."); + const replaced = yield* startCrewTurn({ crewDelivery, resumeGone: true }); + expect(replaced.harness.projection().contextHandoffs).toHaveLength(1); + expect(replaced.sent).toContain("\nShared goal\n"); + expect(replaced.sent).toMatch(/Build the fix\.$/); + const afterReplacement = yield* startCrewTurn({ crewDelivery, resumeGone: true }); + expect(afterReplacement.sent).not.toContain(""); + }).pipe( + Effect.provide( + Layer.mergeAll(crewServices, CrewTurnContext.layer.pipe(Layer.provide(crewServices))), + ), + ), +); + +effectIt.effect( + "an ordinary thread skips the Crew path and starts on the provider session as is", + () => + Effect.gen(function* () { + yield* recordSeat(seatThread, { seat: false }); + const crewDelivery = yield* CrewTurnContext.CrewTurnContext; + const ordinary = yield* startCrewTurn({ crewDelivery }); + expect(ordinary.requested.session.startTurn).toBe(ordinary.harness.nativeStartTurn); + expect(ordinary.sent).toBe("Build the fix."); + }).pipe( + Effect.provide( + Layer.mergeAll(crewServices, CrewTurnContext.layer.pipe(Layer.provide(crewServices))), + ), + ), +); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index d76e3a4dc8de9..fb9d1fb239cb5 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1209,7 +1209,7 @@ export const layer: Layer.Layer< }); }), }); - if (!(yield* isCurrentAttemptInStatus("running"))) return; + if (!(yield* isCurrentAttemptInStatus("running"))) return false; const start = compact ? session.compactThread! : session.startTurn; const context = [delivery.context, restartNote] .filter((part) => part !== "") @@ -1246,17 +1246,27 @@ export const layer: Layer.Layer< }), ), ); + return true; }); + const crewSeat = + Option.isSome(crewTurnContext) && + (yield* crewTurnContext.value.isSeat(projection.thread.id)); const startWithHandoffs = ( turnInput: Parameters[0], compact = false, ) => - (Option.isSome(crewTurnContext) - ? crewTurnContext.value.deliver(projection.thread.id, userText, (assignment) => - startAssignmentWithHandoffs(turnInput, compact, assignment), + (crewSeat + ? crewTurnContext.value.deliver( + { + threadId: projection.thread.id, + providerThread: runningProviderThread, + text: userText, + }, + (assignment) => startAssignmentWithHandoffs(turnInput, compact, assignment), ) : startAssignmentWithHandoffs(turnInput, compact, userText) ).pipe( + Effect.asVoid, Effect.mapError((cause) => cause._tag === "ProviderAdapterTurnStartError" ? cause @@ -1274,7 +1284,7 @@ export const layer: Layer.Layer< missedItems.length === 0 && restartNote === "" && !noteContinuation && - Option.isNone(crewTurnContext) + !crewSeat ? session : makeDeliverySession(session, startWithHandoffs); return runExecution.startRootRun({ diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index b7bb4acc5f12d..157519fdd8388 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -189,6 +189,7 @@ const layerProviderTurnStartServiceProvided = ProviderTurnStartService.layer.pip ); const layerProviderTurnControlServiceProvided = ProviderTurnControlService.layer.pipe( + Layer.provide(CrewTurnContext.layer), Layer.provide(Layer.merge(ProjectionStore.layer, layerProviderSessionManagerProvided)), ); const layerRuntimeRequestServiceProvided = RuntimeRequestService.layer.pipe( diff --git a/packages/contracts/src/j5/crewDeliveryContext.ts b/packages/contracts/src/j5/crewDeliveryContext.ts deleted file mode 100644 index 32de8104ced88..0000000000000 --- a/packages/contracts/src/j5/crewDeliveryContext.ts +++ /dev/null @@ -1,15 +0,0 @@ -const OPEN = "\n"; -const CLOSE = "\n\n\n"; - -/** The assignment keeps its own envelope after the platform's Crew context. */ -export const crewDeliveryContextPrefix = (context: string) => - context === "" - ? "" - : `${OPEN}${context.replaceAll("", "<\\/j5_crew_delivery_context>")}${CLOSE}`; - -/** Call only on platform-owned delivery message ids; ordinary authored text stays literal. */ -export const crewDeliveryAssignment = (text: string) => { - if (!text.startsWith(OPEN)) return text; - const end = text.indexOf(CLOSE, OPEN.length); - return end < 0 ? text : text.slice(end + CLOSE.length); -}; From c5f8b548f23cc5219537c51ff6c8a245bf3125f5 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Wed, 28 Oct 2026 10:21:27 -0400 Subject: [PATCH 04/12] fix(web): a seat whose first start failed reads as failed, not Not started (#745) Co-Authored-By: Claude Sonnet 5.5 --- apps/web/src/j5/crew/crewState.ts | 10 +++ apps/web/src/j5/fleet/FleetPage.test.tsx | 79 +++++++++++++++++++ apps/web/src/j5/fleet/FleetPage.tsx | 13 ++- .../src/j5/threads/SpawnedChildren.test.tsx | 72 +++++++++++++++++ apps/web/src/j5/threads/SpawnedChildren.tsx | 14 ++-- 5 files changed, 180 insertions(+), 8 deletions(-) create mode 100644 apps/web/src/j5/fleet/FleetPage.test.tsx create mode 100644 apps/web/src/j5/threads/SpawnedChildren.test.tsx diff --git a/apps/web/src/j5/crew/crewState.ts b/apps/web/src/j5/crew/crewState.ts index 129b1b1347f12..04f115a6ec83d 100644 --- a/apps/web/src/j5/crew/crewState.ts +++ b/apps/web/src/j5/crew/crewState.ts @@ -70,6 +70,16 @@ export const seatRunLabel = (status: ThreadRuntimeSummary["status"] | undefined) ? "Completed" : null; +/** + * The row label for a Crew seat the status pill is quiet about. A seat whose first start failed + * ran and ended, so how that run ended outranks "Not started", which is only for a seat still + * waiting for its first assignment. + */ +export const seatQuietLabel = (seat: { + readonly notStarted?: boolean | undefined; + readonly runtime?: Pick | null | undefined; +}) => seatRunLabel(seat.runtime?.status) ?? (seat.notStarted === true ? "Not started" : "Idle"); + /** "What is the state of this Crew?" answered from its seats, no Playbook required. */ export const summarizeCrewState = ( threads: ReadonlyArray, diff --git a/apps/web/src/j5/fleet/FleetPage.test.tsx b/apps/web/src/j5/fleet/FleetPage.test.tsx new file mode 100644 index 0000000000000..9e30a18d0ac14 --- /dev/null +++ b/apps/web/src/j5/fleet/FleetPage.test.tsx @@ -0,0 +1,79 @@ +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { renderToStaticMarkup } from "react-dom/server"; +import { expect, it } from "vite-plus/test"; + +import { FleetRowItem } from "./FleetPage"; +import type { FleetAgent, ScopedFleetLedgerProject } from "./fleetClient"; + +const environmentId = EnvironmentId.make("environment:local"); +const threadId = ThreadId.make("thread:builder"); +const project = { + id: "project:1", + title: "Project", + agents: [], + crews: [], + environmentId, + environmentLabel: "Local", +} as ScopedFleetLedgerProject; + +const seatRow = (input: { + readonly notStarted: boolean; + readonly runtimeStatus?: "failed" | "interrupted"; +}) => { + const thread = { + id: threadId, + environmentId, + title: "builder", + updatedAt: "2026-10-27T12:00:00.000Z", + archivedAt: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + ...(input.runtimeStatus === undefined + ? {} + : { runtime: { status: input.runtimeStatus, providerInstanceId: "codex" } }), + } as unknown as EnvironmentThreadShell; + const agent: FleetAgent = { + participantId: "agent:j5:a2a:thread:builder", + threadId, + displayName: "builder", + origin: "agent", + placementParentId: null, + crew: { + crewInstanceId: "crew:1", + crewName: "Review Pair", + seat: "builder", + notStarted: input.notStarted, + captainParticipantId: "agent:j5:a2a:thread:captain", + }, + openAsks: 0, + }; + return renderToStaticMarkup( +
    + undefined} + projectOf={() => undefined} + project={project} + row={{ agent, depth: 1, crewInstanceId: "crew:1" }} + badge={null} + /> +
, + ); +}; + +it("a Fleet seat row says Not started only while the seat is waiting for its first assignment", () => { + expect(seatRow({ notStarted: true })).toContain("Not started"); +}); + +it("a Fleet seat whose first start failed says how it ended, not Not started", () => { + const failed = seatRow({ notStarted: true, runtimeStatus: "failed" }); + expect(failed).toContain("Failed"); + expect(failed).not.toContain("Not started"); + const interrupted = seatRow({ notStarted: true, runtimeStatus: "interrupted" }); + expect(interrupted).toContain("Interrupted"); + expect(interrupted).not.toContain("Not started"); +}); diff --git a/apps/web/src/j5/fleet/FleetPage.tsx b/apps/web/src/j5/fleet/FleetPage.tsx index 5d69f0da43762..44c81688a051f 100644 --- a/apps/web/src/j5/fleet/FleetPage.tsx +++ b/apps/web/src/j5/fleet/FleetPage.tsx @@ -33,7 +33,12 @@ import { useLogicalProjects } from "../logicalProjects"; import { requestConfirmDialog } from "../../confirmDialog"; import { ArchiveWarningCrewSeats, type ArchiveWarningCrew } from "../a2a/ArchiveWarningContent"; import { archiveCrew } from "../crew/crewArchiveClient"; -import { crewHasRunningSeat, summarizeCrewState } from "../crew/crewState"; +import { + classifyCrewSeat, + crewHasRunningSeat, + seatQuietLabel, + summarizeCrewState, +} from "../crew/crewState"; import { stopCrew } from "../crew/crewStopClient"; import { countFleetProjects, @@ -752,7 +757,11 @@ export function FleetRowItem( diff --git a/apps/web/src/j5/threads/SpawnedChildren.test.tsx b/apps/web/src/j5/threads/SpawnedChildren.test.tsx new file mode 100644 index 0000000000000..bc764934b0afb --- /dev/null +++ b/apps/web/src/j5/threads/SpawnedChildren.test.tsx @@ -0,0 +1,72 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; +import { renderToStaticMarkup } from "react-dom/server"; +import { expect, it } from "vite-plus/test"; + +import { SpawnedChildGroupRows } from "./SpawnedChildren"; +import { groupSpawnedChildren, selectSpawnedChildRows } from "./spawnedChildren.logic"; + +const environmentId = EnvironmentId.make("environment:local"); +const threadId = ThreadId.make("thread:builder"); + +const seatRow = (input: { + readonly notStarted: boolean; + readonly runtimeStatus?: "failed" | "interrupted"; +}) => { + const thread = { + id: threadId, + environmentId, + title: "builder", + updatedAt: "2026-10-27T12:00:00.000Z", + archivedAt: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + ...(input.runtimeStatus === undefined + ? {} + : { runtime: { status: input.runtimeStatus, providerInstanceId: "codex" } }), + } as unknown as EnvironmentThreadShell; + const rows = selectSpawnedChildRows( + [ + { + threadId, + participantId: "agent:j5:a2a:thread:builder", + seat: { + crewInstanceId: "crew:1", + crewName: "Review Pair", + seat: "builder", + notStarted: input.notStarted, + }, + }, + ], + new Map([[threadId as string, thread]]), + ); + const [group] = groupSpawnedChildren(rows); + return renderToStaticMarkup( + undefined} + onOpen={() => undefined} + renamingThreadKey={null} + onContextMenu={() => undefined} + onCommitRename={() => undefined} + onCancelRename={() => undefined} + />, + ); +}; + +it("a seat row says Not started only while the seat is waiting for its first assignment", () => { + expect(seatRow({ notStarted: true })).toContain("Not started"); +}); + +it("a seat whose first start failed says how it ended, not Not started", () => { + const failed = seatRow({ notStarted: true, runtimeStatus: "failed" }); + expect(failed).toContain("Failed"); + expect(failed).not.toContain("Not started"); + const interrupted = seatRow({ notStarted: true, runtimeStatus: "interrupted" }); + expect(interrupted).toContain("Interrupted"); + expect(interrupted).not.toContain("Not started"); +}); diff --git a/apps/web/src/j5/threads/SpawnedChildren.tsx b/apps/web/src/j5/threads/SpawnedChildren.tsx index a3bc51904476d..55e9c2fbee76a 100644 --- a/apps/web/src/j5/threads/SpawnedChildren.tsx +++ b/apps/web/src/j5/threads/SpawnedChildren.tsx @@ -23,7 +23,7 @@ import { useThreadShells } from "../../state/entities"; import { environmentServerConfigsAtom } from "../../state/server"; import { buildThreadRouteParams } from "../../threadRoutes"; import { formatElapsedDurationLabel } from "../../timestampFormat"; -import { seatRunLabel } from "../crew/crewState"; +import { seatQuietLabel } from "../crew/crewState"; import { stopCrew } from "../crew/crewStopClient"; import { j5Environment } from "../state"; import { useSpawnedChildren, type SpawnedChild } from "./SpawnedChildrenClient"; @@ -166,7 +166,7 @@ function SpawnedChildrenRows( const childRowClassName = "flex w-full min-w-0 flex-col gap-0.5 rounded-md px-1.5 py-1 text-left outline-hidden hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"; -function SpawnedChildGroupRows( +export function SpawnedChildGroupRows( props: SpawnedChildActions & { readonly environmentId: EnvironmentId; readonly group: SpawnedChildGroup; @@ -283,10 +283,12 @@ function SpawnedChildGroupRows( {status === null ? ( - {child.seat?.notStarted - ? "Not started" - : ((child.seat === null ? null : seatRunLabel(thread.runtime?.status)) ?? - "Idle")} + {child.seat === null + ? "Idle" + : seatQuietLabel({ + notStarted: child.seat.notStarted, + runtime: thread.runtime, + })} ) : ( <> From c3bb58eed694425f55f1230f575d61dd56901712 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Wed, 28 Oct 2026 10:21:28 -0400 Subject: [PATCH 05/12] refactor(j5): stop unwrapping context-wrapped Crew envelopes (#745) The unwrap only served an envelope shape that was never merged, and it would cut authored text that begins with the marker. Co-Authored-By: Claude Sonnet 5.5 --- .../web/src/j5/a2a/ThreadA2ARenderer.test.tsx | 26 +++++-------------- apps/web/src/j5/a2a/ThreadA2ARenderer.tsx | 12 ++++----- packages/contracts/src/j5.ts | 2 -- 3 files changed, 11 insertions(+), 29 deletions(-) diff --git a/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx b/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx index ccccf8e02a3fa..b5702761043a0 100644 --- a/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx +++ b/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx @@ -1,4 +1,3 @@ -import { crewDeliveryContextPrefix } from "@t3tools/contracts/j5"; import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; import { renderToStaticMarkup } from "react-dom/server"; import { describe, expect, it } from "vite-plus/test"; @@ -834,24 +833,11 @@ describe("history recorded before the j5_ prefix", () => { }); }); -it("preserves an activating assignment's sender and reply obligation beneath Crew context", () => { - const original = presentThreadA2ADelivery({ message: message({ text: peerRaw }) }); - const text = crewDeliveryContextPrefix("Approved Crew context") + peerRaw; - expect(presentThreadA2ADelivery({ message: message({ text }) })).toEqual({ - ...original, - rawEnvelope: text, - }); -}); - -describe("Crew context in queued envelopes", () => { - it("keeps the sender and preview body when an older delivery carries Crew context", () => { - const wrapped = crewDeliveryContextPrefix("private Crew context") + peerRaw; - expect( - formatThreadA2AQueuedDelivery(wrapped, new Map([["agent:delivery-sender", "Alice"]])), - ).toEqual({ - label: "From Alice — Please verify the worker.", - tooltipParticipantId: null, - }); - expect(participantIdsForThreadA2AEnvelope(wrapped)).toEqual(["agent:delivery-sender"]); +it("shows authored text exactly as written, even when it begins with the Crew context marker", () => { + const authored = `\nmine\n\n\n${peerRaw}`; + expect(presentThreadA2ADelivery({ message: message({ text: authored }) })).toEqual({ + kind: "raw", + rawEnvelope: authored, }); + expect(participantIdsForThreadA2AEnvelope(authored)).toEqual([]); }); diff --git a/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx b/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx index e4b383920fbf8..adbb8cd66d7f0 100644 --- a/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx +++ b/apps/web/src/j5/a2a/ThreadA2ARenderer.tsx @@ -1,5 +1,4 @@ import { useAtomValue } from "@effect/atom-react"; -import { crewDeliveryAssignment } from "@t3tools/contracts/j5"; import { renderSharedConversationNote } from "../sharing/SharedConversationCards"; import { Tooltip, TooltipTrigger, TooltipPopup } from "../../components/ui/tooltip"; import { observeResize } from "~/lib/observeResize"; @@ -363,9 +362,8 @@ export function presentThreadA2ADelivery( const { message } = input; if (!isThreadA2ADeliveryMessage(message)) return null; - const assignment = crewDeliveryAssignment(message.text); if (message.createdBy === "agent") { - const peer = parseAgentAuthoredEnvelope(assignment); + const peer = parseAgentAuthoredEnvelope(message.text); if (peer) { const sender = presentParticipantIdentity({ participantId: peer.senderId, @@ -386,7 +384,7 @@ export function presentThreadA2ADelivery( }; } } else if (message.createdBy === "user") { - const human = parseHumanEnvelope(assignment); + const human = parseHumanEnvelope(message.text); if (human) { return { kind: "human", @@ -398,7 +396,7 @@ export function presentThreadA2ADelivery( }; } } else if (message.createdBy === "system") { - const silence = parseSilenceEnvelope(assignment); + const silence = parseSilenceEnvelope(message.text); if (silence) { return { kind: "silence", @@ -452,7 +450,7 @@ export function formatThreadA2AQueuedDelivery( text: string, participantLabels: ReadonlyMap, ): { readonly label: string; readonly tooltipParticipantId: string | null } | null { - const peer = parseAgentAuthoredEnvelope(crewDeliveryAssignment(text)); + const peer = parseAgentAuthoredEnvelope(text); if (peer === null) return null; const sender = presentParticipantIdentity({ participantId: peer.senderId, participantLabels }); const firstLine = peer.body.split("\n")[0]?.trim() ?? ""; @@ -463,7 +461,7 @@ export function formatThreadA2AQueuedDelivery( } export function participantIdsForThreadA2AEnvelope(text: string): ReadonlyArray { - const peer = parseAgentAuthoredEnvelope(crewDeliveryAssignment(text)); + const peer = parseAgentAuthoredEnvelope(text); return peer === null ? [] : [peer.senderId]; } diff --git a/packages/contracts/src/j5.ts b/packages/contracts/src/j5.ts index 97ca0b2eab135..7b3de9caba253 100644 --- a/packages/contracts/src/j5.ts +++ b/packages/contracts/src/j5.ts @@ -1280,5 +1280,3 @@ export const J5ClientReadRpcGroup = RpcGroup.make( stream: true, }), ); - -export { crewDeliveryContextPrefix, crewDeliveryAssignment } from "./j5/crewDeliveryContext.ts"; From aa9cd8464b60791f4fbfa5087d26c57e18d7e28c Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Wed, 28 Oct 2026 10:21:30 -0400 Subject: [PATCH 06/12] docs(j5): Crew delivery, steering, introduction and Not started as they now behave (#745) Co-Authored-By: Claude Sonnet 5.5 --- FORK.md | 8 ++++---- docs/j5/product/a2a/agent-tools.md | 2 +- docs/j5/product/features/crews.md | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/FORK.md b/FORK.md index 9321dda4d813c..3def0e8a96ae4 100644 --- a/FORK.md +++ b/FORK.md @@ -483,7 +483,7 @@ migrations after upstream migrations. 88. Agent Setup and Crew approval settings ([#743](https://github.com/Jacksondr5/j5code/issues/743)): `packages/contracts/src/settings.ts` registers J5's `crewAutoApprove` boolean (default off) in server settings, patches, and project overrides. `apps/web/src/components/settings/settingsSearch.ts` renames the existing `/settings/personas` destination to Agent Setup and adds search terms and the scoped Crew setting target. `apps/mobile/src/features/settings/SettingsRouteScreen.tsx` and `apps/mobile/src/Stack.tsx` rename the existing Personas navigation entry and title to Agent Setup. Runtime behavior and the web sections stay in J5-owned files; mobile still exposes only the persona library. -89. Deferred Crew assignments ([#745](https://github.com/Jacksondr5/j5code/issues/745)): `orchestration-v2/runtimeLayer.ts` wraps the shared orchestrator with J5-owned `CrewDeliveryContext.ts` for first-assignment workspace preparation and guards, and supplies J5-owned `CrewTurnContext.ts` to provider turn start. `orchestration-v2/ProviderTurnStartService.ts` delegates the selected assignment's text to that service immediately around provider delivery. The service builds the approved introduction or net roster changes from the current roster, and records them only after the provider accepts the prompt. Editable messages and shared author prefixes stay unchanged, so queued edits, cancellations and reordering cannot consume context. Waiting seats whose Crew is retired fail visibly; a retained worktree guard applies even after retirement. J5 migration 49 owns the context, and `CrewSeatPreparation.ts` uses upstream's persisted preparation path. `orchestration-v2/ProviderTurnStartService.test.ts` exercises this hook on a retained native conversation with no history handoff, including provider-before-acknowledgment order. Non-Crew threads keep upstream delivery unchanged. On an advance, retain the hook at actual delivery after queue selection, shared by every provider and transport. +89. Deferred Crew assignments ([#745](https://github.com/Jacksondr5/j5code/issues/745)): `orchestration-v2/runtimeLayer.ts` wraps the shared orchestrator with J5-owned `CrewDeliveryContext.ts` for first-assignment workspace preparation and guards, and supplies J5-owned `CrewTurnContext.ts` to provider turn start and provider turn control. `orchestration-v2/ProviderTurnStartService.ts` asks that service whether the thread is a Crew seat (one indexed read) and delegates only a seat's selected assignment text to it immediately around provider delivery; every other thread keeps upstream's fast path and delivery unchanged, and `CrewDeliveryContext.ts` likewise passes any non-seat thread's dispatch straight through. `orchestration-v2/ProviderTurnControlService.ts` wraps the live session with the service's `steering`, one hook beside upstream's `steerTurn` call, so a message steered into a busy seat carries the current context too. The service builds the approved introduction or net roster changes from the current roster, sends the full introduction again when the provider conversation it reached is replaced (a model or provider switch, or a missing native session rebuilt from history), and records what it sent only after the provider accepts the prompt; a send that never happens (the run was stopped or superseded before `startTurn`) leaves it owed. Editable messages and shared author prefixes stay unchanged, so queued edits, cancellations and reordering cannot consume context. Waiting seats whose Crew is retired fail visibly; a retained worktree guard applies even after retirement. J5 migration 49 owns the context, and `CrewSeatPreparation.ts` uses upstream's persisted preparation path. `orchestration-v2/ProviderTurnStartService.test.ts` and `ProviderTurnControlService.test.ts` exercise the hooks against the real seat context, including a retained and a replaced native conversation and a Stop before the provider send. On an advance, retain the hooks at actual delivery and steering after queue selection, shared by every provider and transport. ## Pin and upstream advance runbook @@ -789,9 +789,9 @@ explicitly marked. | `packages/provider-core/src/server/orchestrationInstructions.test.ts` | N | 8, B | | `packages/provider-core/src/server/orchestrationInstructions.ts` | N | 8, B | | `packages/provider-pi/src/server/mcpExtensionSource.test.ts` | N | 8 | -| `apps/server/src/orchestration-v2/ProviderTurnControlService.ts` | R | 26 | -| `apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts` | A | N | -| `apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts` | N | 89 | +| `apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts` | N | 89 | +| `apps/server/src/orchestration-v2/ProviderTurnControlService.ts` | R | 26, 89 | +| `apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts` | A | N, 89 | | `apps/server/src/orchestration-v2/ProviderTurnStartService.ts` | A | 30, N, 89 | | `apps/server/src/orchestration-v2/RunFinalizationService.ts` | R | 30 | | `apps/server/src/orchestration-v2/ThreadLaunchService.ts` | R | Saved-agent launch | diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index aa2e5787a3b40..6d1dd61a2d249 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -401,7 +401,7 @@ run; `j5_stop_crew` doesn't, and unarchiving doesn't restart it. 5. A `j5_send_message` to the caller itself is refused with an error naming the caller's own id. 6. `j5_list_participants` marks the caller's row `self`, reports a person's row as unable to receive a plain message and able to be asked, and omits provider Subagents. 7. `j5_spawn_agent` refuses a call that omits provider, model, or reasoning, refuses a choice outside the Role's allowlist with an error naming the Role, and refuses a caller that sits in a Crew with an error naming escalation to its Captain. -8. A spawned agent's first turn contains its own participant id and project. A Crew seat receives its approved instructions, shared brief, current roster with responsibilities and participant ids, and any playbook or handoff obligation on its first assignment; the assignment keeps its own envelope and reply obligation. Later assignments reuse the same thread without repeating that introduction. Started members receive net roster changes at the top of their next delivery, without a separate turn. +8. A spawned agent's first turn contains its own participant id and project. A Crew seat receives its approved instructions, shared brief, current roster with responsibilities and participant ids, and any playbook or handoff obligation on its first assignment; the assignment keeps its own envelope and reply obligation. Later assignments reuse the same thread without repeating that introduction, unless the provider conversation was replaced, which sends it again. Started members receive net roster changes at the top of their next delivery, including a message steered into a running turn, without a separate turn. 9. `j5_stop_agent` and `t3_thread_organize` act on one target; neither cascades. `j5_stop_agent` reaches an agent in any project on this server, and refuses a target that runs with broader permission modes than the caller unless the caller is that seat's Captain. A stopped run is never resumed after a server restart, even when restart continuation is enabled. 10. `t3_thread_organize` archives and restores any thread in the environment that upstream's access check lets the caller act on. Archive closes Exchanges through the shared reactor without a confirmation-token exchange or interrupting an existing run; human archive warnings remain. 11. `j5_clear_own_ask` closes only an Exchange the caller opened and records the closure as sender-cleared. diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index 07bfde5a672b9..1be59dc8eb788 100644 --- a/docs/j5/product/features/crews.md +++ b/docs/j5/product/features/crews.md @@ -69,7 +69,7 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif ### Handoff artifacts -12. A seat whose definition declares an output artifact writes it as its handoff artifact in the project's artifacts; its first turn names the exact path. The first assignment carries its playbook context and handoff obligation; a later assignment reuses the same thread and workspace without repeating its introduction. Members that finished remain available on the roster. Started members receive net roster changes, naming who joined or left and their responsibility, at the top of their next delivery. Waiting members receive the current roster with their first assignment. Context is attached at provider delivery, after queued edits, cancellations, and reordering; a rejected provider start leaves it owed. A waiting member whose Crew retired must have its Crew restored before starting, and a worktree seat cannot fall back to the project root. Roster changes alone start no turns, and availability produces no polling or acknowledgment turns. +12. A seat whose definition declares an output artifact writes it as its handoff artifact in the project's artifacts; its first turn names the exact path. The first assignment carries its playbook context and handoff obligation; a later assignment reuses the same thread and workspace without repeating its introduction, unless the provider conversation was replaced (a model or provider switch, or a native session the provider lost), in which case the introduction is sent again with the current roster. Members that finished remain available on the roster. Started members receive net roster changes, naming who joined or left and their responsibility, at the top of their next delivery, including a message steered into a turn in progress. Waiting members receive the current roster with their first assignment. Context is attached at provider delivery, after queued edits, cancellations, and reordering; a start that never reaches the provider, because it was refused, stopped, or superseded, leaves it owed. A waiting member whose Crew retired must have its Crew restored before starting, and a worktree seat cannot fall back to the project root. Roster changes alone start no turns, and availability produces no polling or acknowledgment turns. 13. When a seat finishes, the Captain receives a notice that leads with how the run ended and, for a failed run, carries the run's recorded error, then whether the seat's handoff artifact was written, missing, unavailable with the reason it can never be read, or never declared, a written handoff artifact riding inline when short and by path otherwise; a finish whose notice would repeat the seat's last one is silent, and a notice arriving while the Captain's turn runs folds into the seat notice already queued behind it rather than queuing another turn. 14. A seat that finishes without its handoff artifact is reminded once and is reported to its Captain on its next finished run whatever happened. @@ -88,7 +88,7 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif ### State -22. A Crew's Fleet row and Captain's expander summarize measured seat states, including Not started separately from idle, running, failed, needing a person, settled, and unknown. Not started means creation succeeded and the provider has not accepted its first assignment. Stop, archive, settle, and unarchive treat waiting seats as idle seats. A failed last run reads as failed; nothing is inferred from silence. A seat with a finished run still reads Failed, Interrupted, or Completed. In the Captain's timeline, a roster approval shows “Crew approved · N members”, plus “· by ” in a shared conversation, where more than one person could have approved it; other notices show a line only for a seat that needs attention. A clean finish adds no line. +22. A Crew's Fleet row and Captain's expander summarize measured seat states, including Not started separately from idle, running, failed, needing a person, settled, and unknown. Not started means creation succeeded and the seat is still waiting for its first assignment; a seat whose first start ran and failed or was interrupted reads that instead. Stop, archive, settle, and unarchive treat waiting seats as idle seats. A failed last run reads as failed; nothing is inferred from silence. A seat with a finished run still reads Failed, Interrupted, or Completed. In the Captain's timeline, a roster approval shows “Crew approved · N members”, plus “· by ” in a shared conversation, where more than one person could have approved it; other notices show a line only for a seat that needs attention. A clean finish adds no line. ### Several people From 9f04c4637f37c160f94a3ac705c3b21c8c95b541 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Thu, 29 Oct 2026 08:18:28 -0400 Subject: [PATCH 07/12] fix(web): carry the Not started seat label onto the Fleet fact cells (#745) Co-Authored-By: Claude Sonnet 5.5 --- apps/web/src/j5/fleet/FleetPage.test.tsx | 10 +++------- apps/web/src/j5/fleet/FleetPage.tsx | 17 +++++++++++------ 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/apps/web/src/j5/fleet/FleetPage.test.tsx b/apps/web/src/j5/fleet/FleetPage.test.tsx index 9e30a18d0ac14..16f1542f14074 100644 --- a/apps/web/src/j5/fleet/FleetPage.test.tsx +++ b/apps/web/src/j5/fleet/FleetPage.test.tsx @@ -69,11 +69,7 @@ it("a Fleet seat row says Not started only while the seat is waiting for its fir expect(seatRow({ notStarted: true })).toContain("Not started"); }); -it("a Fleet seat whose first start failed says how it ended, not Not started", () => { - const failed = seatRow({ notStarted: true, runtimeStatus: "failed" }); - expect(failed).toContain("Failed"); - expect(failed).not.toContain("Not started"); - const interrupted = seatRow({ notStarted: true, runtimeStatus: "interrupted" }); - expect(interrupted).toContain("Interrupted"); - expect(interrupted).not.toContain("Not started"); +it("a Fleet seat whose first start failed does not say Not started", () => { + expect(seatRow({ notStarted: true, runtimeStatus: "failed" })).not.toContain("Not started"); + expect(seatRow({ notStarted: true, runtimeStatus: "interrupted" })).not.toContain("Not started"); }); diff --git a/apps/web/src/j5/fleet/FleetPage.tsx b/apps/web/src/j5/fleet/FleetPage.tsx index 44c81688a051f..45eefb67b3887 100644 --- a/apps/web/src/j5/fleet/FleetPage.tsx +++ b/apps/web/src/j5/fleet/FleetPage.tsx @@ -83,12 +83,17 @@ const threadFor = ( threadsByKey: ThreadLookup, environmentId: EnvironmentId, agent: FleetAgent, -): EnvironmentThreadShell | undefined => - agent.threadId === null - ? undefined - : threadsByKey.get( - scopedThreadKey(scopeThreadRef(environmentId, ThreadId.make(agent.threadId))), - ); +): (EnvironmentThreadShell & { readonly notStarted?: boolean }) | undefined => { + const thread = + agent.threadId === null + ? undefined + : threadsByKey.get( + scopedThreadKey(scopeThreadRef(environmentId, ThreadId.make(agent.threadId))), + ); + return thread === undefined || agent.crew?.notStarted === undefined + ? thread + : { ...thread, notStarted: agent.crew.notStarted }; +}; const projectKey = (ledgerProject: ScopedFleetLedgerProject) => `${ledgerProject.environmentId}:${ledgerProject.id}`; From 9b368df8e22e71afa0f29466967ab117b6aa054d Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Mon, 2 Nov 2026 09:41:04 -0500 Subject: [PATCH 08/12] fix(j5): drop the static-markup seat label tests; crewState covers the label Co-Authored-By: Claude Sonnet 5.5 --- apps/web/src/j5/crew/crewState.test.ts | 12 +++ apps/web/src/j5/fleet/FleetPage.test.tsx | 75 ------------------- .../src/j5/threads/SpawnedChildren.test.tsx | 72 ------------------ 3 files changed, 12 insertions(+), 147 deletions(-) delete mode 100644 apps/web/src/j5/fleet/FleetPage.test.tsx delete mode 100644 apps/web/src/j5/threads/SpawnedChildren.test.tsx diff --git a/apps/web/src/j5/crew/crewState.test.ts b/apps/web/src/j5/crew/crewState.test.ts index feb5b19b05980..bd392dc5c9b58 100644 --- a/apps/web/src/j5/crew/crewState.test.ts +++ b/apps/web/src/j5/crew/crewState.test.ts @@ -4,6 +4,7 @@ import { classifyCrewSeat, crewHasRunningSeat, formatCrewStateSummary, + seatQuietLabel, seatRunLabel, summarizeCrewState, type CrewSeatThread, @@ -110,4 +111,15 @@ describe("crew state", () => { expect(seatRunLabel("idle")).toBeNull(); expect(seatRunLabel(undefined)).toBeNull(); }); + + it("reads Not started only for a seat that never ran, and how its run ended otherwise", () => { + expect(seatQuietLabel({ notStarted: true })).toBe("Not started"); + expect(seatQuietLabel({ notStarted: true, runtime: { status: "idle" } })).toBe("Not started"); + expect(seatQuietLabel({ notStarted: true, runtime: { status: "failed" } })).toBe("Failed"); + expect(seatQuietLabel({ notStarted: true, runtime: { status: "interrupted" } })).toBe( + "Interrupted", + ); + expect(seatQuietLabel({ notStarted: false })).toBe("Idle"); + expect(seatQuietLabel({})).toBe("Idle"); + }); }); diff --git a/apps/web/src/j5/fleet/FleetPage.test.tsx b/apps/web/src/j5/fleet/FleetPage.test.tsx deleted file mode 100644 index 16f1542f14074..0000000000000 --- a/apps/web/src/j5/fleet/FleetPage.test.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; -import { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import { renderToStaticMarkup } from "react-dom/server"; -import { expect, it } from "vite-plus/test"; - -import { FleetRowItem } from "./FleetPage"; -import type { FleetAgent, ScopedFleetLedgerProject } from "./fleetClient"; - -const environmentId = EnvironmentId.make("environment:local"); -const threadId = ThreadId.make("thread:builder"); -const project = { - id: "project:1", - title: "Project", - agents: [], - crews: [], - environmentId, - environmentLabel: "Local", -} as ScopedFleetLedgerProject; - -const seatRow = (input: { - readonly notStarted: boolean; - readonly runtimeStatus?: "failed" | "interrupted"; -}) => { - const thread = { - id: threadId, - environmentId, - title: "builder", - updatedAt: "2026-10-27T12:00:00.000Z", - archivedAt: null, - hasPendingApprovals: false, - hasPendingUserInput: false, - modelSelection: { instanceId: "codex", model: "gpt-5.4" }, - ...(input.runtimeStatus === undefined - ? {} - : { runtime: { status: input.runtimeStatus, providerInstanceId: "codex" } }), - } as unknown as EnvironmentThreadShell; - const agent: FleetAgent = { - participantId: "agent:j5:a2a:thread:builder", - threadId, - displayName: "builder", - origin: "agent", - placementParentId: null, - crew: { - crewInstanceId: "crew:1", - crewName: "Review Pair", - seat: "builder", - notStarted: input.notStarted, - captainParticipantId: "agent:j5:a2a:thread:captain", - }, - openAsks: 0, - }; - return renderToStaticMarkup( -
    - undefined} - projectOf={() => undefined} - project={project} - row={{ agent, depth: 1, crewInstanceId: "crew:1" }} - badge={null} - /> -
, - ); -}; - -it("a Fleet seat row says Not started only while the seat is waiting for its first assignment", () => { - expect(seatRow({ notStarted: true })).toContain("Not started"); -}); - -it("a Fleet seat whose first start failed does not say Not started", () => { - expect(seatRow({ notStarted: true, runtimeStatus: "failed" })).not.toContain("Not started"); - expect(seatRow({ notStarted: true, runtimeStatus: "interrupted" })).not.toContain("Not started"); -}); diff --git a/apps/web/src/j5/threads/SpawnedChildren.test.tsx b/apps/web/src/j5/threads/SpawnedChildren.test.tsx deleted file mode 100644 index bc764934b0afb..0000000000000 --- a/apps/web/src/j5/threads/SpawnedChildren.test.tsx +++ /dev/null @@ -1,72 +0,0 @@ -import { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; -import { renderToStaticMarkup } from "react-dom/server"; -import { expect, it } from "vite-plus/test"; - -import { SpawnedChildGroupRows } from "./SpawnedChildren"; -import { groupSpawnedChildren, selectSpawnedChildRows } from "./spawnedChildren.logic"; - -const environmentId = EnvironmentId.make("environment:local"); -const threadId = ThreadId.make("thread:builder"); - -const seatRow = (input: { - readonly notStarted: boolean; - readonly runtimeStatus?: "failed" | "interrupted"; -}) => { - const thread = { - id: threadId, - environmentId, - title: "builder", - updatedAt: "2026-10-27T12:00:00.000Z", - archivedAt: null, - hasPendingApprovals: false, - hasPendingUserInput: false, - modelSelection: { instanceId: "codex", model: "gpt-5.4" }, - ...(input.runtimeStatus === undefined - ? {} - : { runtime: { status: input.runtimeStatus, providerInstanceId: "codex" } }), - } as unknown as EnvironmentThreadShell; - const rows = selectSpawnedChildRows( - [ - { - threadId, - participantId: "agent:j5:a2a:thread:builder", - seat: { - crewInstanceId: "crew:1", - crewName: "Review Pair", - seat: "builder", - notStarted: input.notStarted, - }, - }, - ], - new Map([[threadId as string, thread]]), - ); - const [group] = groupSpawnedChildren(rows); - return renderToStaticMarkup( - undefined} - onOpen={() => undefined} - renamingThreadKey={null} - onContextMenu={() => undefined} - onCommitRename={() => undefined} - onCancelRename={() => undefined} - />, - ); -}; - -it("a seat row says Not started only while the seat is waiting for its first assignment", () => { - expect(seatRow({ notStarted: true })).toContain("Not started"); -}); - -it("a seat whose first start failed says how it ended, not Not started", () => { - const failed = seatRow({ notStarted: true, runtimeStatus: "failed" }); - expect(failed).toContain("Failed"); - expect(failed).not.toContain("Not started"); - const interrupted = seatRow({ notStarted: true, runtimeStatus: "interrupted" }); - expect(interrupted).toContain("Interrupted"); - expect(interrupted).not.toContain("Not started"); -}); From cc57ff9119946ab0cdc0e7c2b82a24bc212cdaa3 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Mon, 2 Nov 2026 09:42:53 -0500 Subject: [PATCH 09/12] fix(j5): Crew seat context writes and announces only when it changes; the roster keeps launch names A follow-up or steer to a seat whose roster and conversation are unchanged no longer updates the seat context or bumps the crew and fleet feeds. The delivered roster names each seat as it was launched instead of by persona id. Co-Authored-By: Claude Sonnet 5.5 --- .../src/j5/a2a/CrewDeliveryContext.test.ts | 77 ++++++++++++++++++- .../src/j5/a2a/CrewLaunchService.test.ts | 4 + apps/server/src/j5/a2a/CrewLaunchService.ts | 4 +- apps/server/src/j5/a2a/CrewTurnContext.ts | 41 +++++++--- .../migrations/049_CrewSeatActivation.test.ts | 9 ++- .../a2a/migrations/049_CrewSeatActivation.ts | 3 +- 6 files changed, 121 insertions(+), 17 deletions(-) diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts index 7b66a9b93d55f..02bb4ab72274f 100644 --- a/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts @@ -19,6 +19,8 @@ import { type CommandReceiptV2, } from "../../orchestration-v2/CommandReceiptStore.ts"; import * as Crews from "./AgentCrewInstanceService.ts"; +import { ReadChanges } from "./ReadChanges.ts"; +import * as Stream from "effect/Stream"; import * as DeliveryContext from "./CrewDeliveryContext.ts"; import { participantIdForThread } from "./HomeRegistrar.ts"; import { A2ALedger, layer as ledgerLayer } from "./LedgerService.ts"; @@ -122,7 +124,18 @@ const fixture = Effect.gen(function* () { Effect.gen(function* () { return yield* (yield* Orchestrator.OrchestratorV2).dispatch(command); }); - const deliveryLayer = CrewTurnContext.layer; + const notified: Array> = []; + const deliveryLayer = CrewTurnContext.layerWithChanges.pipe( + Layer.provide( + Layer.succeed( + ReadChanges, + ReadChanges.of({ + notify: (...keys) => Effect.sync(() => void notified.push(keys)), + changes: Stream.empty, + }), + ), + ), + ); const providerThread = (native: string) => ({ id: "provider-thread:reviewer", @@ -174,6 +187,7 @@ const fixture = Effect.gen(function* () { send, deliver, steer, + notified, }; }); @@ -361,6 +375,67 @@ it.effect("the introduction is sent again only when the provider conversation ch }).pipe(Effect.provide(base)), ); +it.effect("a delivery that changes nothing writes and announces nothing", () => + Effect.gen(function* () { + const f = yield* fixture; + yield* f.sql`CREATE TABLE seat_context_writes (n INTEGER)`; + yield* f.sql`CREATE TRIGGER count_seat_context_writes AFTER UPDATE ON j5_crew_seat_context + BEGIN INSERT INTO seat_context_writes VALUES (1); END`; + const writes = () => + f.sql<{ readonly n: number }>`SELECT count(*) AS n FROM seat_context_writes`.pipe( + Effect.map(([row]) => row!.n), + ); + + yield* f.deliver("first", { native: "native-1" }); + assert.equal(yield* writes(), 1); + assert.lengthOf(f.notified, 1); + + yield* f.deliver("follow-up", { native: "native-1" }); + yield* f.steer("steer"); + assert.equal(yield* writes(), 1); + assert.lengthOf(f.notified, 1); + + yield* f.crews.addMembers("crew:test", [member("security")]); + yield* f.deliver("after the roster changed", { native: "native-1" }); + assert.equal(yield* writes(), 2); + assert.deepStrictEqual(f.notified.at(-1), ["crew", "fleet"]); + assert.lengthOf(f.notified, 2); + + yield* f.deliver("replaced conversation", { native: "native-2" }); + assert.equal(yield* writes(), 3); + yield* f.deliver("and again", { native: "native-2" }); + assert.equal(yield* writes(), 3); + assert.lengthOf(f.notified, 3); + }).pipe(Effect.provide(base)), +); + +it.effect("a refused delivery records nothing, so the next one still carries what is owed", () => + Effect.gen(function* () { + const f = yield* fixture; + yield* f.deliver("first"); + yield* f.crews.addMembers("crew:test", [member("security")]); + yield* f.deliver("refused", { fail: true }).pipe(Effect.result); + assert.lengthOf(f.notified, 1); + assert.include((yield* f.deliver("accepted"))!, "joined: security:"); + assert.lengthOf(f.notified, 2); + }).pipe(Effect.provide(base)), +); + +it.effect("the roster names each seat as it was launched, not by its persona id", () => + Effect.gen(function* () { + const f = yield* fixture; + yield* f.sql`INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace, agent_display_name) + VALUES ('thread:builder', '', '{"type":"shared"}', 'Team Builder')`; + yield* f.sql`UPDATE j5_agent_crew_member SET agent_id = 'builder-persona' WHERE seat_name = 'builder'`; + const prompt = (yield* f.deliver("first"))!; + assert.include(prompt, "- builder: participant_id="); + assert.include(prompt, "persona=Team Builder"); + assert.notInclude(prompt, "builder-persona"); + assert.include(prompt, "- reviewer (you):"); + assert.include(prompt, "persona=custom"); + }).pipe(Effect.provide(base)), +); + it.effect("a migrated seat has no introduction to send again", () => Effect.gen(function* () { const f = yield* fixture; diff --git a/apps/server/src/j5/a2a/CrewLaunchService.test.ts b/apps/server/src/j5/a2a/CrewLaunchService.test.ts index b6923c3bb563c..2aa6f5cebb55f 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.test.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.test.ts @@ -494,6 +494,10 @@ it.effect( assert.include(brief, "\nWrite the running notes."); assert.notInclude(brief, ""); assert.include(brief, "persona=custom"); + const [stored] = yield* (yield* SqlClient.SqlClient)<{ + readonly agent_display_name: string | null; + }>`SELECT agent_display_name FROM j5_crew_seat_context WHERE first_turn_text LIKE '%your_seat: scribe%'`; + assert.equal(stored?.agent_display_name, "custom"); // A persona Captain runs under its persona's policy (workspace write, auto-accept-edits here) // and has the person supervising it; its custom seat still defaults to Full access. diff --git a/apps/server/src/j5/a2a/CrewLaunchService.ts b/apps/server/src/j5/a2a/CrewLaunchService.ts index a0cb56c8416c7..d73163f6dc2c3 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.ts @@ -703,8 +703,8 @@ export const layer = Layer.effect( }); const workspaceJson = yield* encodeWorkspace(member.workspace); yield* sql` - INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace) - VALUES (${member.threadId}, ${text}, ${workspaceJson}) + INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace, agent_display_name) + VALUES (${member.threadId}, ${text}, ${workspaceJson}, ${member.agentDisplayName}) ON CONFLICT (thread_id) DO NOTHING `; } diff --git a/apps/server/src/j5/a2a/CrewTurnContext.ts b/apps/server/src/j5/a2a/CrewTurnContext.ts index e2e9b12d84a7d..0a64d19385549 100644 --- a/apps/server/src/j5/a2a/CrewTurnContext.ts +++ b/apps/server/src/j5/a2a/CrewTurnContext.ts @@ -106,10 +106,20 @@ const make = Effect.gen(function* () { } const crew = yield* crews.read(membership.crewInstanceId); if (crew === null) return yield* new CrewTurnContextError({ threadId }); + // The name each seat was launched with; a seat from before it was recorded falls back to + // its persona id. + const launched = yield* sql<{ + readonly thread_id: string; + readonly agent_display_name: string | null; + }>` + SELECT thread_id, agent_display_name FROM j5_crew_seat_context + WHERE thread_id IN ${sql.in(crew.members.map((member) => member.threadId))} + `; + const displayNames = new Map(launched.map((row) => [row.thread_id, row.agent_display_name])); const roster = crew.members.map((member) => ({ seat: member.seatName, participantId: member.participantId, - agentDisplayName: member.agentId ?? "custom", + agentDisplayName: displayNames.get(member.threadId) ?? member.agentId ?? "custom", reason: member.reason, })); const rosterJson = encodeRoster(roster); @@ -152,17 +162,22 @@ const make = Effect.gen(function* () { ].join("\n"); } + // Only a first delivery, a new roster or a new conversation changes what the Crew reads. + const unchanged = + context.delivered_roster === rosterJson && context.delivered_conversation === conversation; return { prefix: deliveryContext(prefix), - delivered: sql` - UPDATE j5_crew_seat_context - SET delivered_roster = ${rosterJson}, delivered_conversation = ${conversation} - WHERE thread_id = ${threadId} - `.pipe( - Effect.andThen(changes.notify("crew", "fleet")), - Effect.asVoid, - Effect.mapError((cause) => new CrewTurnContextError({ threadId, cause })), - ), + delivered: unchanged + ? Effect.void + : sql` + UPDATE j5_crew_seat_context + SET delivered_roster = ${rosterJson}, delivered_conversation = ${conversation} + WHERE thread_id = ${threadId} + `.pipe( + Effect.andThen(changes.notify("crew", "fleet")), + Effect.asVoid, + Effect.mapError((cause) => new CrewTurnContextError({ threadId, cause })), + ), }; }).pipe( Effect.mapError((cause) => @@ -211,7 +226,9 @@ const make = Effect.gen(function* () { return CrewTurnContext.of({ isSeat, deliver, steering }); }); -export const layer = Layer.effect(CrewTurnContext, make).pipe( +/** The service over the caller's `ReadChanges`, so a test can watch what it announces. */ +export const layerWithChanges = Layer.effect(CrewTurnContext, make).pipe( Layer.provide(Crews.layer), - Layer.provide(ReadChanges.layer), ); + +export const layer = layerWithChanges.pipe(Layer.provide(ReadChanges.layer)); diff --git a/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts index 645c468c7ddd7..cb6a42651967a 100644 --- a/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts +++ b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts @@ -55,7 +55,14 @@ it.effect( `; assert.deepStrictEqual( columns.map((column) => column.name), - ["thread_id", "first_turn_text", "workspace", "delivered_roster", "delivered_conversation"], + [ + "thread_id", + "first_turn_text", + "workspace", + "delivered_roster", + "delivered_conversation", + "agent_display_name", + ], ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.ts b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.ts index c349b32a0f36d..ed7847a1bcc4b 100644 --- a/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.ts +++ b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.ts @@ -9,7 +9,8 @@ export default Effect.gen(function* () { first_turn_text TEXT NOT NULL, workspace TEXT NOT NULL, delivered_roster TEXT, - delivered_conversation TEXT + delivered_conversation TEXT, + agent_display_name TEXT ) `; yield* sql` From 0f5140efea1203b5a7328a7e85699bd63751ceb8 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Mon, 2 Nov 2026 11:38:00 -0500 Subject: [PATCH 10/12] feat(j5): a Crew member's thread keeps what it was told A record-only platform message joins a thread's history without starting a run. When a seat's prompt carrying the introduction or a roster change is accepted, the seat's thread records that text once. Co-Authored-By: Claude Sonnet 5.5 --- .../CrewDeliveryContext.integration.test.ts | 10 +- .../src/j5/a2a/CrewDeliveryContext.test.ts | 119 ++++++++++++++- apps/server/src/j5/a2a/CrewTurnContext.ts | 33 ++++- apps/server/src/j5/a2a/spawnIds.ts | 19 +++ .../Orchestrator.platform-message.test.ts | 139 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 82 +++++++++++ .../ProviderTurnControlService.test.ts | 7 +- .../ProviderTurnStartService.test.ts | 5 + .../ProviderTurnStartService.ts | 1 + .../src/orchestration-v2/runtimeLayer.ts | 68 +++++---- packages/contracts/src/orchestrationV2.ts | 13 ++ 11 files changed, 453 insertions(+), 43 deletions(-) create mode 100644 apps/server/src/orchestration-v2/Orchestrator.platform-message.test.ts diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts index 645785bb9c421..4fb3fb4132f81 100644 --- a/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts @@ -43,7 +43,7 @@ it.effect( harness.layer, Crews.layer.pipe(Layer.provide(harness.layer)), ledgerLayer.pipe(Layer.provide(harness.layer)), - CrewTurnContext.layer.pipe(Layer.provide(harness.layer)), + CrewTurnContext.layer.pipe(Layer.provide(Layer.merge(harness.layer, harness.orchestrator))), ); const layer = Preparation.layer.pipe( Layer.provideMerge(services), @@ -168,6 +168,7 @@ it.effect( yield* crewContext.deliver( { threadId, + runId: ready.runs[0]!.id, providerThread: { id: "provider-thread:crew-reviewer", nativeThreadRef: null, @@ -183,6 +184,13 @@ it.effect( return prompt; }); assert.include(yield* promptFor(ready.messages[0]!.text), "Shared goal"); + // The member's thread keeps what it was told, once, and the record starts no run. + const introduced = yield* threads.getThreadProjection(threadId); + const kept = introduced.messages.filter((message) => message.createdBy === "system"); + assert.lengthOf(kept, 1); + assert.include(kept[0]!.text, "\nShared goal\n"); + assert.notInclude(kept[0]!.text, "Review the code now."); + assert.lengthOf(introduced.runs, ready.runs.length); yield* crews.addMembers("crew:integration", [ { seatName: "tester", diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts index 02bb4ab72274f..b38868f792eec 100644 --- a/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts @@ -3,6 +3,7 @@ import { assert, it } from "@effect/vitest"; import { CommandId, MessageId, + RunId, ThreadId, type OrchestrationV2ServerCommand, } from "@t3tools/contracts"; @@ -125,17 +126,39 @@ const fixture = Effect.gen(function* () { return yield* (yield* Orchestrator.OrchestratorV2).dispatch(command); }); const notified: Array> = []; + // What the member's thread was asked to keep, with a receipt's replay: a command id seen twice + // lands once. + const recorded = yield* Ref.make>([]); + const recording = { fails: false }; + const recorder = Layer.mock(Orchestrator.OrchestratorV2)({ + dispatch: (command) => + Effect.gen(function* () { + if (recording.fails) + return yield* new Orchestrator.OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + }); + yield* Ref.update(recorded, (all) => + all.some((seen) => seen.commandId === command.commandId) ? all : [...all, command], + ); + return { sequence: 1, storedEvents: [] }; + }), + }); const deliveryLayer = CrewTurnContext.layerWithChanges.pipe( Layer.provide( - Layer.succeed( - ReadChanges, - ReadChanges.of({ - notify: (...keys) => Effect.sync(() => void notified.push(keys)), - changes: Stream.empty, - }), + Layer.merge( + recorder, + Layer.succeed( + ReadChanges, + ReadChanges.of({ + notify: (...keys) => Effect.sync(() => void notified.push(keys)), + changes: Stream.empty, + }), + ), ), ), ); + const runId = RunId.make("run:reviewer"); const providerThread = (native: string) => ({ id: "provider-thread:reviewer", @@ -149,7 +172,12 @@ const fixture = Effect.gen(function* () { Effect.gen(function* () { let prompt: string | null = null; yield* (yield* CrewTurnContext.CrewTurnContext).deliver( - { threadId: seatId, providerThread: providerThread(options.native ?? "native-1"), text }, + { + threadId: seatId, + runId: runId, + providerThread: providerThread(options.native ?? "native-1"), + text, + }, (sent) => options.fail === true ? Effect.fail("provider refused") @@ -171,6 +199,7 @@ const fixture = Effect.gen(function* () { }); yield* session.steerTurn({ threadId: seatId, + runId, providerThread: providerThread("native-1"), message: { text }, } as never); @@ -188,6 +217,8 @@ const fixture = Effect.gen(function* () { deliver, steer, notified, + recorded, + recording, }; }); @@ -480,3 +511,77 @@ it.effect("a thread that is not a Crew seat is dispatched untouched, without a r assert.equal(f.receiptReads(), 0); }).pipe(Effect.provide(base)), ); + +/** What the member's thread was asked to keep: the text, not the assignment that followed it. */ +const recordedTexts = (commands: ReadonlyArray) => + commands.flatMap((command) => (command.type === "platform-message.record" ? [command.text] : [])); + +it.effect( + "the introduction and each roster change are kept in the member's thread once, as the model read them", + () => + Effect.gen(function* () { + const f = yield* fixture; + const first = (yield* f.deliver("Review the fix.", { native: "native-1" }))!; + const [introduction] = recordedTexts(yield* Ref.get(f.recorded)); + assert.isTrue(first.startsWith(`${introduction}\n\n`)); + assert.isTrue(introduction!.startsWith("\n")); + assert.include(introduction, "\nShared goal\n"); + assert.notInclude(introduction, "Review the fix."); + + yield* f.deliver("follow-up", { native: "native-1" }); + yield* f.steer("steer"); + assert.lengthOf(recordedTexts(yield* Ref.get(f.recorded)), 1); + + yield* f.crews.addMembers("crew:test", [member("security")]); + const second = (yield* f.deliver("after the roster changed", { native: "native-1" }))!; + const changed = recordedTexts(yield* Ref.get(f.recorded)).at(-1)!; + assert.isTrue(second.startsWith(`${changed}\n\n`)); + assert.include(changed, "\njoined: security:"); + assert.notInclude(changed, "after the roster changed"); + + yield* f.deliver("replaced conversation", { native: "native-2" }); + const all = yield* Ref.get(f.recorded); + assert.lengthOf(recordedTexts(all), 3); + assert.include(recordedTexts(all).at(-1)!, ""); + assert.lengthOf(new Set(all.map((command) => command.commandId)), 3); + const messages = all.flatMap((command) => + command.type === "platform-message.record" ? [command.messageId] : [], + ); + assert.lengthOf(new Set(messages), 3); + }).pipe(Effect.provide(base)), +); + +it.effect("a refused or superseded send keeps nothing in the member's thread", () => + Effect.gen(function* () { + const f = yield* fixture; + yield* f.deliver("refused", { fail: true }).pipe(Effect.result); + assert.isNull(yield* f.deliver("stopped", { sent: false })); + assert.lengthOf(yield* Ref.get(f.recorded), 0); + yield* f.deliver("accepted"); + yield* f.crews.addMembers("crew:test", [member("security")]); + yield* f.steer("refused", { fail: true }).pipe(Effect.exit); + assert.lengthOf(yield* Ref.get(f.recorded), 1); + }).pipe(Effect.provide(base)), +); + +it.effect( + "a record that cannot be kept never fails the turn, and a retried delivery keeps it once", + () => + Effect.gen(function* () { + const f = yield* fixture; + f.recording.fails = true; + assert.isTrue((yield* f.deliver("first"))!.endsWith("first")); + assert.lengthOf(yield* Ref.get(f.recorded), 0); + f.recording.fails = false; + + // The prompt was accepted but its bookkeeping failed, so the next delivery carries the + // same context again and must land on the same record. + yield* f.sql`UPDATE j5_crew_seat_context SET delivered_roster = NULL`; + yield* f.sql`CREATE TRIGGER refuse_seat_context_update BEFORE UPDATE ON j5_crew_seat_context + BEGIN SELECT RAISE(ABORT, 'locked'); END`; + yield* f.deliver("second"); + yield* f.sql`DROP TRIGGER refuse_seat_context_update`; + yield* f.deliver("third"); + assert.lengthOf(yield* Ref.get(f.recorded), 1); + }).pipe(Effect.provide(base)), +); diff --git a/apps/server/src/j5/a2a/CrewTurnContext.ts b/apps/server/src/j5/a2a/CrewTurnContext.ts index 0a64d19385549..afb7191ebdee4 100644 --- a/apps/server/src/j5/a2a/CrewTurnContext.ts +++ b/apps/server/src/j5/a2a/CrewTurnContext.ts @@ -1,4 +1,4 @@ -import { type OrchestrationV2ProviderThread, ThreadId } from "@t3tools/contracts"; +import { type OrchestrationV2ProviderThread, type RunId, ThreadId } from "@t3tools/contracts"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -6,10 +6,11 @@ import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; +import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts"; import * as Crews from "./AgentCrewInstanceService.ts"; import * as ReadChanges from "./ReadChanges.ts"; import { participantIdForThread } from "./HomeRegistrar.ts"; -import { crewContextText } from "./spawnIds.ts"; +import { crewContextRecordIds, crewContextText } from "./spawnIds.ts"; class CrewTurnContextError extends Schema.TaggedError()( "CrewTurnContextError", @@ -27,6 +28,8 @@ const isCrewTurnContextError = Schema.is(CrewTurnContextError); export interface CrewDelivery { readonly threadId: ThreadId; + /** The run the text belongs to; the member's thread keeps what it was told under that run. */ + readonly runId: RunId; /** The provider conversation about to receive the text; a new one needs the introduction again. */ readonly providerThread: Pick; readonly text: string; @@ -86,6 +89,7 @@ const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const crews = yield* Crews.AgentCrewInstanceService; const changes = yield* ReadChanges.ReadChanges; + const orchestrator = yield* Orchestrator.OrchestratorV2; const prepare = Effect.fn("j5.crewTurnContext.prepare")(function* (delivery: CrewDelivery) { const { threadId } = delivery; const conversation = conversationOf(delivery.providerThread); @@ -165,8 +169,20 @@ const make = Effect.gen(function* () { // Only a first delivery, a new roster or a new conversation changes what the Crew reads. const unchanged = context.delivered_roster === rosterJson && context.delivered_conversation === conversation; + const delivered = deliveryContext(prefix); + const recordedText = delivered.trimEnd(); return { - prefix: deliveryContext(prefix), + prefix: delivered, + // What the model read, kept in the member's thread without the assignment after it. + record: + recordedText === "" + ? null + : { + threadId, + runId: delivery.runId, + text: recordedText, + ...crewContextRecordIds({ threadId, conversation, text: recordedText }), + }, delivered: unchanged ? Effect.void : sql` @@ -207,6 +223,16 @@ const make = Effect.gen(function* () { }), ), ); + // Best effort like the bookkeeping above: the member already has the context. + if (context.record !== null) + yield* orchestrator.dispatch({ type: "platform-message.record", ...context.record }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to record the Crew context in the member's thread", { + threadId: delivery.threadId, + cause, + }), + ), + ); return true; }); const steering: CrewTurnContext["Service"]["steering"] = (session) => ({ @@ -214,6 +240,7 @@ const make = Effect.gen(function* () { deliver( { threadId: input.threadId, + runId: input.runId, providerThread: input.providerThread, text: input.message.text, }, diff --git a/apps/server/src/j5/a2a/spawnIds.ts b/apps/server/src/j5/a2a/spawnIds.ts index 152150f27b858..7133f29de0117 100644 --- a/apps/server/src/j5/a2a/spawnIds.ts +++ b/apps/server/src/j5/a2a/spawnIds.ts @@ -44,6 +44,25 @@ export const spawnThreadId = (input: SpawnStableInput) => .digest("hex")}`, ); +/** + * The command and message that keep what a member was told in its own thread. Derived from the + * conversation and the text, so a retried delivery records it once. + */ +export const crewContextRecordIds = (input: { + readonly threadId: ThreadId; + readonly conversation: string; + readonly text: string; +}) => { + const key = NodeCrypto.createHash("sha256") + .update(JSON.stringify([input.threadId, input.conversation, input.text])) + .digest("hex") + .slice(0, 24); + return { + commandId: CommandId.make(`command:j5:crew-context:${key}`), + messageId: MessageId.make(`message:j5:crew-context:${key}`), + }; +}; + export const spawnCrewInstanceId = (input: SpawnStableInput) => lifecycleId({ kind: "crew", operation: "spawn-crew", ...input }); diff --git a/apps/server/src/orchestration-v2/Orchestrator.platform-message.test.ts b/apps/server/src/orchestration-v2/Orchestrator.platform-message.test.ts new file mode 100644 index 0000000000000..7213cea86618d --- /dev/null +++ b/apps/server/src/orchestration-v2/Orchestrator.platform-message.test.ts @@ -0,0 +1,139 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import { historicalMessage } from "@t3tools/provider-core/server/handoffBudget"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; + +const instanceId = ProviderInstanceId.make("codex"); +const modelSelection = { instanceId, model: "gpt-5.1-codex" }; +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("No provider process needed for a recorded message"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "platform-message" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), +); + +it.effect( + "a platform message joins the history without starting or queuing a run, and replays once", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("thread:platform-message"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-platform-message"), + threadId, + projectId: ProjectId.make("project:platform-message"), + title: "Member", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "agent", + creationSource: "mcp", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("assignment"), + threadId, + messageId: MessageId.make("message:assignment"), + text: "Review the fix.", + attachments: [], + dispatchMode: { type: "defer_start" }, + createdBy: "agent", + creationSource: "mcp", + }); + const before = yield* projections.getThreadProjection(threadId); + const shellBefore = yield* projections.getThreadShell(threadId); + + const record = { + type: "platform-message.record" as const, + commandId: CommandId.make("record-introduction"), + threadId, + runId: before.runs[0]!.id, + messageId: MessageId.make("message:introduction"), + text: "\nYou are on a Crew.\n", + }; + const first = yield* orchestrator.dispatch(record); + assert.isUndefined(first.replayed); + const replay = yield* orchestrator.dispatch(record); + assert.isTrue(replay.replayed); + + const after = yield* projections.getThreadProjection(threadId); + // The run the assignment started is the only one: nothing started, nothing queued. + assert.deepStrictEqual( + after.runs.map((run) => [run.id, run.status]), + before.runs.map((run) => [run.id, run.status]), + ); + const messages = after.messages.filter((message) => message.id === record.messageId); + assert.lengthOf(messages, 1); + assert.deepInclude(messages[0]!, { + role: "user", + createdBy: "system", + creationSource: "server", + runId: before.runs[0]!.id, + text: record.text, + }); + const items = after.turnItems + .filter((item) => item.type === "user_message") + .toSorted((left, right) => left.ordinal - right.ordinal); + assert.lengthOf(items, 2); + // It sits in the run it was told with, right after the assignment that began it. + assert.equal(items[1]!.type === "user_message" && items[1]!.messageId, record.messageId); + assert.equal(items[1]!.runId, before.runs[0]!.id); + assert.isAbove(items[1]!.ordinal, items[0]!.ordinal); + // A steer never opens a new response group, so it does not split the assignment from its work. + assert.equal(items[1]!.type === "user_message" && items[1]!.inputIntent, "steer"); + + // A system message is neither the person's activity nor pending work: the shell is as it was. + const shellAfter = yield* projections.getThreadShell(threadId); + assert.equal(shellAfter?.status, shellBefore?.status); + assert.equal(shellAfter?.latestRunId, shellBefore?.latestRunId); + assert.deepStrictEqual( + shellAfter?.latestUserAuthoredMessageAt, + shellBefore?.latestUserAuthoredMessageAt, + ); + + // History rebuilds read it as something the model was told in that run, never as a turn + // it is asked to answer: no run takes it as its input. + const history = yield* projections.getTurnStartHistory(threadId, [before.runs[0]!.id]); + const rebuilt = history.flatMap((item) => { + const message = historicalMessage(item); + return message === null ? [] : [message]; + }); + assert.deepInclude(rebuilt.at(-1)!, { + role: "user", + kind: "user_message", + text: record.text, + }); + assert.isFalse(after.runs.some((run) => run.userMessageId === record.messageId)); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index da674a64ac11c..dbe9c7a909323 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -522,6 +522,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId { case "thread.created.record": return command.parentThreadId; case "secret_request.record": + case "platform-message.record": return command.threadId; case "thread.fork": case "thread.merge_back": @@ -7887,6 +7888,84 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, ); + const dispatchPlatformMessageRecord = Effect.fn("orchestrationV2.dispatch.platformMessageRecord")( + function* ( + command: Extract< + OrchestrationV2InternalCommand, + { readonly type: "platform-message.record" } + >, + events: Ref.Ref>, + ) { + const projection = yield* projectionStore + .getThreadRecords(command.threadId, ["runs"]) + .pipe(mapDispatchError(command)); + const run = projection.runs.find((candidate) => candidate.id === command.runId); + if (run === undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Run ${command.runId} is not in thread ${command.threadId}.`, + }); + } + const now = yield* DateTime.now; + const emitEvent = emit(events, command); + yield* emitEvent({ + type: "message.updated", + threadId: command.threadId, + runId: run.id, + ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { + id: command.messageId, + threadId: command.threadId, + runId: run.id, + nodeId: run.rootNodeId, + role: "user", + text: command.text, + attachments: [], + streaming: false, + createdBy: "system", + creationSource: "server", + createdAt: now, + updatedAt: now, + }, + }); + // A steer never opens a new response group, so the agent's work stays under its assignment. + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + runId: run.id, + ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { + id: idAllocator.derive.userTurnItem({ messageId: command.messageId }), + threadId: command.threadId, + runId: run.id, + nodeId: run.rootNodeId, + providerThreadId: run.providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: yield* nextTurnItemOrdinal({ thread: projection.thread }), + status: "completed", + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "user_message", + messageId: command.messageId, + inputIntent: "steer", + text: command.text, + attachments: [], + createdBy: "system", + creationSource: "server", + }, + }); + }, + ); + const dispatchRuntimeRequestRespond = Effect.fn("Orchestrator.dispatchRuntimeRequestRespond")( function* ( command: Extract, @@ -12117,6 +12196,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "secret_request.record": yield* dispatchSecretRequestRecord(command, events); break; + case "platform-message.record": + yield* dispatchPlatformMessageRecord(command, events); + break; default: return yield* dispatchUnsupported(command); } diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 6b1571722aa36..76a37e7a7af9e 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -34,6 +34,7 @@ import { LedgerProjectId } from "../j5/a2a/contracts.ts"; import { spawnFirstTurnText } from "../j5/a2a/spawnIds.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ProviderSessionManager from "./ProviderSessionManager.ts"; @@ -349,6 +350,10 @@ const crewServices = Layer.mergeAll( crewDatabase, Crews.layer.pipe(Layer.provide(crewDatabase)), ledgerLayer.pipe(Layer.provide(crewDatabase)), + // The seat records what it was told through a dispatch these tests do not inspect. + Layer.mock(Orchestrator.OrchestratorV2)({ + dispatch: () => Effect.succeed({ sequence: 1, storedEvents: [] }), + }), ); it.effect("steering a busy Crew seat carries the roster change made while it worked", () => @@ -432,7 +437,7 @@ it.effect("steering a busy Crew seat carries the roster change made while it wor // The builder's assignment started the turn that is still running. yield* Effect.gen(function* () { yield* (yield* CrewTurnContext.CrewTurnContext).deliver( - { threadId, providerThread, text: "Build the fix." }, + { threadId, runId: RunId.make("run:crew-builder"), providerThread, text: "Build the fix." }, () => Effect.succeed(true), ); }).pipe(Effect.provide(CrewTurnContext.layer)); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 7753918f1aefe..1a6e14591b721 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -56,6 +56,7 @@ import * as ContextHandoffService from "./ContextHandoffService.ts"; import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ProviderSessionManager from "./ProviderSessionManager.ts"; @@ -1961,6 +1962,10 @@ const crewServices = Layer.mergeAll( crewDatabase, Crews.layer.pipe(Layer.provide(crewDatabase)), ledgerLayer.pipe(Layer.provide(crewDatabase)), + // The seat records what it was told through a dispatch these tests do not inspect. + Layer.mock(Orchestrator.OrchestratorV2)({ + dispatch: () => Effect.succeed({ sequence: 1, storedEvents: [] }), + }), ); const recordSeat = (seatThreadId: ThreadId, options: { readonly seat?: boolean } = {}) => diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 07c29178335c1..b134cc01a39e4 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1433,6 +1433,7 @@ export const layer: Layer.Layer< ? crewTurnContext.value.deliver( { threadId: projection.thread.id, + runId: run.id, providerThread: runningProviderThread, text: userText, }, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index dfa227770b83a..6d525677d8e46 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -176,8 +176,43 @@ const layerRunExecutionServiceProvided = RunExecutionService.layer.pipe( ), ); +const layerCrewOrchestratorBase = Orchestrator.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerCheckpointServiceProvided, + CommandPolicy.layer, + layerStores, + layerEventSinkProvided, + layerCommandReceiptStoreProvided, + layerContextHandoffServiceProvided, + IdAllocator.layer, + ProjectStore.layer, + layerProviderAdapterRegistryProvided, + // Reuse the continuation worker's layer reference so memoization shares one request queue. + ProviderContinuationRequests.layer, + layerProviderEventIngestorProvided, + layerRuntimePolicyProvided, + layerProviderSessionManagerProvided, + layerProviderSwitchServiceProvided, + layerRunExecutionServiceProvided, + ThreadForkService.layer, + ), + ), +); + +const layerOrchestratorProvided = CrewDeliveryContext.layer.pipe( + Layer.provide(layerCrewOrchestratorBase), + Layer.provide(layerCommandReceiptStoreProvided), +); + +// The member's thread records what it was told through the Orchestrator, which sits below the +// provider turn services. +const layerCrewTurnContextProvided = CrewTurnContext.layer.pipe( + Layer.provide(layerOrchestratorProvided), +); + const layerProviderTurnStartServiceProvided = ProviderTurnStartService.layer.pipe( - Layer.provide(CrewTurnContext.layer), + Layer.provide(layerCrewTurnContextProvided), Layer.provide( Layer.mergeAll( layerContextHandoffServiceProvided, @@ -194,7 +229,7 @@ const layerProviderTurnStartServiceProvided = ProviderTurnStartService.layer.pip ); const layerProviderTurnControlServiceProvided = ProviderTurnControlService.layer.pipe( - Layer.provide(CrewTurnContext.layer), + Layer.provide(layerCrewTurnContextProvided), Layer.provide(Layer.merge(ProjectionStore.layer, layerProviderSessionManagerProvided)), ); const layerRuntimeRequestServiceProvided = RuntimeRequestService.layer.pipe( @@ -234,35 +269,6 @@ const layerRunFinalizationServiceProvided = RunFinalizationService.layer.pipe( ), ); -const layerCrewOrchestratorBase = Orchestrator.layer.pipe( - Layer.provide( - Layer.mergeAll( - layerCheckpointServiceProvided, - CommandPolicy.layer, - layerStores, - layerEventSinkProvided, - layerCommandReceiptStoreProvided, - layerContextHandoffServiceProvided, - IdAllocator.layer, - ProjectStore.layer, - layerProviderAdapterRegistryProvided, - // Reuse the continuation worker's layer reference so memoization shares one request queue. - ProviderContinuationRequests.layer, - layerProviderEventIngestorProvided, - layerRuntimePolicyProvided, - layerProviderSessionManagerProvided, - layerProviderSwitchServiceProvided, - layerRunExecutionServiceProvided, - ThreadForkService.layer, - ), - ), -); - -const layerOrchestratorProvided = CrewDeliveryContext.layer.pipe( - Layer.provide(layerCrewOrchestratorBase), - Layer.provide(layerCommandReceiptStoreProvided), -); - const layerAgentSessionImporterProvided = AgentSessionImporter.layer.pipe( Layer.provide( Layer.mergeAll( diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 324bb0736350b..46268927342aa 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -3301,6 +3301,19 @@ const OrchestrationV2InternalCommand = Schema.Union([ }), ), }), + /** + * Adds a message the platform wrote to the history of `runId`, which is already under way. It + * starts and queues no run, so it tells a reader something without asking the agent for a + * turn. Internal so no client can speak as the platform. + */ + Schema.Struct({ + type: Schema.Literal("platform-message.record"), + commandId: CommandId, + threadId: ThreadId, + runId: RunId, + messageId: MessageId, + text: Schema.String, + }), /** * Internal so no client can mark a request saved without the value being * stored. From b0ea47ef20500df8b27ddcc4b6412dfeaebcfaae Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Mon, 2 Nov 2026 11:52:59 -0500 Subject: [PATCH 11/12] feat(j5): show what a Crew member was told as a card in its thread The introduction and each roster change appear as a collapsed card that opens to the text the model read, on web and mobile. Records the new internal command in FORK.md (case 106) and the register (D43). Co-Authored-By: Claude Sonnet 5.5 --- FORK.md | 5 +- apps/mobile/src/j5/a2a/timeline.tsx | 28 ++++++++- .../src/j5/a2a/timelinePresentation.test.ts | 15 +++++ .../mobile/src/j5/a2a/timelinePresentation.ts | 9 ++- .../j5/crew/CrewContextCard.browser.test.tsx | 61 +++++++++++++++++++ apps/web/src/j5/crew/CrewNoticeRenderer.tsx | 46 +++++++++++++- docs/j5/product/features/crews.md | 3 +- docs/j5/product/upstream.md | 13 ++++ .../client-runtime/src/j5/crewNotices.test.ts | 44 +++++++++++++ packages/client-runtime/src/j5/crewNotices.ts | 28 +++++++++ .../src/j5/userMessagePresentation.test.ts | 8 +++ .../src/j5/userMessagePresentation.ts | 11 +++- 12 files changed, 263 insertions(+), 8 deletions(-) create mode 100644 apps/web/src/j5/crew/CrewContextCard.browser.test.tsx create mode 100644 packages/client-runtime/src/j5/crewNotices.test.ts diff --git a/FORK.md b/FORK.md index fa5f4a83096d4..3949e16d47f5e 100644 --- a/FORK.md +++ b/FORK.md @@ -527,7 +527,7 @@ migrations after upstream migrations. 105. Agent Setup and Crew approval settings ([#743](https://github.com/Jacksondr5/j5code/issues/743)): `packages/contracts/src/settings.ts` registers J5's `crewAutoApprove` boolean (default off) in server settings, patches, and project overrides. `apps/web/src/components/settings/settingsSearch.ts` renames the existing `/settings/personas` destination to Agent Setup and adds search terms and the scoped Crew setting target. `apps/mobile/src/features/settings/SettingsRouteScreen.tsx` and `apps/mobile/src/Stack.tsx` rename the existing Personas navigation entry and title to Agent Setup. Runtime behavior and the web sections stay in J5-owned files; mobile still exposes only the persona library. -106. Deferred Crew assignments ([#745](https://github.com/Jacksondr5/j5code/issues/745)): `orchestration-v2/runtimeLayer.ts` wraps the shared orchestrator with J5-owned `CrewDeliveryContext.ts` for first-assignment workspace preparation and guards, and supplies J5-owned `CrewTurnContext.ts` to provider turn start and provider turn control. `orchestration-v2/ProviderTurnStartService.ts` asks that service whether the thread is a Crew seat (one indexed read) and delegates only a seat's selected assignment text to it immediately around provider delivery; every other thread keeps upstream's fast path and delivery unchanged, and `CrewDeliveryContext.ts` likewise passes any non-seat thread's dispatch straight through. `orchestration-v2/ProviderTurnControlService.ts` wraps the live session with the service's `steering`, one hook beside upstream's `steerTurn` call, so a message steered into a busy seat carries the current context too. The service builds the approved introduction or net roster changes from the current roster, sends the full introduction again when the provider conversation it reached is replaced (a model or provider switch, or a missing native session rebuilt from history), and records what it sent only after the provider accepts the prompt; a send that never happens (the run was stopped or superseded before `startTurn`) leaves it owed. Editable messages and shared author prefixes stay unchanged, so queued edits, cancellations and reordering cannot consume context. Waiting seats whose Crew is retired fail visibly; a retained worktree guard applies even after retirement. J5 migration 49 owns the context, and `CrewSeatPreparation.ts` uses upstream's persisted preparation path. `orchestration-v2/ProviderTurnStartService.test.ts` and `ProviderTurnControlService.test.ts` exercise the hooks against the real seat context, including a retained and a replaced native conversation and a Stop before the provider send. On an advance, retain the hooks at actual delivery and steering after queue selection, shared by every provider and transport. +106. Deferred Crew assignments ([#745](https://github.com/Jacksondr5/j5code/issues/745)): `orchestration-v2/runtimeLayer.ts` wraps the shared orchestrator with J5-owned `CrewDeliveryContext.ts` for first-assignment workspace preparation and guards, and supplies J5-owned `CrewTurnContext.ts` to provider turn start and provider turn control. `orchestration-v2/ProviderTurnStartService.ts` asks that service whether the thread is a Crew seat (one indexed read) and delegates only a seat's selected assignment text to it immediately around provider delivery; every other thread keeps upstream's fast path and delivery unchanged, and `CrewDeliveryContext.ts` likewise passes any non-seat thread's dispatch straight through. `orchestration-v2/ProviderTurnControlService.ts` wraps the live session with the service's `steering`, one hook beside upstream's `steerTurn` call, so a message steered into a busy seat carries the current context too. The service builds the approved introduction or net roster changes from the current roster, sends the full introduction again when the provider conversation it reached is replaced (a model or provider switch, or a missing native session rebuilt from history), and records what it sent only after the provider accepts the prompt; a send that never happens (the run was stopped or superseded before `startTurn`) leaves it owed. Editable messages and shared author prefixes stay unchanged, so queued edits, cancellations and reordering cannot consume context. Waiting seats whose Crew is retired fail visibly; a retained worktree guard applies even after retirement. J5 migration 49 owns the context, and `CrewSeatPreparation.ts` uses upstream's persisted preparation path. `orchestration-v2/ProviderTurnStartService.test.ts` and `ProviderTurnControlService.test.ts` exercise the hooks against the real seat context, including a retained and a replaced native conversation and a Stop before the provider send. A seat's thread also keeps what it was told (register D43): after the provider accepts a prompt that carried the introduction or a roster change, `CrewTurnContext.ts` dispatches the server-only `platform-message.record` command with that text, ids derived from the conversation and the text so a retry records once, and a failure to post is logged without failing the turn. `packages/contracts/src/orchestrationV2.ts` appends the command to the internal command union; `orchestration-v2/Orchestrator.ts` adds one `commandThreadId` case, one `dispatch` case and `dispatchPlatformMessageRecord`, which emits the existing `message.updated` and `turn-item.updated` events for the named run with no run created or queued; `ProviderTurnStartService.ts` adds `runId: run.id` to the delivery it already hands the seat service; and `runtimeLayer.ts` builds the orchestrator layers above the two turn services so `CrewTurnContext.layer` can depend on the orchestrator. The client side is J5-owned: `presentCrewContext` in `packages/client-runtime/src/j5/crewNotices.ts`, `CrewNoticeRenderer.tsx` on web and `timeline.tsx` on mobile. `Orchestrator.platform-message.test.ts` proves the command, and `CrewDeliveryContext.test.ts` and its integration test prove the posting. On an advance, retain the hooks at actual delivery and steering after queue selection, shared by every provider and transport, and the internal command with its one decision function. ## Pin and upstream advance runbook @@ -840,6 +840,7 @@ explicitly marked. | `apps/server/src/orchestration-v2/ProviderTurnControlService.ts` | R | 26, 106 | | `apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts` | A | N, 106 | | `apps/server/src/orchestration-v2/ProviderTurnStartService.ts` | A | 30, N, 106 | +| `packages/contracts/src/orchestrationV2.ts` | N | 106 | | `apps/server/src/orchestration-v2/RunFinalizationService.ts` | R | 30 | | `apps/server/src/orchestration-v2/ThreadLaunchService.ts` | R | Saved-agent launch | | `apps/server/src/orchestration-v2/runtimeLayer.test.ts` | R | 3 | @@ -997,7 +998,7 @@ explicitly marked. | `packages/provider-cursor/src/server/adapter.ts` | N | B | | `packages/provider-opencode/src/server/v2/adapter.ts` | N | B | | `packages/provider-opencode/src/server/adapter.ts` | N | N | -| `apps/server/src/orchestration-v2/Orchestrator.ts` | N | Role library, Saved-agent mentions | +| `apps/server/src/orchestration-v2/Orchestrator.ts` | N | Role library, Saved-agent mentions, 106 | | `apps/server/src/orchestration-v2/ProjectionStore.ts` | N | Role library | | `apps/server/src/orchestration-v2/RuntimePolicy.ts` | N | 47, Role library | | `apps/server/src/orchestration-v2/ThreadManagementService.ts` | N | 26 | diff --git a/apps/mobile/src/j5/a2a/timeline.tsx b/apps/mobile/src/j5/a2a/timeline.tsx index d15df9ff83945..fbba2dbc1f9aa 100644 --- a/apps/mobile/src/j5/a2a/timeline.tsx +++ b/apps/mobile/src/j5/a2a/timeline.tsx @@ -7,7 +7,7 @@ import type { J5UserMessagePresentation, } from "@t3tools/client-runtime/j5/user-message"; import { isSharedNote } from "@t3tools/client-runtime/j5/shared-conversation"; -import type { ReactNode } from "react"; +import { useState, type ReactNode } from "react"; import { Pressable, View } from "react-native"; import { AppText as Text } from "../../components/ui/AppText"; @@ -44,6 +44,9 @@ export function renderJ5TimelineNotice(input: { ); } + if (notice.kind === "context") { + return ; + } return ( {notice.label} @@ -54,6 +57,29 @@ export function renderJ5TimelineNotice(input: { ); } +/** What the platform told a Crew member: its title, and the model's own reading once opened. */ +function CrewContextNotice(props: { readonly title: string; readonly text: string }) { + const [open, setOpen] = useState(false); + return ( + + setOpen((value) => !value)} + > + + {open ? "▾" : "▸"} {props.title} from J5 + + + {open ? ( + + {props.text} + + ) : null} + + ); +} + function Tag(props: { readonly label: string; readonly tone?: "warning" | "success" }) { return ( { ).toEqual({ kind: "raw", label: "Crew notice" }); }); + it("shows what a Crew member was told as a card of its own, not as the reader's message", () => { + expect( + presentJ5TimelineNotice({ + id: "message:j5:crew-context:abc", + role: "user", + createdBy: "system", + text: "\n\njoined: security\n\n", + }), + ).toEqual({ + kind: "context", + title: "Roster changed", + text: "\njoined: security\n", + }); + }); + it("leaves letters and upstream's own messages to their rows", () => { expect(presentJ5TimelineNotice(delivery("agent", askRaw))).toBeNull(); expect( diff --git a/apps/mobile/src/j5/a2a/timelinePresentation.ts b/apps/mobile/src/j5/a2a/timelinePresentation.ts index c11688006573b..451652705d3ca 100644 --- a/apps/mobile/src/j5/a2a/timelinePresentation.ts +++ b/apps/mobile/src/j5/a2a/timelinePresentation.ts @@ -1,3 +1,4 @@ +import { presentCrewContext } from "@t3tools/client-runtime/j5/crew-notices"; import type { ParticipantIdentities } from "@t3tools/client-runtime/j5/participant-identity"; import { isJ5DeliveryMessage, @@ -45,16 +46,20 @@ export type J5FeedMessagePresentation = ReturnType; /** * J5's platform notices that upstream's row would draw as the reader's own message: a silence, - * which has a plain summary, and a Crew notice or a delivery notice this client cannot read yet, - * which keep their raw text until the notices are redrawn. Null for every other message. + * which has a plain summary, what a Crew member was told (a card that opens to the text), and a + * Crew notice or a delivery notice this client cannot read yet, which keep their raw text until + * the notices are redrawn. Null for every other message. */ export function presentJ5TimelineNotice( message: J5UserMessageInput, ): | { readonly kind: "silence"; readonly summary: string | null } | { readonly kind: "raw"; readonly label: string } + | { readonly kind: "context"; readonly title: string; readonly text: string } | null { if (message.role !== "user" || message.createdBy !== "system") return null; + const context = presentCrewContext(message); + if (context !== null) return { kind: "context", title: context.title, text: context.text }; const presentation = presentJ5UserMessage(message); if (presentation?.group !== "notice") { return isJ5DeliveryMessage(message) ? { kind: "raw", label: "Raw A2A delivery" } : null; diff --git a/apps/web/src/j5/crew/CrewContextCard.browser.test.tsx b/apps/web/src/j5/crew/CrewContextCard.browser.test.tsx new file mode 100644 index 0000000000000..ab75e5255bf42 --- /dev/null +++ b/apps/web/src/j5/crew/CrewContextCard.browser.test.tsx @@ -0,0 +1,61 @@ +import { MessageId } from "@t3tools/contracts"; +import { expect, it } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import type { ChatMessage } from "~/types"; + +import { render } from "../../../test/render"; +import { renderThreadA2ADelivery } from "../a2a/ThreadA2ARenderer"; + +const CREATED_AT = "2026-10-31T12:00:00.000Z"; +const message = (text: string): ChatMessage => ({ + id: MessageId.make("message:j5:crew-context:abc"), + role: "user", + text, + runId: null, + streaming: false, + createdBy: "system", + creationSource: "server", + createdAt: CREATED_AT, + updatedAt: CREATED_AT, +}); +const context = (text: string) => + `\n${text}\n`; + +it("shows the introduction folded to its title and opens to the text the model read", async () => { + await using screen = await render( + <> + {renderThreadA2ADelivery({ + message: message(context("\nYou are the reviewer.\n")), + timestampLabel: "Today, 8:00 AM", + })} + , + { router: false }, + ); + const card = screen.container.querySelector( + "details[data-j5-crew-context='introduction']", + )!; + await expect.element(screen.getByText("Introduction")).toBeVisible(); + expect(card.open).toBe(false); + + await userEvent.click(screen.getByText("Introduction")); + expect(card.open).toBe(true); + await expect.element(screen.getByText(/You are the reviewer\./)).toBeVisible(); +}); + +it("titles a roster change as its own card", async () => { + await using screen = await render( + <> + {renderThreadA2ADelivery({ + message: message( + context( + "\njoined: security: participant_id=p1 responsibility=audit\n", + ), + ), + })} + , + { router: false }, + ); + await expect.element(screen.getByText("Roster changed")).toBeVisible(); + expect(screen.container.querySelector("[data-j5-crew-context='roster-changed']")).not.toBeNull(); +}); diff --git a/apps/web/src/j5/crew/CrewNoticeRenderer.tsx b/apps/web/src/j5/crew/CrewNoticeRenderer.tsx index 37cf0c2c47cce..7ce23599227f1 100644 --- a/apps/web/src/j5/crew/CrewNoticeRenderer.tsx +++ b/apps/web/src/j5/crew/CrewNoticeRenderer.tsx @@ -1,13 +1,15 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; import { useNavigate } from "@tanstack/react-router"; -import { UsersIcon } from "lucide-react"; +import { ChevronRightIcon, UsersIcon } from "lucide-react"; import type { ReactNode } from "react"; import { cn } from "../../lib/utils"; import { buildThreadRouteParams } from "../../threadRoutes"; import { + presentCrewContext, presentCrewNotice, + type CrewContextNotice, type CrewNoticeMessage, type CrewNoticePresentation, } from "@t3tools/client-runtime/j5/crew-notices"; @@ -30,6 +32,46 @@ export interface CrewNoticeRenderInput { readonly markdownCwd?: string | undefined; } +/** + * What the platform told this member with an assignment, folded to its title: the text is the + * model's own reading, long and not written for the person, so it opens on request. + */ +function CrewContextCard(props: { + readonly notice: CrewContextNotice; + readonly input: CrewNoticeRenderInput; +}) { + const { notice, input } = props; + return ( +
+ + + + {notice.title} + from J5 + {input.timestampLabel ? ( + + ) : null} + +
+        {notice.text}
+      
+
+ ); +} + /** A declined request as the Captain received it: what was asked for, and who declined it. */ function CrewDeclinedCard(props: { readonly notice: Extract; @@ -147,6 +189,8 @@ function CrewNoticeLines(props: { * Approval summaries remain visible; completed finishes without a warning take no timeline row. */ export function renderCrewNotice(input: CrewNoticeRenderInput): ReactNode { + const context = presentCrewContext(input.message); + if (context !== null) return ; const notice = presentCrewNotice(input.message); if (notice === null) return null; if (notice.kind === "gate" && notice.decision === "declined") diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index 2f547d75b63ea..2e70672572565 100644 --- a/docs/j5/product/features/crews.md +++ b/docs/j5/product/features/crews.md @@ -69,7 +69,7 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif ### Handoff artifacts -12. A seat whose definition declares an output artifact writes it as its handoff artifact in the project's artifacts; its first turn names the exact path. The first assignment carries its playbook context and handoff obligation; a later assignment reuses the same thread and workspace without repeating its introduction, unless the provider conversation was replaced (a model or provider switch, or a native session the provider lost), in which case the introduction is sent again with the current roster. Members that finished remain available on the roster. Started members receive net roster changes, naming who joined or left and their responsibility, at the top of their next delivery, including a message steered into a turn in progress. Waiting members receive the current roster with their first assignment. Context is attached at provider delivery, after queued edits, cancellations, and reordering; a start that never reaches the provider, because it was refused, stopped, or superseded, leaves it owed. A waiting member whose Crew retired must have its Crew restored before starting, and a worktree seat cannot fall back to the project root. Roster changes alone start no turns, and availability produces no polling or acknowledgment turns. +12. A seat whose definition declares an output artifact writes it as its handoff artifact in the project's artifacts; its first turn names the exact path. The first assignment carries its playbook context and handoff obligation; a later assignment reuses the same thread and workspace without repeating its introduction, unless the provider conversation was replaced (a model or provider switch, or a native session the provider lost), in which case the introduction is sent again with the current roster. Members that finished remain available on the roster. Started members receive net roster changes, naming who joined or left and their responsibility, at the top of their next delivery, including a message steered into a turn in progress. Waiting members receive the current roster with their first assignment. Context is attached at provider delivery, after queued edits, cancellations, and reordering; a start that never reaches the provider, because it was refused, stopped, or superseded, leaves it owed. A waiting member whose Crew retired must have its Crew restored before starting, and a worktree seat cannot fall back to the project root. What a member was told is kept in its own thread: once the provider has taken a prompt that carried the introduction or a roster change, the thread gains a collapsed card, **Introduction** or **Roster changed**, that opens to the text the model read, without the assignment. The card sits with the run it was told in, starts no run and queues none, and is posted once however often a delivery is retried; a refused or superseded send posts nothing. Roster changes alone start no turns, and availability produces no polling or acknowledgment turns. 13. When a seat finishes, the Captain receives a notice that leads with how the run ended and, for a failed run, carries the run's recorded error, then whether the seat's handoff artifact was written, missing, unavailable with the reason it can never be read, or never declared, a written handoff artifact riding inline when short and by path otherwise; a finish whose notice would repeat the seat's last one is silent, and a notice arriving while the Captain's turn runs folds into the seat notice already queued behind it rather than queuing another turn. 14. A seat that finishes without its handoff artifact is reminded once and is reported to its Captain on its next finished run whatever happened. @@ -141,3 +141,4 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif - 2026-10-22 — active peer steering covers Claude (Bryant). - 2026-10-17 — several people (Jackson; [record](../../worklog/2026-10-16-people-and-access-session.md)): "the person" is anyone who can write to the Captain's thread, and a Crew's later requests reach all of them, which ends the stall where a guest who asked for a Crew never saw its seats' approvals (AC23; [#534](https://github.com/Jacksondr5/j5code/issues/534)). - 2026-10-27 — the Captain's timeline shows the person only what they would act on: launch and finish notices become one line per seat that needs them, and each seat's row says how its last run ended (Bryant; [#741](https://github.com/Jacksondr5/j5code/issues/741)). +- 2026-10-31 — a member's introduction and roster changes are visible in its own thread, as a collapsed card that opens to what the model read, where they had been sent to the model only (Jackson, 2026-10-31; register D43). diff --git a/docs/j5/product/upstream.md b/docs/j5/product/upstream.md index aa62611453005..5585c1801c23c 100644 --- a/docs/j5/product/upstream.md +++ b/docs/j5/product/upstream.md @@ -118,6 +118,18 @@ Letter codes in the Decided lines (SC2, QS1, AR3, and so on) are rulings recorde **Decided:** Jackson, 2026-10-13. Recorded in FORK.md case 74. +#### D43. A thread can keep a message the platform wrote without a run + +**Upstream:** a message in a thread's history is a turn: dispatching one always starts a run, queues one behind the running turn, or steers the running one. There is no way to add something to the history that the agent is not asked to answer. + +**J5:** an internal command records a platform-authored message in a thread, as a user-role message from the platform, without starting, queuing or counting a run. J5 uses it for one thing: after the provider takes a prompt that carried a Crew member's introduction or a roster change, the member's thread records exactly what the model read, without the assignment, as a collapsed card. It sits with the run it was told in and is recorded once however often the delivery is retried. + +**Why:** since the Crew member's introduction began riding with its first assignment for the model only, the person reading the member's thread could not see what the member had been told (Jackson, review of the first-assignment change). Posting it with `message.dispatch` would have started a run on a member that should only be told something. + +**Consequences:** one new internal command, decided into upstream's existing message and turn-item events, with no new projection (FORK.md case 106); the edits are one `case` and one decision function in `Orchestrator.ts`, one internal command in the contracts, one `runId` in the delivery `ProviderTurnStartService.ts` already builds, and the turn services' layers built below the orchestrator in `runtimeLayer.ts`. The record sits in the thread's history with a steer's intent, so a context handoff or a history rebuilt after a lost session reads it as something the model was told, never as a turn to answer. At each advance, check that a new message or turn-item kind and the history rebuilds still take a run-less user message. + +**Decided:** Jackson, 2026-10-31, as the product decision that a member's introduction is visible in its thread; Bryant approved this implementation and the upstream edits. Recorded in FORK.md case 106. + ### New threads #### D12. Multi-model send is refused from a persona draft @@ -630,3 +642,4 @@ J5 kept a run from resuming after a usage-limit reset when the person had presse - 2026-10-31 — D33: "Merge back" is disabled for someone who can't start a thread in the fork's project, which the server already refused (Jackson's 2026-10-31 approval; [#730](https://github.com/Jacksondr5/j5code/issues/730)). - 2026-11-01 — D33: the mobile client reads shared conversations as web does, with each message's author and avatar, who answered each prompt, and another person's message held until its author is known; sharing itself stays on web and desktop (the mobile catch-up; [#832](https://github.com/Jacksondr5/j5code/issues/832), [#871](https://github.com/Jacksondr5/j5code/issues/871), [#869](https://github.com/Jacksondr5/j5code/issues/869)). - 2026-11-01 — D41 added: on mobile, a draft's persona has its own row under the checkout row, and the slash menu covers the draft rows (Jackson, Checkpoint 1; [#866](https://github.com/Jacksondr5/j5code/issues/866)). +- 2026-10-31 — D43 added: a thread can keep a message the platform wrote without a run, so a Crew member's introduction and roster changes show in its own thread (Jackson, 2026-10-31). diff --git a/packages/client-runtime/src/j5/crewNotices.test.ts b/packages/client-runtime/src/j5/crewNotices.test.ts new file mode 100644 index 0000000000000..270a519e90d15 --- /dev/null +++ b/packages/client-runtime/src/j5/crewNotices.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { presentCrewContext } from "./crewNotices.ts"; + +const context = (text: string) => + `\n${text}\n`; +const system = (text: string) => ({ role: "user", createdBy: "system", text }); + +describe("presentCrewContext", () => { + it("reads the introduction a member was given, without the wrapper", () => { + const introduction = "\nYou are reviewer.\n"; + expect(presentCrewContext(system(context(introduction)))).toEqual({ + kind: "introduction", + title: "Introduction", + text: introduction, + }); + }); + + it("reads a roster change as its own card", () => { + const change = + "\njoined: security: participant_id=p1 responsibility=audit\n"; + expect(presentCrewContext(system(context(change)))).toEqual({ + kind: "roster-changed", + title: "Roster changed", + text: change, + }); + }); + + it("gives back the closing tag the server escaped inside the text", () => { + const escaped = context("quoted <\\/j5_crew_delivery_context> inside"); + expect(presentCrewContext(system(escaped))?.text).toBe( + "quoted
inside", + ); + }); + + it("leaves everything else to the ordinary row", () => { + const text = context("You are reviewer."); + expect(presentCrewContext({ role: "user", createdBy: "user", text })).toBeNull(); + expect(presentCrewContext({ role: "assistant", createdBy: "system", text })).toBeNull(); + expect(presentCrewContext(system(`Please read:\n${text}`))).toBeNull(); + expect(presentCrewContext(system(`${text}\n\nReview the fix.`))).toBeNull(); + expect(presentCrewContext(system(context(" ")))).toBeNull(); + }); +}); diff --git a/packages/client-runtime/src/j5/crewNotices.ts b/packages/client-runtime/src/j5/crewNotices.ts index e05d6a2b0afdd..414ec46e0009f 100644 --- a/packages/client-runtime/src/j5/crewNotices.ts +++ b/packages/client-runtime/src/j5/crewNotices.ts @@ -241,6 +241,34 @@ const parseSeats = (text: string): CrewNoticePresentation | null => { : { kind: "seats", seats: seats as ReadonlyArray }; }; +/** + * What the platform told a Crew member with an assignment, kept in the member's own thread: the + * text the model read, in the tag the server wrote it in. Strictly recognized from that tag. + */ +export interface CrewContextNotice { + readonly kind: "introduction" | "roster-changed"; + readonly title: string; + /** The context without its wrapper, as the model read it. */ + readonly text: string; +} + +const CONTEXT_OPEN = "\n"; +const CONTEXT_CLOSE = "\n"; +const ROSTER_CHANGED_OPEN = ""; + +export const presentCrewContext = (message: CrewNoticeMessage): CrewContextNotice | null => { + if (message.role !== "user" || message.createdBy !== "system") return null; + const { text } = message; + if (!text.startsWith(CONTEXT_OPEN) || !text.endsWith(CONTEXT_CLOSE)) return null; + const body = text + .slice(CONTEXT_OPEN.length, text.length - CONTEXT_CLOSE.length) + .replaceAll("<\\/j5_crew_delivery_context>", ""); + if (body.trim() === "") return null; + return body.startsWith(ROSTER_CHANGED_OPEN) + ? { kind: "roster-changed", title: "Roster changed", text: body } + : { kind: "introduction", title: "Introduction", text: body }; +}; + /** Null for anything that is not a Crew notice; the ordinary renderer then owns the message. */ export const presentCrewNotice = (message: CrewNoticeMessage): CrewNoticePresentation | null => { if (message.role !== "user") return null; diff --git a/packages/client-runtime/src/j5/userMessagePresentation.test.ts b/packages/client-runtime/src/j5/userMessagePresentation.test.ts index b96c556f86116..a34a92c608020 100644 --- a/packages/client-runtime/src/j5/userMessagePresentation.test.ts +++ b/packages/client-runtime/src/j5/userMessagePresentation.test.ts @@ -520,6 +520,14 @@ describe("groups 4 and 5: classified, drawn elsewhere", () => { expect( presentJ5UserMessage({ id: "message:crew", role: "user", text: gate, createdBy: "system" }), ).toMatchObject({ group: "notice", kind: "crew-gate" }); + expect( + presentJ5UserMessage({ + id: "message:j5:crew-context:abc", + role: "user", + text: "\nYou are on a Crew.\n", + createdBy: "system", + }), + ).toMatchObject({ group: "notice", kind: "crew-context", summary: "Introduction" }); expect( presentJ5UserMessage({ id: "message:restart-continuation:run-1", diff --git a/packages/client-runtime/src/j5/userMessagePresentation.ts b/packages/client-runtime/src/j5/userMessagePresentation.ts index ec421f3ef0191..6db302acb31d7 100644 --- a/packages/client-runtime/src/j5/userMessagePresentation.ts +++ b/packages/client-runtime/src/j5/userMessagePresentation.ts @@ -6,7 +6,11 @@ import type { } from "@t3tools/contracts"; import { resolveUserMessagePresentation } from "../userMessage.ts"; -import { participantIdsForCrewNotice, presentCrewNotice } from "./crewNotices.ts"; +import { + participantIdsForCrewNotice, + presentCrewContext, + presentCrewNotice, +} from "./crewNotices.ts"; /** * How J5 shows a user-role message in a thread's timeline, grouped by who is speaking @@ -32,6 +36,7 @@ export type J5NoticeKind = | "silence" | "crew-gate" | "crew-seats" + | "crew-context" | "restart-continuation" | "pr-watch" | "platform"; @@ -503,6 +508,10 @@ export function presentJ5UserMessage( if (prompt !== undefined) return { group: "prompt", side: "left", kind: prompt[1], text }; if (message.createdBy === "system") { + const context = presentCrewContext({ role: message.role, text, createdBy: message.createdBy }); + if (context !== null) { + return { group: "notice", side: "left", kind: "crew-context", summary: context.title, text }; + } const crew = presentCrewNotice({ role: message.role, text, createdBy: message.createdBy }); return { group: "notice", From 5a98a5e3cf05a0f33554347aad9d61e9479145a8 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Mon, 2 Nov 2026 17:29:41 -0500 Subject: [PATCH 12/12] fix(web): SpawnedChildGroupRows is no longer exported now that no test imports it (#745) Co-Authored-By: Claude Sonnet 5.5 --- apps/web/src/j5/threads/SpawnedChildren.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/j5/threads/SpawnedChildren.tsx b/apps/web/src/j5/threads/SpawnedChildren.tsx index c3a171b3c1bbb..11038d10da34f 100644 --- a/apps/web/src/j5/threads/SpawnedChildren.tsx +++ b/apps/web/src/j5/threads/SpawnedChildren.tsx @@ -148,7 +148,7 @@ function SpawnedChildrenRows( const childRowClassName = "flex w-full min-w-0 flex-col gap-0.5 rounded-md px-1.5 py-1 text-left outline-hidden hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"; -export function SpawnedChildGroupRows( +function SpawnedChildGroupRows( props: SpawnedChildActions & { readonly environmentId: EnvironmentId; readonly group: SpawnedChildGroup;