diff --git a/FORK.md b/FORK.md index 61c532b627f3a..3949e16d47f5e 100644 --- a/FORK.md +++ b/FORK.md @@ -76,7 +76,7 @@ These files exist upstream, but J5 owns its copy outright and they are not integ ### Sanctioned appended integration cases -Against upstream pin `d2c440312e5f39d59827ed466838a623516454d6`, the inventory has 106 entries: 1–105 plus 15b. Seventeen are retired and keep their numbers (10–14, 15b, 16–18, 20, 27–29, 54, 55, 61, 66), and 19 and 39 are retired except for a remainder. Existing numbers never change; a new case takes the next number. Line coordinates and landing SHAs below describe historical integrations; use named symbols and tests after upstream movement. Branding has its own inventory in `BRANDING.md`; temporary defect patches are listed separately below. +Against upstream pin `d2c440312e5f39d59827ed466838a623516454d6`, the inventory has 107 entries: 1–106 plus 15b. Seventeen are retired and keep their numbers (10–14, 15b, 16–18, 20, 27–29, 54, 55, 61, 66), and 19 and 39 are retired except for a remainder. Existing numbers never change; a new case takes the next number. Line coordinates and landing SHAs below describe historical integrations; use named symbols and tests after upstream movement. Branding has its own inventory in `BRANDING.md`; temporary defect patches are listed separately below. 1. A1's independent communication-ledger migration lane: in `apps/server/src/persistence/Sqlite.ts`, `layerSetup` runs `runJ5CompatibleUpstreamMigrations` and then `runJ5A2AMigrations` where upstream calls `runMigrations()`. Upstream's `layerConfig` has already run `initializeV2Database`, which copies `state.sqlite` to `statev2.sqlite`, so both run only against `statev2.sqlite`. J5 adopts that copy-on-first-start unchanged (Jackson's 2026-09-24 decision #2): an existing `statev2.sqlite` wins and `state.sqlite` is never recopied or written again, so the cutover is one-way: writes after the first V2 boot are invisible to an older binary. Snapshot before the upgrade, and roll back across it by stopping writers and moving `statev2.sqlite` aside (`docs/j5/runbooks/dogfood-runtime.md`); never run old and new binaries against the two files. `layerFromPath` calls one J5 step, `snapshotBeforeMigrations` (`apps/server/src/j5/persistence/MigrationSnapshot.ts`), before it builds the SQL layer, so every file-backed open is covered. When the database has migration history and either lane has a migration pending (upstream's `effect_sql_migrations` against upstream's manifest, or `j5_a2a_migrations` against J5's ledger list), it is first copied with `VACUUM INTO`, through a read-only connection, to `statev2.pre-migration-u-j.sqlite` beside it, named for the newest migration each lane had recorded. The copy is synchronous and does not use `node:sqlite`'s `backup()`: on the Node 26 that release executables embed, `backup()` rejects the one-step rate Node 24 accepts and its promise settles only when another event wakes the loop, which stopped the first nightly from starting. The snapshot is a compacted copy in rollback-journal mode; the server sets WAL again when it opens a restored one. A database with no history, or with nothing pending, is not copied. The newest three snapshots are kept (`MIGRATION_SNAPSHOTS_KEPT`) and older ones deleted. This is the roll-forward policy's emergency exit (issue #507): J5 adds no refusal to start on a database newer than the build, as upstream adds none for that case. Upstream refuses only a history that would skip one of V2's own migrations (`assertV2MigrationsCanRun` in `Migrations.ts`), and a second server on the same home (`apps/server/src/serverOwnership.ts`, exit 78), whose lock `layerMakeServer` takes before anything opens the database, so before the snapshot. A failed copy dies there, so the server does not start and nothing migrates. It dies rather than fails so the layer's error type, which upstream's tests name, stays upstream's. `MigrationSnapshot.test.ts` covers it. The `j5_run_observability_migrations` lane (one index) is not consulted. J5 tooling (`fleet-load.ts`, `devDeliverySeed.ts`, `dogfood-snapshot.sh`, `dogfood-local.sh`) targets `statev2.sqlite`; `apps/server/src/j5/persistence/StateV2Cutover.test.ts` covers the copy, no-recopy and failed-first-boot retry. Case 31 defines the compatibility wrapper; J5's own migration IDs remain in separate tracking tables and run after upstream migration completion. 2. The authenticated J5 MCP registration seam: the `layer` of `apps/server/src/mcp/McpHttpServer.ts` calls `layerJ5Toolkits(toolkitRegistration)` (`apps/server/src/j5/a2a/mcp/registration.ts`) in place of upstream's orchestrator, thread, attachment, project and environment registrations. Upstream's preview, preview-controls, worktree, pull-request, device and html toolkits are registered whole, as upstream registers them. Upstream's lint rule `no-raw-mcp-registration` allows MCP registration only in `McpHttpServer.ts`, so J5 registers through the `toolkitRegistration` function that file passes in. `layerJ5Toolkits` registers J5's own tools and the admitted part of those five upstream toolkits. `upstreamCatalog.ts` selects the admitted tools one by one and runs them on upstream's own handlers through `handlersFor`, which is one documented cast. Upstream's `McpServer.toolkit` asks for every tool's declared dependencies at registration, so J5's environment toolkit registration (`registration.ts`) provides `ThreadCommandExecutor.layer`, as upstream's own does. `apps/server/src/mcp/McpInvocationContext.ts` adds the `artifacts` capability that case 33's tools check. @@ -527,6 +527,8 @@ 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. 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 Current pin: `d2c440312e5f39d59827ed466838a623516454d6`, upstream's stable release tag `v0.1.3` on `main` (frozen 2026-10-27). The previous pin was `70d60e03a7a35c6fa131825bbfa05ec893e69912`, upstream's nightly tag `v0.1.1-nightly.20261017.3238`. @@ -834,15 +836,17 @@ explicitly marked. | `packages/provider-core/src/server/ProviderAdapter.ts` | R | 47, 60, N, Role library | | `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.ts` | A | 30, N | +| `apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts` | N | 106 | +| `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 | | `apps/server/src/orchestration-v2/ThreadSearch.ts` | N | 69, 91 | | `apps/server/src/orchestration-v2/ThreadSearch.test.ts` | N | 69 | -| `apps/server/src/orchestration-v2/runtimeLayer.ts` | R | 5, 21, 26, 30, 38, 91 | +| `apps/server/src/orchestration-v2/runtimeLayer.ts` | R | 5, 21, 26, 30, 38, 91, 106 | | `apps/server/src/os-jank.ts` | R | H | | `apps/server/src/persistence/Sqlite.ts` | A | 1, 31 | | `apps/server/src/project/RepositoryIdentityResolver.test.ts` | N | gh default repository patch | @@ -994,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/server/src/j5/a2a/AgentCrewInstanceService.ts b/apps/server/src/j5/a2a/AgentCrewInstanceService.ts index b21eda2a42099..125e569b01f0f 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; } @@ -181,6 +183,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; @@ -226,6 +229,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), @@ -269,7 +273,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..4fb3fb4132f81 --- /dev/null +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.integration.test.ts @@ -0,0 +1,384 @@ +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"; +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)), + CrewTurnContext.layer.pipe(Layer.provide(Layer.merge(harness.layer, harness.orchestrator))), + ); + 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.notInclude(preparing.messages[0]!.text, "Shared goal"); + assert.isTrue(preparing.messages[0]!.text.endsWith("Review the code now.")); + assert.isTrue((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 crewContext = yield* CrewTurnContext.CrewTurnContext; + const promptFor = (text: string) => + Effect.gen(function* () { + let prompt = ""; + yield* crewContext.deliver( + { + threadId, + runId: ready.runs[0]!.id, + 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"); + // 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", + 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* promptFor(nextText); + assert.include(prompt, "joined: tester:"); + assert.isTrue(prompt.endsWith("Edited second 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}`), + 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, 2); + 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..b38868f792eec --- /dev/null +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts @@ -0,0 +1,587 @@ +import * as CrewTurnContext from "./CrewTurnContext.ts"; +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + RunId, + 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 { 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"; +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(); + let receiptReads = 0; + 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.sync(() => { + receiptReads += 1; + return 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); + }); + 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.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", + 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* () { + let prompt: string | null = null; + yield* (yield* CrewTurnContext.CrewTurnContext).deliver( + { + threadId: seatId, + runId: runId, + 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, + runId, + providerThread: providerThread("native-1"), + message: { text }, + } as never); + return steered[0] ?? null; + }).pipe(Effect.provide(deliveryLayer)); + return { + sql, + crews, + commands, + receipts, + receiptReads: () => receiptReads, + rejected, + layer, + send, + deliver, + steer, + notified, + recorded, + recording, + }; +}); + +it.effect( + "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 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); + 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("provider refusal keeps the introduction and roster changes owed", () => + Effect.gen(function* () { + const f = yield* fixture; + 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", { 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"); + assert.equal(yield* f.deliver("later"), "later"); + }).pipe(Effect.provide(base)), +); + +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")]); + 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( + "an archived waiting seat cannot bypass workspace preparation when independently reopened", + () => + Effect.gen(function* () { + const f = yield* fixture; + 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").pipe(Effect.result))._tag, "Failure"); + }).pipe(Effect.provide(base)), +); + +it.effect( + "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"); + assert.lengthOf(yield* Ref.get(f.commands), 0); + }).pipe(Effect.provide(base)), +); + +it.effect( + "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) + 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 [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)), +); + +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 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; + 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)), +); + +/** 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/CrewDeliveryContext.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.ts new file mode 100644 index 0000000000000..c8364aa8dc07a --- /dev/null +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.ts @@ -0,0 +1,125 @@ +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"; +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 { participantIdForThread } from "./HomeRegistrar.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."; + } +} + +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."; + } +} + +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 receipts = yield* CommandReceiptStoreV2; + const crews = yield* Crews.AgentCrewInstanceService; + const locks = yield* KeyedLock.make(); + 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))) + 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); + 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 (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, + }); + } + return yield* inner.dispatch({ + ...command, + dispatchMode: { type: "defer_start", workspaceStrategy: workspace }, + }); + }).pipe( + Effect.mapError((cause) => + isDispatchError(cause) + ? cause + : new Orchestrator.OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause, + }), + ), + ), + ); + 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 }); + }), +).pipe(Layer.provide(Crews.layer)); diff --git a/apps/server/src/j5/a2a/CrewLaunchReporter.test.ts b/apps/server/src/j5/a2a/CrewLaunchReporter.test.ts index 46f242e5e9281..23aa157ff59f8 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 5ad145fbf4e0b..1679ea0dfc9c0 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 { /** @@ -243,14 +242,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 4c54f18464564..2aa6f5cebb55f 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", [ @@ -356,9 +364,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}`); @@ -391,7 +403,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="); @@ -469,16 +487,17 @@ 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"); + 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. @@ -1547,18 +1566,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), ); @@ -1859,8 +1870,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"); @@ -2084,21 +2096,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 f85c9fc9fcb09..d73163f6dc2c3 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" } @@ -624,8 +626,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( { @@ -645,8 +647,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, @@ -656,12 +659,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, @@ -698,38 +701,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, agent_display_name) + VALUES (${member.threadId}, ${text}, ${workspaceJson}, ${member.agentDisplayName}) + 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* ( @@ -740,6 +722,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] : [], @@ -756,17 +749,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", { @@ -781,7 +764,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"] = Effect.fn("j5.a2a.crewLaunch.launch")( @@ -846,7 +835,7 @@ export const layer = Layer.effect( ); }, (launch, input) => - // 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 3cb54a0cd2a75..bb7621970ba5a 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.test.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.test.ts @@ -1847,7 +1847,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; @@ -1901,11 +1901,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)); @@ -2225,11 +2234,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)); @@ -2448,11 +2464,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/CrewTurnContext.ts b/apps/server/src/j5/a2a/CrewTurnContext.ts new file mode 100644 index 0000000000000..afb7191ebdee4 --- /dev/null +++ b/apps/server/src/j5/a2a/CrewTurnContext.ts @@ -0,0 +1,261 @@ +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"; +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 { crewContextRecordIds, 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 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; +} + +export class CrewTurnContext extends Context.Service< + CrewTurnContext, + { + /** 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({ + 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 orchestrator = yield* Orchestrator.OrchestratorV2; + 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, delivered_conversation + 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 }); + // 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: displayNames.get(member.threadId) ?? member.agentId ?? "custom", + reason: member.reason, + })); + const rosterJson = encodeRoster(roster); + let prefix = ""; + // 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>/, + () => + 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"); + } + + // 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: 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` + 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) => + isCrewTurnContextError(cause) ? cause : new CrewTurnContextError({ threadId, cause }), + ), + ); + }); + 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 = Effect.fn("CrewTurnContext.deliver")(function* ( + delivery: CrewDelivery, + send: (text: string) => Effect.Effect, + ) { + 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: delivery.threadId, + cause, + }), + ), + ); + // 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) => ({ + steerTurn: (input) => + deliver( + { + threadId: input.threadId, + runId: input.runId, + 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 }); +}); + +/** 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), +); + +export const layer = layerWithChanges.pipe(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 e157b67721afb..64bd7ef76f419 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:" }))), @@ -1440,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.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 90ce0917e3e16..f7615109ad222 100644 --- a/apps/server/src/j5/a2a/crewGateNotice.ts +++ b/apps/server/src/j5/a2a/crewGateNotice.ts @@ -12,6 +12,7 @@ import { formatRunFailureField } from "./runFailures.ts"; * on the roster. */ export type SeatStartVerdict = + | { readonly kind: "waiting" } | { readonly kind: "started" } | { readonly kind: "failed"; @@ -147,7 +148,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)}` @@ -199,7 +205,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 18ffcc58fc386..20e23b878255e 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -562,10 +562,10 @@ 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..cb6a42651967a --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.test.ts @@ -0,0 +1,68 @@ +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: 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 + (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; + readonly delivered_conversation: string | null; + }>` + 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), + ["builder", "reviewer"], + ); + assert.include( + roster.map((member) => member.reason), + "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", + "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 new file mode 100644 index 0000000000000..ed7847a1bcc4b --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/049_CrewSeatActivation.ts @@ -0,0 +1,25 @@ +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, + delivered_conversation TEXT, + agent_display_name 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 21b1eb415db28..f2eada4bc4b2c 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"; @@ -205,6 +206,7 @@ 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..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 }); @@ -76,6 +95,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 +110,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 +145,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 433d8393066f4..59d052f2decb6 100644 --- a/apps/server/src/j5/a2a/spawnedChildrenRead.ts +++ b/apps/server/src/j5/a2a/spawnedChildrenRead.ts @@ -51,6 +51,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 76a0beabfda27..248ed37a06b2d 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)), @@ -196,6 +206,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/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 4837c4a2ac1c6..76a37e7a7af9e 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,9 +21,20 @@ 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 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"; @@ -332,3 +344,143 @@ 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)), + // 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", () => + 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, runId: RunId.make("run:crew-builder"), 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.succeedSome(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 bb9d50d38e8f2..e7e534bf5dd24 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 = Effect.fn("ProviderTurnControlService.load")(function* (input: { readonly threadId: ThreadId; @@ -352,7 +354,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 5faf24a8fd5aa..1a6e14591b721 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -1,9 +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, GitCommandError, MessageId, NodeId, @@ -46,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"; @@ -1471,6 +1482,10 @@ 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; + /** Builds history handoffs with the real service instead of a canned summary. */ + readonly realHandoffs?: boolean; readonly text?: string; readonly resumeThread: ( ids: NativeResumeIds, @@ -1516,7 +1531,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({ @@ -1524,7 +1542,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, @@ -1535,26 +1555,33 @@ 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)({ - 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(() => { @@ -1599,6 +1626,7 @@ function makeNativeResumeHarness(input: { }, resumeThread, ensureThread, + startTurn: nativeStartTurn, } as never), }), Layer.mock(ProviderAuthService.ProviderAuthService)({ @@ -1618,7 +1646,23 @@ function makeNativeResumeHarness(input: { resumeThread, ensureThread, 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* () { @@ -1872,3 +1916,193 @@ 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: { + 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${delivery.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"]); + }), +); + +// 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)), + // 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 } = {}) => + 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 2e8dea4ff0c0f..b134cc01a39e4 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 { @@ -157,6 +158,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; @@ -1307,132 +1309,157 @@ export const layer: Layer.Layer< !coveredItemIds.has(item.id) && historicalMessage(item) !== null, ); - const startWithHandoffs = Effect.fn("ProviderTurnStartService.startWithHandoffs")( - function* (turnInput: Parameters[0], compact = false) { - const retryHandoff = - missedItems.length === 0 - ? [] - : [ - yield* contextHandoffService.prepareProviderHandoff({ + const startAssignmentWithHandoffs = Effect.fn( + "ProviderTurnStartService.startAssignmentWithHandoffs", + )(function* ( + turnInput: Parameters[0], + compact: boolean, + assignment: string, + ) { + const retryHandoff = + missedItems.length === 0 + ? [] + : [ + yield* contextHandoffService.prepareProviderHandoff({ + threadId: projection.thread.id, + targetRunId: run.id, + transferId: null, + fromProviderThreadIds: [providerThread.id], + toProviderThreadId: providerThread.id, + fromProviderInstanceId: run.providerInstanceId, + toProviderInstanceId: run.providerInstanceId, + coveredRunOrdinals: { + from: missedRuns[0]!.ordinal, + to: missedRuns.at(-1)!.ordinal, + }, + strategy: "delta_since_target_last_seen", + items: missedItems, + runs: projection.runs, + createdAt: yield* DateTime.now, + }), + ]; + const delivery = yield* deliverContextHandoffs({ + handoffs: [...effectiveHandoffs, ...retryHandoff], + deferInline: compact || goalCommand, + providerThread: runningProviderThread, + budget: Effect.gen(function* () { + return handoffBudget({ + tokenCap, + modelContextWindow, + userText: restartNote === "" ? assignment : `${restartNote}\n\n${assignment}`, + attachments: message.attachments, + providerThread: budgetProviderThread, + nativeContextEstimate: + budgetProviderThread.contextUsage?.usedTokens === undefined + ? yield* nativeContextEstimate + : 0, + }); + }), + alreadyDeliveredItemIds: deliveredItemIds, + ...(session.injectHistory === undefined + ? {} + : { + inject: (history: ProviderAdapter.ProviderAdapterV2HistoricalContext) => + session.injectHistory!({ + providerThread: runningProviderThread, + ...history, + }), + }), + persist: Effect.fn("ProviderTurnStartService.persist")(function* (handoff) { + const updatedAt = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: yield* idAllocator.allocate.event({ threadId: projection.thread.id, - targetRunId: run.id, - transferId: null, - fromProviderThreadIds: [providerThread.id], - toProviderThreadId: providerThread.id, - fromProviderInstanceId: run.providerInstanceId, - toProviderInstanceId: run.providerInstanceId, - coveredRunOrdinals: { - from: missedRuns[0]!.ordinal, - to: missedRuns.at(-1)!.ordinal, - }, - strategy: "delta_since_target_last_seen", - items: missedItems, - runs: projection.runs, - createdAt: yield* DateTime.now, }), - ]; - const delivery = yield* deliverContextHandoffs({ - handoffs: [...effectiveHandoffs, ...retryHandoff], - deferInline: compact || goalCommand, - providerThread: runningProviderThread, - budget: Effect.gen(function* () { - return handoffBudget({ - tokenCap, - modelContextWindow, - userText: restartNote === "" ? userText : `${restartNote}\n\n${userText}`, - attachments: message.attachments, - providerThread: budgetProviderThread, - nativeContextEstimate: - budgetProviderThread.contextUsage?.usedTokens === undefined - ? yield* nativeContextEstimate - : 0, - }); - }), - alreadyDeliveredItemIds: deliveredItemIds, - ...(session.injectHistory === undefined - ? {} - : { - inject: (history: ProviderAdapter.ProviderAdapterV2HistoricalContext) => - session.injectHistory!({ - providerThread: runningProviderThread, - ...history, - }), - }), - persist: Effect.fn("ProviderTurnStartService.persist")(function* (handoff) { - const updatedAt = yield* DateTime.now; - yield* eventSink.write({ - events: [ - { - id: yield* idAllocator.allocate.event({ - threadId: projection.thread.id, + type: "context-handoff.updated", + threadId: projection.thread.id, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: updatedAt, + payload: { ...handoff, updatedAt }, + }, + ], + }); + }), + }); + if (!(yield* isCurrentAttemptInStatus("running"))) return false; + const start = compact ? session.compactThread! : session.startTurn; + const context = [delivery.context, restartNote].filter((part) => part !== "").join("\n\n"); + const { restartContinuationOfRunId: _resumedRunId, ...promptedInput } = turnInput; + yield* start({ + ...(noteContinuation ? promptedInput : turnInput), + message: { + ...turnInput.message, + text: + context === "" || goalCommand + ? assignment + : `${context}\n\nUser message:\n${assignment}`, + }, + }).pipe( + // Clear pending handoff markers for refused prompts so the next turn retains the native session. + Effect.tapError((error) => + refusedBeforePrompt(error) + ? delivery.unsent.pipe( + Effect.catchCause(() => + Effect.logWarning("Failed to restore unsent context handoffs", { + runId: run.id, }), - type: "context-handoff.updated", - threadId: projection.thread.id, - runId: run.id, - providerInstanceId: run.providerInstanceId, - occurredAt: updatedAt, - payload: { ...handoff, updatedAt }, - }, - ], - }); + ), + ) + : Effect.void, + ), + ); + // After provider acceptance, failed delivery bookkeeping must not stop live ingestion. + yield* delivery.delivered.pipe( + Effect.catchCause(() => + Effect.logWarning("Failed to record accepted context handoff delivery", { + runId: run.id, + deliveryStatus: "pending", }), - }); - if (!(yield* isCurrentAttemptInStatus("running"))) return; - const start = compact ? session.compactThread! : session.startTurn; - const context = [delivery.context, restartNote] - .filter((part) => part !== "") - .join("\n\n"); - const { restartContinuationOfRunId: _resumedRunId, ...promptedInput } = turnInput; - yield* start({ - ...(noteContinuation ? promptedInput : turnInput), - message: { - ...turnInput.message, - text: - context === "" || goalCommand - ? userText - : `${context}\n\nUser message:\n${userText}`, - }, - }).pipe( - // Clear pending handoff markers for refused prompts so the next turn retains the native session. - Effect.tapError((error) => - refusedBeforePrompt(error) - ? delivery.unsent.pipe( - Effect.catchCause(() => - Effect.logWarning("Failed to restore unsent context handoffs", { - runId: run.id, - }), - ), - ) - : Effect.void, - ), - ); - // After provider acceptance, failed delivery bookkeeping must not stop live ingestion. - yield* delivery.delivered.pipe( - Effect.catchCause(() => - Effect.logWarning("Failed to record accepted context handoff delivery", { - runId: run.id, - deliveryStatus: "pending", - }), - ), - ); - }, - Effect.mapError((cause) => - cause._tag === "ProviderAdapterTurnStartError" - ? cause - : new ProviderAdapter.ProviderAdapterTurnStartError({ - driver: session.driver, + ), + ); + return true; + }); + const crewSeat = + Option.isSome(crewTurnContext) && + (yield* crewTurnContext.value.isSeat(projection.thread.id)); + const startWithHandoffs = ( + turnInput: Parameters[0], + compact = false, + ) => + (crewSeat + ? crewTurnContext.value.deliver( + { threadId: projection.thread.id, - providerThreadId: providerThread.id, runId: run.id, - cause, - }), - ), - ); + providerThread: runningProviderThread, + text: userText, + }, + (assignment) => startAssignmentWithHandoffs(turnInput, compact, assignment), + ) + : startAssignmentWithHandoffs(turnInput, compact, userText) + ).pipe( + Effect.asVoid, + Effect.mapError((cause) => + cause._tag === "ProviderAdapterTurnStartError" + ? cause + : new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: session.driver, + threadId: projection.thread.id, + providerThreadId: providerThread.id, + runId: run.id, + cause, + }), + ), + ); const deliverySession = effectiveHandoffs.length === 0 && missedItems.length === 0 && restartNote === "" && - !noteContinuation + !noteContinuation && + !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 c248e4e7d0d6e..6d525677d8e46 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -1,3 +1,5 @@ +import * as CrewTurnContext from "../j5/a2a/CrewTurnContext.ts"; +import * as CrewDeliveryContext from "../j5/a2a/CrewDeliveryContext.ts"; import * as GuestShareService from "../guest/GuestShareService.ts"; import * as UsageLimitRecoveryWorker from "./UsageLimitRecoveryWorker.ts"; import * as Scheduler from "../scheduling/Scheduler.ts"; @@ -174,7 +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(layerCrewTurnContextProvided), Layer.provide( Layer.mergeAll( layerContextHandoffServiceProvided, @@ -191,6 +229,7 @@ const layerProviderTurnStartServiceProvided = ProviderTurnStartService.layer.pip ); const layerProviderTurnControlServiceProvided = ProviderTurnControlService.layer.pipe( + Layer.provide(layerCrewTurnContextProvided), Layer.provide(Layer.merge(ProjectionStore.layer, layerProviderSessionManagerProvided)), ); const layerRuntimeRequestServiceProvided = RuntimeRequestService.layer.pipe( @@ -230,30 +269,6 @@ const layerRunFinalizationServiceProvided = RunFinalizationService.layer.pipe( ), ); -const layerOrchestratorProvided = 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 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 cac4dcb80914d..cb71e5b24392c 100644 --- a/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx +++ b/apps/web/src/j5/a2a/ThreadA2ARenderer.test.tsx @@ -187,3 +187,9 @@ describe("literalUserMessageContext", () => { expect(context.recordsById.size).toBe(0); }); }); + +it("shows authored text exactly as written, even when it begins with the Crew context marker", () => { + const authored = `\nmine\n\n\n${peerPlainRaw}`; + expect(presentJ5UserMessage(message({ text: authored }))).toBeNull(); + expect(participantIdsForThreadA2AEnvelope(authored)).toEqual([]); +}); 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/apps/web/src/j5/crew/crewNotices.logic.test.ts b/apps/web/src/j5/crew/crewNotices.logic.test.ts index 0df722d7762f4..bd521c34d7751 100644 --- a/apps/web/src/j5/crew/crewNotices.logic.test.ts +++ b/apps/web/src/j5/crew/crewNotices.logic.test.ts @@ -610,3 +610,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/crewState.test.ts b/apps/web/src/j5/crew/crewState.test.ts index 88a77a04d07a3..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, @@ -56,6 +57,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 +85,7 @@ describe("crew state", () => { failed: 1, "needs-you": 1, settled: 1, + "not-started": 0, idle: 1, archived: 0, unknown: 1, @@ -97,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/crew/crewState.ts b/apps/web/src/j5/crew/crewState.ts index 62ad046564cbb..f07e1b2becda2 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"; @@ -49,7 +51,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"; }; /** @@ -66,6 +68,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, @@ -75,6 +87,7 @@ export const summarizeCrewState = ( failed: 0, "needs-you": 0, settled: 0, + "not-started": 0, idle: 0, archived: 0, unknown: 0, @@ -96,6 +109,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 9933318f605ec..2b5b71ceefd2c 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 3f61526ee3a40..8bc3ffae375d1 100644 --- a/apps/web/src/j5/fleet/FleetPage.tsx +++ b/apps/web/src/j5/fleet/FleetPage.tsx @@ -34,7 +34,12 @@ import { requestConfirmDialog } from "../../confirmDialog"; import type { ArchiveWarningCrew } from "@t3tools/client-runtime/j5/archive-flow"; import { ArchiveWarningCrewSeats } 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, @@ -79,12 +84,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}`; @@ -719,7 +729,15 @@ 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 80019e77bac03..11038d10da34f 100644 --- a/apps/web/src/j5/threads/SpawnedChildren.tsx +++ b/apps/web/src/j5/threads/SpawnedChildren.tsx @@ -21,7 +21,7 @@ import { useThreadShells } from "../../state/entities"; import { environmentServerConfigsAtom } from "../../state/server"; import { buildThreadRouteParams } from "../../threadRoutes"; import { RelativeAge } from "../RelativeAge"; -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"; @@ -262,8 +262,12 @@ function SpawnedChildGroupRows( {status === null ? ( - {(child.seat === null ? null : seatRunLabel(thread.runtime?.status)) ?? - "Idle"} + {child.seat === null + ? "Idle" + : seatQuietLabel({ + notStarted: child.seat.notStarted, + runtime: thread.runtime, + })} ) : ( <> 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 ff7c55216e5d4..35ee5ff0b50fc 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 | | --------------------------------- | -------------- | -------- | --------------------------------------------------------------------------- | @@ -402,7 +404,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, 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 b69939f8d6b3b..2e70672572565 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. @@ -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, 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. @@ -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 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 @@ -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) @@ -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 df56a6b1b4431..414ec46e0009f 100644 --- a/packages/client-runtime/src/j5/crewNotices.ts +++ b/packages/client-runtime/src/j5/crewNotices.ts @@ -9,7 +9,7 @@ export interface CrewNoticeMessage { readonly createdBy?: string | undefined; } -export type SeatStart = "started" | "failed" | "pending"; +export type SeatStart = "waiting" | "started" | "failed" | "pending"; export interface CrewRosterSeat { readonly seat: string; @@ -83,7 +83,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) => @@ -97,7 +97,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); @@ -239,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", diff --git a/packages/contracts/src/j5.ts b/packages/contracts/src/j5.ts index 9ff70fcbf67e3..f24359c97be75 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, }), ), 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. diff --git a/packages/provider-core/src/j5/orchestrationInstructions.ts b/packages/provider-core/src/j5/orchestrationInstructions.ts index 1f0cdf1da69be..1827cd2747a38 100644 --- a/packages/provider-core/src/j5/orchestrationInstructions.ts +++ b/packages/provider-core/src/j5/orchestrationInstructions.ts @@ -27,7 +27,7 @@ ${AGENT_INVOCATION_INSTRUCTIONS} - Follow a running delegate's \`next\`: its completion wakes this thread, so end your turn. Do not poll it (\`task_status\`, \`sleep\`, watchers, Monitor, ScheduleWakeup). Stop a delegate run you replace or no longer need with \`task_cancel\`. - If you are a subagent or delegated child, do the work yourself. Start no subagents unless your task says to.`, `- 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.`, `- Given a thread id, \`t3_thread_read\` it before you answer about it.