From cc1f8b7944a346f19a0c9ff22cd614079abc83dd Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 13:36:10 -0400 Subject: [PATCH 1/9] feat(j5): j5_send_message tells the sender how a message will land (#746) The result carries a typed deliveryOutcome (steered, queued, starting, waiting_for_recipient), predicted at send time by the rule the delivery worker applies, replacing the old delivery field. deliveryNotice stays as advice for held queues, usage limits and failed worktree setup. Co-Authored-By: Claude Sonnet 5.5 --- .../a2a/DeliveryTransport.integration.test.ts | 130 ++++++++++---- .../src/j5/a2a/EnvelopeFormatter.test.ts | 2 +- .../src/j5/a2a/PeerPollRoundTrip.test.ts | 4 +- apps/server/src/j5/a2a/SendService.ts | 2 +- apps/server/src/j5/a2a/contracts.ts | 23 ++- apps/server/src/j5/a2a/envelopes.v1.json | 2 +- apps/server/src/j5/a2a/mcp/handlers.ts | 4 +- apps/server/src/j5/a2a/mcp/outsideAgent.ts | 7 +- apps/server/src/j5/a2a/receiverBacklog.ts | 169 ++++++++++++------ docs/j5/product/a2a/agent-tools.md | 6 +- 10 files changed, 244 insertions(+), 105 deletions(-) diff --git a/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts b/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts index 2d394d4d439d8..d3f631785310d 100644 --- a/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts +++ b/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts @@ -151,7 +151,7 @@ import { formatPeerEnvelope, } from "./EnvelopeFormatter.ts"; import { A2ALedger, layer as ledgerLayer } from "./LedgerService.ts"; -import { readReceiverBacklog, withDeliveryNotice } from "./receiverBacklog.ts"; +import { readReceiverDelivery, withDeliveryOutcome } from "./receiverBacklog.ts"; import { noneLayer as peerDirectoryNoneLayer } from "./PeerDirectory.ts"; import { A2ALifecycleService, manualLayer as lifecycleServiceLayer } from "./LifecycleService.ts"; import { @@ -1135,20 +1135,23 @@ it.effect("measures the backlog a send waits behind on a busy receiver", () => message: `Update ${name}`, acceptedAt: `2026-09-24T00:00:0${sequence++}.000Z`, }); - const backlogFor = (sent: { readonly messageId: LedgerMessageId }) => - readReceiverBacklog({ + const deliveryFor = (sent: { readonly messageId: LedgerMessageId }) => + readReceiverDelivery({ receiverId: target.receiverId, callerThreadId: caller.threadId, sentMessageId: sent.messageId, }); + const backlogFor = (sent: { readonly messageId: LedgerMessageId }) => + deliveryFor(sent).pipe(Effect.map((delivery) => delivery?.backlog)); - // An idle receiver takes the message at once: nothing to warn about. + // An idle receiver, or a seat that has not started, takes the message at once: nothing to + // warn about. const firstInput = sendInput(caller, "first"); const first = yield* send.send(firstInput); - assert.isUndefined(yield* backlogFor(first)); + assert.deepStrictEqual(yield* deliveryFor(first), { outcome: "starting" }); // Nor once the message has started its own run. yield* worker.drain; - assert.isUndefined(yield* backlogFor(first)); + assert.deepStrictEqual(yield* deliveryFor(first), { outcome: "starting" }); yield* startPendingTestTurn(target.threadId); yield* finishTestTurn(harness, target.threadId); @@ -1156,14 +1159,13 @@ it.effect("measures the backlog a send waits behind on a busy receiver", () => // A replayed send of a message that has already run reports the current state. const replay = yield* send.send(firstInput); assert.equal(replay.messageId, first.messageId); - assert.isUndefined(yield* backlogFor(replay)); + assert.isUndefined(yield* deliveryFor(replay)); // Committed sends the worker has not handed over yet are waiting too. yield* send.send(sendInput(caller, "second")); const third = yield* send.send(sendInput(caller, "third")); - assert.deepStrictEqual(yield* backlogFor(third), { - type: "behind_turn", - waiting: 2, - fromCaller: 2, + assert.deepStrictEqual(yield* deliveryFor(third), { + outcome: "queued", + backlog: { type: "behind_turn", waiting: 2, fromCaller: 2 }, }); // Queued runs and pending deliveries add up; another sender's count is not the caller's. yield* worker.drain; @@ -1176,7 +1178,7 @@ it.effect("measures the backlog a send waits behind on a busy receiver", () => // Only agents on this server are measured. assert.isUndefined( - yield* readReceiverBacklog({ + yield* readReceiverDelivery({ receiverId: ParticipantId.make("agent:j5-a2a-delivery-backlog-elsewhere"), callerThreadId: caller.threadId, sentMessageId: third.messageId, @@ -1224,34 +1226,98 @@ it.effect("counts a message queued before an Astra turn became steerable", () => "queued", ); assert.deepStrictEqual( - yield* readReceiverBacklog({ + yield* readReceiverDelivery({ receiverId: target.receiverId, callerThreadId: ThreadId.make("thread:j5-a2a-delivery-backlog-astra-queued-caller"), sentMessageId: target.messageId, }), - { type: "behind_turn", waiting: 1, fromCaller: 0 }, + { outcome: "queued", backlog: { type: "behind_turn", waiting: 1, fromCaller: 0 } }, ); }).pipe(Effect.provide(makeTestLayer(harness))); }), ); -it.effect( - "reports no backlog for a running Astra receiver, which takes peer messages mid-turn", - () => - Effect.gen(function* () { - const harness = yield* makeHarness; - yield* Effect.gen(function* () { - const target = yield* seedTarget("backlog-astra", "gpt-6-astra"); - yield* startBusyTurn(target); - assert.isUndefined( - yield* readReceiverBacklog({ - receiverId: target.receiverId, - callerThreadId: ThreadId.make("thread:j5-a2a-delivery-backlog-astra-caller"), - sentMessageId: target.messageId, - }), - ); - }).pipe(Effect.provide(makeTestLayer(harness))); - }), +it.effect("predicts how a message lands on a busy receiver, before and after the worker acts", () => + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* Effect.gen(function* () { + const send = yield* A2ASendService; + const worker = yield* A2ADeliveryWorker; + const effects = yield* OrchestrationEffectWorkerV2; + const caller = yield* seedTarget("outcome-caller"); + let sequence = 0; + const sendTo = ( + target: { readonly receiverId: ParticipantId }, + name: string, + mode?: "steer" | "restart", + ) => + send.send({ + commandId: CommCommandId.make(`command:j5-a2a-delivery-outcome-${name}`), + senderThreadId: caller.threadId, + to: target.receiverId, + message: `Update ${name}`, + ...(mode === undefined + ? {} + : { mode, modeLimit: { runtimeMode: "full-access", interactionMode: "default" } }), + acceptedAt: `2026-09-24T00:00:0${sequence++}.000Z`, + }); + const outcomeOf = ( + target: { readonly receiverId: ParticipantId }, + sent: { readonly messageId: LedgerMessageId }, + mode?: "steer" | "restart", + ) => + readReceiverDelivery({ + receiverId: target.receiverId, + callerThreadId: caller.threadId, + sentMessageId: sent.messageId, + mode, + }).pipe(Effect.map((delivery) => delivery?.outcome)); + + // A running GPT 6 turn takes the update mid-turn. Once the worker has steered it, the + // message has no run of its own, and still reads as steered. + const astra = yield* seedTarget( + "outcome-astra", + "gpt-6-astra", + undefined, + caller.ledgerProjectId, + ); + yield* startBusyTurn(astra); + const steeredByDefault = yield* sendTo(astra, "astra"); + assert.equal(yield* outcomeOf(astra, steeredByDefault), "steered"); + const drained = yield* worker.drain.pipe(Effect.forkChild({ startImmediately: true })); + yield* runWorkerUntil(effects, drained); + assert.lengthOf(yield* Ref.get(harness.steerInputs), 1); + assert.equal(yield* outcomeOf(astra, steeredByDefault), "steered"); + + // Another model queues a plain update behind the turn, steers when asked, and starts a new + // turn for a restart. + const other = yield* seedTarget( + "outcome-other", + modelSelection.model, + undefined, + caller.ledgerProjectId, + ); + yield* startBusyTurn(other); + assert.equal(yield* outcomeOf(other, yield* sendTo(other, "plain")), "queued"); + assert.equal( + yield* outcomeOf(other, yield* sendTo(other, "steer", "steer"), "steer"), + "steered", + ); + assert.equal( + yield* outcomeOf(other, yield* sendTo(other, "restart", "restart"), "restart"), + "starting", + ); + + // Nobody is on a thread that has not started: the message starts its first turn. + const idle = yield* seedTarget( + "outcome-idle", + modelSelection.model, + undefined, + caller.ledgerProjectId, + ); + assert.equal(yield* outcomeOf(idle, yield* sendTo(idle, "idle")), "starting"); + }).pipe(Effect.provide(makeLifecycleTestLayer(harness))); + }), ); it.effect( @@ -3903,7 +3969,7 @@ const sendNoticeTo = Effect.fn("A2AIntegration.sendNoticeTo")(function* ( message: "An update", acceptedAt: "2026-09-24T00:00:00.000Z", }); - return (yield* withDeliveryNotice(sent, { + return (yield* withDeliveryOutcome(sent, { receiverId: target.receiverId, callerThreadId: caller.threadId, })).deliveryNotice; diff --git a/apps/server/src/j5/a2a/EnvelopeFormatter.test.ts b/apps/server/src/j5/a2a/EnvelopeFormatter.test.ts index f910a2a442748..b46e1026a027d 100644 --- a/apps/server/src/j5/a2a/EnvelopeFormatter.test.ts +++ b/apps/server/src/j5/a2a/EnvelopeFormatter.test.ts @@ -175,7 +175,7 @@ it("renders the receiver backlog notice with its measured counts", () => { it("keeps the tool descriptions on their documented contracts", () => { assert.equal( A2A_SEND_TOOL_DESCRIPTION, - "Send one durable message. To another agent, three uses: a **plain send** when you don't need a reply; an **ask** — set expect_reply=true with a one-line intent, opening an exchange the receiver owes a reply to; a **reply** — include the exchange_id from the ask you are answering, which closes that exchange. To the human, only an ask: a plain send to a person is refused — if nobody needs to act, say it in your own thread instead. Set urgency only when asking the human. Use this tool only for participants already returned by j5_list_participants; when creating a Peer Agent, put any reply expectation in j5_spawn_agent's brief instead of sending a follow-up ask. Returns once the message is committed; delivery continues asynchronously — carry on with your work, and the reply arrives later as an incoming message. An agent that is busy may handle each message as its own turn after its current one ends, so put related updates in one message rather than sending them one by one; the result's deliveryNotice says when your message will wait behind the receiver's current turn. To interrupt an agent that is busy, set mode: mode=steer puts your message into the turn it is running now, and mode=restart stops that turn and starts it again on your message. Without mode the message is delivered the ordinary way, whatever its text or its intent says: Claude and Codex GPT 6 agents take it into the turn they are running, and other agents take it after their current turn ends. intent only labels an ask. Leave mode out for updates and replies. A Claude agent takes a steer once its running tool calls finish, and on other agents a steer can cancel the tool calls in flight, so keep it for a correction the receiver must see now, not for an update. An idle receiver starts a turn on your message whichever mode you set. Attach files for an agent on this server with attachments: pending uploads from t3_attachment_prepare_upload, or files its thread already holds. A provider Subagent is not a participant and is refused. Reuse client_request_id to retry the same send safely.", + "Send one durable message. To another agent, three uses: a **plain send** when you don't need a reply; an **ask** — set expect_reply=true with a one-line intent, opening an exchange the receiver owes a reply to; a **reply** — include the exchange_id from the ask you are answering, which closes that exchange. To the human, only an ask: a plain send to a person is refused — if nobody needs to act, say it in your own thread instead. Set urgency only when asking the human. Use this tool only for participants already returned by j5_list_participants; when creating a Peer Agent, put any reply expectation in j5_spawn_agent's brief instead of sending a follow-up ask. Returns once the message is committed; delivery continues asynchronously — carry on with your work, and the reply arrives later as an incoming message. An agent that is busy may handle each message as its own turn after its current one ends, so put related updates in one message rather than sending them one by one. The result's deliveryOutcome says what will happen to your message: steered (it joins the turn the receiver is running now), queued (it waits for the receiver's current turn to end, or for a held queue or usage limit to lift; deliveryNotice says what it waits behind), starting (it begins a turn for an idle receiver, a Crew member that has not started, or a restart), or waiting_for_recipient (the receiver's server is offline and receives it when next available). The outcome is predicted as the message is sent, and you are told separately if it later fails to arrive. A refused message is an error with its reason, not an outcome. To interrupt an agent that is busy, set mode: mode=steer puts your message into the turn it is running now, and mode=restart stops that turn and starts it again on your message. Without mode the message is delivered the ordinary way, whatever its text or its intent says: Claude and Codex GPT 6 agents take it into the turn they are running, and other agents take it after their current turn ends. intent only labels an ask. Leave mode out for updates and replies. A Claude agent takes a steer once its running tool calls finish, and on other agents a steer can cancel the tool calls in flight, so keep it for a correction the receiver must see now, not for an update. An idle receiver starts a turn on your message whichever mode you set. Attach files for an agent on this server with attachments: pending uploads from t3_attachment_prepare_upload, or files its thread already holds. A provider Subagent is not a participant and is refused. Reuse client_request_id to retry the same send safely.", ); assert.include( A2A_SEND_TOOL_DESCRIPTION, diff --git a/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts b/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts index b69230be1fc94..446b0cadea2a4 100644 --- a/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts +++ b/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts @@ -954,7 +954,7 @@ it.effect( }; const waiting = yield* vmServer.send.send(note); assert.equal(waiting.receiverServer, laptop.label); - assert.equal(waiting.delivery, "waiting_for_recipient"); + assert.equal(waiting.deliveryOutcome, "waiting_for_recipient"); assert.isString(waiting.recipientLastAvailableAt); assert.equal( waiting.note, @@ -985,7 +985,7 @@ it.effect( for (const retry of [note, ended]) { const retried = yield* vmServer.send.send(retry); assert.equal(retried.receiverServer, laptop.label, retry.commandId); - assert.isUndefined(retried.delivery, retry.commandId); + assert.isUndefined(retried.deliveryOutcome, retry.commandId); assert.isUndefined(retried.note, retry.commandId); } }), diff --git a/apps/server/src/j5/a2a/SendService.ts b/apps/server/src/j5/a2a/SendService.ts index 5865ee94b2c24..67b325b7c7425 100644 --- a/apps/server/src/j5/a2a/SendService.ts +++ b/apps/server/src/j5/a2a/SendService.ts @@ -1265,7 +1265,7 @@ const rawLayer: Layer.Layer< return { ...result, receiverServer: server.name, - delivery: "waiting_for_recipient", + deliveryOutcome: "waiting_for_recipient", ...(server.lastAvailableAt === null ? {} : { recipientLastAvailableAt: server.lastAvailableAt }), diff --git a/apps/server/src/j5/a2a/contracts.ts b/apps/server/src/j5/a2a/contracts.ts index 919daedb85781..309d532f5c411 100644 --- a/apps/server/src/j5/a2a/contracts.ts +++ b/apps/server/src/j5/a2a/contracts.ts @@ -447,6 +447,22 @@ export const SendAsOutsideAgentInput = Schema.Struct({ }); export type SendAsOutsideAgentInput = typeof SendAsOutsideAgentInput.Type; +/** + * What a sent message will do, predicted when it is sent by the rule the delivery worker applies: + * `steered` lands in the turn the recipient is running now (directly, or by interrupting and + * restarting that turn when the sender asked for a `steer`); `queued` waits for a turn boundary or + * for a held queue or usage limit to lift; `starting` begins a turn for an idle recipient, a Crew + * seat that has not started, or a `restart`; `waiting_for_recipient` is an offline peer server. + * A refusal is not an outcome: it is the tool's error, with its reason. + */ +export const SendDeliveryOutcome = Schema.Literals([ + "steered", + "queued", + "starting", + "waiting_for_recipient", +]); +export type SendDeliveryOutcome = typeof SendDeliveryOutcome.Type; + export const SendMessageResult = Schema.Struct({ messageId: LedgerMessageId, exchangeId: Schema.NullOr(ExchangeId), @@ -457,8 +473,11 @@ export const SendMessageResult = Schema.Struct({ deliveryNotice: Schema.optional(Schema.String), /** The name of the peer server the receiver lives on; absent for a receiver on this server. */ receiverServer: Schema.optionalKey(Schema.String), - /** Present when the receiver's server polls this one and is offline: the message waits for it. */ - delivery: Schema.optionalKey(Schema.Literal("waiting_for_recipient")), + /** + * Absent when nothing can be said: the receiver is a person or an agent on a peer server that is + * available (its server decides on arrival), or the message already ran or was cancelled. + */ + deliveryOutcome: Schema.optionalKey(SendDeliveryOutcome), /** When that server was last available: its last poll. */ recipientLastAvailableAt: Schema.optionalKey(Schema.String), /** The same facts in one sentence an agent reads at a glance. */ diff --git a/apps/server/src/j5/a2a/envelopes.v1.json b/apps/server/src/j5/a2a/envelopes.v1.json index 7989976256dd6..67e7b8fae42ef 100644 --- a/apps/server/src/j5/a2a/envelopes.v1.json +++ b/apps/server/src/j5/a2a/envelopes.v1.json @@ -13,7 +13,7 @@ "replyInstruction": "Reply once with j5_send_message(to=\"{{senderId}}\", exchange_id=\"{{exchangeId}}\", message=\"...\") to close the exchange. Follow-ups from the asker carrying this id join the same exchange.", "oneShotInstruction": "The sender did not request a reply to this message. Use j5_send_message without exchange_id only if a new message is needed.", "closedExchangeInstruction": "The platform closed this exchange when this reply was sent. No further reply is required.", - "sendToolDescription": "Send one durable message. To another agent, three uses: a **plain send** when you don't need a reply; an **ask** — set expect_reply=true with a one-line intent, opening an exchange the receiver owes a reply to; a **reply** — include the exchange_id from the ask you are answering, which closes that exchange. To the human, only an ask: a plain send to a person is refused — if nobody needs to act, say it in your own thread instead. Set urgency only when asking the human. Use this tool only for participants already returned by j5_list_participants; when creating a Peer Agent, put any reply expectation in j5_spawn_agent's brief instead of sending a follow-up ask. Returns once the message is committed; delivery continues asynchronously — carry on with your work, and the reply arrives later as an incoming message. An agent that is busy may handle each message as its own turn after its current one ends, so put related updates in one message rather than sending them one by one; the result's deliveryNotice says when your message will wait behind the receiver's current turn. To interrupt an agent that is busy, set mode: mode=steer puts your message into the turn it is running now, and mode=restart stops that turn and starts it again on your message. Without mode the message is delivered the ordinary way, whatever its text or its intent says: Claude and Codex GPT 6 agents take it into the turn they are running, and other agents take it after their current turn ends. intent only labels an ask. Leave mode out for updates and replies. A Claude agent takes a steer once its running tool calls finish, and on other agents a steer can cancel the tool calls in flight, so keep it for a correction the receiver must see now, not for an update. An idle receiver starts a turn on your message whichever mode you set. Attach files for an agent on this server with attachments: pending uploads from t3_attachment_prepare_upload, or files its thread already holds. A provider Subagent is not a participant and is refused. Reuse client_request_id to retry the same send safely.", + "sendToolDescription": "Send one durable message. To another agent, three uses: a **plain send** when you don't need a reply; an **ask** — set expect_reply=true with a one-line intent, opening an exchange the receiver owes a reply to; a **reply** — include the exchange_id from the ask you are answering, which closes that exchange. To the human, only an ask: a plain send to a person is refused — if nobody needs to act, say it in your own thread instead. Set urgency only when asking the human. Use this tool only for participants already returned by j5_list_participants; when creating a Peer Agent, put any reply expectation in j5_spawn_agent's brief instead of sending a follow-up ask. Returns once the message is committed; delivery continues asynchronously — carry on with your work, and the reply arrives later as an incoming message. An agent that is busy may handle each message as its own turn after its current one ends, so put related updates in one message rather than sending them one by one. The result's deliveryOutcome says what will happen to your message: steered (it joins the turn the receiver is running now), queued (it waits for the receiver's current turn to end, or for a held queue or usage limit to lift; deliveryNotice says what it waits behind), starting (it begins a turn for an idle receiver, a Crew member that has not started, or a restart), or waiting_for_recipient (the receiver's server is offline and receives it when next available). The outcome is predicted as the message is sent, and you are told separately if it later fails to arrive. A refused message is an error with its reason, not an outcome. To interrupt an agent that is busy, set mode: mode=steer puts your message into the turn it is running now, and mode=restart stops that turn and starts it again on your message. Without mode the message is delivered the ordinary way, whatever its text or its intent says: Claude and Codex GPT 6 agents take it into the turn they are running, and other agents take it after their current turn ends. intent only labels an ask. Leave mode out for updates and replies. A Claude agent takes a steer once its running tool calls finish, and on other agents a steer can cancel the tool calls in flight, so keep it for a correction the receiver must see now, not for an update. An idle receiver starts a turn on your message whichever mode you set. Attach files for an agent on this server with attachments: pending uploads from t3_attachment_prepare_upload, or files its thread already holds. A provider Subagent is not a participant and is refused. Reuse client_request_id to retry the same send safely.", "listToolDescription": "Your address book, one project at a time: the project's agents, and the human, with the display name to recognize them by, the participant_id to address them with, the project_id and project_title that place them, and what each accepts (messages, exchanges, urgency). Leave project_id out to list your own project; pass another project's id, from t3_project_list, to list that one. People appear in every listing. Results come a page at a time: your own row first, then the people, then agents with the most recently active first. Narrow a listing with name_contains, or with settled=true or settled=false for settled or active agents. If this server is peered with others, each row also carries `server`: the name of the server the participant lives on, and whether it is this one (`local`), and the result names every server in `servers`; pass a peer server's name as server to list that server's agents instead of this one's. When you're told to message someone by name or role, resolve them here first. Your own row is marked self=true and its project_title is the project you work in; it cannot receive messages or open exchanges from you — use schedule_task if you need a future trigger for yourself. Provider Subagents are not participants: they do not appear here and cannot be messaged. Archived agents are hidden by default; set include_archived=true to see them with archived=true. They cannot receive messages or open Exchanges. The roster changes — after you spawn, archive, unarchive, or delete an agent, call this again instead of reusing a stale listing.", "receiverBacklogNotice": "{{receiverId}} is in the middle of a turn, with {{waiting}} message(s) waiting for it ({{fromYou}} from you). It will handle each one as a separate turn after its current turn ends, so put any further updates for it in one message.", "receiverLimitAutoResumeNotice": "{{receiverId}} hit its provider's usage limit and continues automatically at {{resetAt}}. Your message is saved and will run then, in the order it was sent. Don't send it again.", diff --git a/apps/server/src/j5/a2a/mcp/handlers.ts b/apps/server/src/j5/a2a/mcp/handlers.ts index 8ae3cc61a4a6d..78d2af13e30fb 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -55,7 +55,7 @@ import { A2ALedger } from "../LedgerService.ts"; import { PeerDirectory } from "../PeerDirectory.ts"; import { PeerRegistryService } from "../PeerRegistryService.ts"; import { ParticipantPlacementService } from "../PlacementService.ts"; -import { withDeliveryNotice } from "../receiverBacklog.ts"; +import { withDeliveryOutcome } from "../receiverBacklog.ts"; import { A2ASendService } from "../SendService.ts"; import { stopThread } from "../stopThread.ts"; import { sendClaimingAttachments } from "./attachments.ts"; @@ -415,7 +415,7 @@ const handlers = { ? yield* send() : yield* sendClaimingAttachments(receiverThreadId, attachments, send); yield* worker.notify; - return yield* withDeliveryNotice(result, { + return yield* withDeliveryOutcome(result, { receiverId: input.to, callerThreadId: scope.thread.threadId, mode, diff --git a/apps/server/src/j5/a2a/mcp/outsideAgent.ts b/apps/server/src/j5/a2a/mcp/outsideAgent.ts index 46f605097ecc4..86117630b2e11 100644 --- a/apps/server/src/j5/a2a/mcp/outsideAgent.ts +++ b/apps/server/src/j5/a2a/mcp/outsideAgent.ts @@ -17,6 +17,7 @@ import { exceededDispatchModeLimit } from "../../../orchestration-v2/DispatchMod import { ThreadManagementService } from "../../../orchestration-v2/ThreadManagementService.ts"; import { type CommCommandId, outsideAgentParticipantId } from "../contracts.ts"; import { A2ADeliveryWorker } from "../DeliveryWorker.ts"; +import { withDeliveryOutcome } from "../receiverBacklog.ts"; import { A2ASendService } from "../SendService.ts"; import { sendClaimingAttachments } from "./attachments.ts"; import type { J5SendMessageInput } from "./tools.ts"; @@ -201,7 +202,7 @@ export const sendAsOutsideAgent = Effect.fn("j5.a2a.mcp.sendAsOutsideAgent")(fun ? yield* send() : yield* sendClaimingAttachments(receiver.threadId, attachments, send); yield* (yield* A2ADeliveryWorker).notify; - // No backlog notice: it counts the caller's own waiting messages by its thread, and an outside - // agent has none. - return result; + // The outcome only: the backlog notice counts the caller's own waiting messages by its thread, + // and an outside agent has none. + return yield* withDeliveryOutcome(result, { receiverId: input.to, mode }); }); diff --git a/apps/server/src/j5/a2a/receiverBacklog.ts b/apps/server/src/j5/a2a/receiverBacklog.ts index 95d28f4c772fe..5ce02279731be 100644 --- a/apps/server/src/j5/a2a/receiverBacklog.ts +++ b/apps/server/src/j5/a2a/receiverBacklog.ts @@ -4,7 +4,7 @@ import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import { OrchestratorV2 } from "../../orchestration-v2/Orchestrator.ts"; -import { latestActiveRun } from "../../orchestration-v2/ThreadManagementService.ts"; +import { isActiveRun, latestActiveRun } from "../../orchestration-v2/ThreadManagementService.ts"; import { latestExecutedRun, latestRootProviderFailure, @@ -22,7 +22,13 @@ import { formatReceiverLimitNotice, formatReceiverQueueHeldNotice, } from "./EnvelopeFormatter.ts"; -import { LedgerMessageId, Participant, type ParticipantId, type SendMode } from "./contracts.ts"; +import { + LedgerMessageId, + Participant, + type ParticipantId, + type SendDeliveryOutcome, + type SendMode, +} from "./contracts.ts"; export type ReceiverBacklog = | { @@ -40,23 +46,32 @@ export type ReceiverBacklog = /** Its queue is held, so the message runs only once a person resumes it. */ | { readonly type: "queue_held" }; +/** What the sender is told about a message to an agent on this server. */ +export type ReceiverDelivery = { + readonly outcome: Exclude; + /** Why a queued message waits, when there is something to tell the sender. */ + readonly backlog?: ReceiverBacklog; +}; + const decodeParticipant = Schema.decodeUnknownEffect(Schema.fromJsonString(Participant)); /** - * What a just-sent message is waiting behind: the receiver's running turn and the - * A2A messages after it, both those already queued as runs and those the delivery - * worker has not handed over yet; or a held queue or usage limit, which only a resume - * or a continue lifts (D4). Undefined when the message will not wait: the receiver is - * idle and takes it now, takes it mid-turn (Claude or a GPT 6 model, or a steer or restart), is - * not an agent on this server, or the message has already run or will never run. - * Measured when called and never stored, so it is advice to the sender, not a delivery - * fact. A failed read is logged and reads as undefined: the message is already - * committed, and the send must not fail over advice. + * What will become of a just-sent message to an agent on this server, by the rule the delivery + * worker applies, so the sender need not wait for the worker: `steered` into the running turn a + * Claude or GPT 6 receiver takes updates in, or one a sender-asked `steer` lands on; `starting` + * for an idle receiver, a Crew seat that has not started, or a `restart`; `queued` behind a turn + * or held queue, with a `backlog` saying why when it is something the sender can act on. A message + * the worker already handed over reads from what it did: its own run, or a delivery with no run, + * which is a steer. Undefined when nothing can be said: the receiver is not an agent on this + * server, or the message has already run or will never run. Measured when called and never + * stored, so it is advice to the sender, not a delivery fact. A failed read is logged and reads + * as undefined: the message is already committed, and the send must not fail over advice. */ -export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( +export const readReceiverDelivery = Effect.fn("j5.a2a.readReceiverDelivery")( function* (input: { readonly receiverId: ParticipantId; - readonly callerThreadId: ThreadId; + /** The sending thread; an outside agent has none, and counts no waiting messages of its own. */ + readonly callerThreadId?: ThreadId | undefined; readonly sentMessageId: LedgerMessageId; /** How the sender asked for the message to land; absent means `queue`. */ readonly mode?: SendMode | undefined; @@ -91,16 +106,29 @@ export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( ]); if (target.thread.archivedAt !== null) return undefined; + const mode = input.mode ?? "queue"; const runByMessage = new Map(target.runs.map((run) => [run.userMessageId, run])); const sentRun = runByMessage.get(deliveryMessageId(input.sentMessageId)); - // Already started or finished (a replay reports the current state, not the first one). - if (sentRun !== undefined && sentRun.status !== "queued") return undefined; const pending = pendingRows.filter( (row) => !runByMessage.has(deliveryMessageId(LedgerMessageId.make(row.message_id))), ); - // Neither queued nor pending: cancelled or alarmed, so it is not waiting. - if (sentRun === undefined && !pending.some((row) => row.message_id === input.sentMessageId)) - return undefined; + if (sentRun !== undefined && sentRun.status !== "queued") { + // The worker got there first: a turn already runs on it (a replay reports the current + // state, not the first one). A steer by interrupt-restart shows the same way. + return isActiveRun(sentRun) + ? ({ outcome: mode === "steer" ? "steered" : "starting" } satisfies ReceiverDelivery) + : undefined; + } + if (sentRun === undefined && !pending.some((row) => row.message_id === input.sentMessageId)) { + // Not queued and not pending: a steer the worker has delivered into a running turn leaves + // no run of its own; a cancelled or alarmed message is not going anywhere. + const status = (yield* sql<{ readonly status: string }>` + SELECT status FROM j5_a2a_delivery WHERE message_id = ${input.sentMessageId} LIMIT 1 + `)[0]?.status; + return status === "delivered" + ? ({ outcome: mode === "restart" ? "starting" : "steered" } satisfies ReceiverDelivery) + : undefined; + } if (latestActiveRun(target) === undefined) { // An idle receiver takes the message now, resuming a held queue first, unless it @@ -115,36 +143,45 @@ export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( turnItemTypes: ["error"], }); const hold = idleQueueHold({ ...target, turnItems }); - if (hold?.type === "worktree_setup_failed") return { type: "queue_held" } as const; - if (hold?.type !== "usage_limit") return undefined; - // Upstream continues it at the reset only when its recovery is armed for this limit, - // as the thread's usage-limit banner shows. - const recovery = target.thread.limitRecovery; - const resetAt = latestRootProviderFailure(hold.run, turnItems)?.resetAt; - return { - type: "usage_limit", - resetAt: - recovery?.autoResume === true && - recovery.runId === hold.run.id && - recovery.resetAt === resetAt - ? recovery.resetAt - : null, - } satisfies ReceiverBacklog; + if (hold?.type === "worktree_setup_failed") + return { outcome: "queued", backlog: { type: "queue_held" } } satisfies ReceiverDelivery; + if (hold?.type === "usage_limit") { + // Upstream continues it at the reset only when its recovery is armed for this limit, + // as the thread's usage-limit banner shows. + const recovery = target.thread.limitRecovery; + const resetAt = latestRootProviderFailure(hold.run, turnItems)?.resetAt; + return { + outcome: "queued", + backlog: { + type: "usage_limit", + resetAt: + recovery?.autoResume === true && + recovery.runId === hold.run.id && + recovery.resetAt === resetAt + ? recovery.resetAt + : null, + }, + } satisfies ReceiverDelivery; + } + // Resuming a held queue starts its messages first and this one joins the back; the sender + // needs no notice, it runs without a person. + return target.runs.some((run) => run.status === "queued" && run.id !== sentRun?.id) + ? ({ outcome: "queued" } satisfies ReceiverDelivery) + : ({ outcome: "starting" } satisfies ReceiverDelivery); } // Not yet handed over, so a running Claude or GPT 6 turn, or the turn a steer or restart lands on, // will take it mid-turn. Once queued, it stays queued even if the receiver's turn later // becomes steerable. - const mode = input.mode ?? "queue"; if ( sentRun === undefined && (mode === "queue" ? peerSteeringRun(target, "peer") : requestedSteeringRun(target, "peer", mode)) !== undefined ) - return undefined; + return { outcome: mode === "restart" ? "starting" : "steered" } satisfies ReceiverDelivery; // A held queue drains only when someone resumes the thread, not when its turn ends. if (target.runs.some((run) => run.status === "queued" && run.queueHeld === true)) - return { type: "queue_held" } as const; + return { outcome: "queued", backlog: { type: "queue_held" } } satisfies ReceiverDelivery; const callerId = (yield* sql<{ readonly sender_id: string }>` SELECT sender_id FROM j5_a2a_delivery WHERE message_id = ${input.sentMessageId} LIMIT 1 `)[0]?.sender_id; @@ -159,17 +196,22 @@ export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( messageIds: queued.map((run) => run.userMessageId), })).messages; return { - type: "behind_turn", - waiting: queued.length + pending.length, - fromCaller: - queuedMessages.filter((message) => message.senderThreadId === input.callerThreadId).length + - pending.filter((row) => row.sender_id === callerId).length, - } satisfies ReceiverBacklog; + outcome: "queued", + backlog: { + type: "behind_turn", + waiting: queued.length + pending.length, + fromCaller: + input.callerThreadId === undefined + ? 0 + : queuedMessages.filter((message) => message.senderThreadId === input.callerThreadId) + .length + pending.filter((row) => row.sender_id === callerId).length, + }, + } satisfies ReceiverDelivery; }, (effect, input) => effect.pipe( Effect.catch((cause) => - Effect.logWarning("J5 A2A receiver backlog read failed", { + Effect.logWarning("J5 A2A receiver delivery read failed", { receiverId: input.receiverId, cause, }).pipe(Effect.as(undefined)), @@ -177,28 +219,39 @@ export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( ), ); -/** Adds a notice to a send result when the message will wait: behind the receiver's turn, or on its hold. */ -export const withDeliveryNotice = Effect.fn("j5.a2a.withDeliveryNotice")(function* < +/** + * Adds what the sender should know to a send result: the predicted `deliveryOutcome`, and a + * `deliveryNotice` when the message waits on something the sender can act on. An outside agent has + * no thread to count waiting messages by, so it gets the outcome alone. + */ +export const withDeliveryOutcome = Effect.fn("j5.a2a.withDeliveryOutcome")(function* < R extends { readonly messageId: LedgerMessageId }, >( result: R, input: { readonly receiverId: ParticipantId; - readonly callerThreadId: ThreadId; + readonly callerThreadId?: ThreadId | undefined; readonly mode?: SendMode | undefined; }, ) { - const backlog = yield* readReceiverBacklog({ ...input, sentMessageId: result.messageId }); - if (backlog === undefined) return result; + const delivery = yield* readReceiverDelivery({ ...input, sentMessageId: result.messageId }); + if (delivery === undefined) return result; + const { backlog } = delivery; const deliveryNotice = - backlog.type === "behind_turn" - ? formatReceiverBacklogNotice({ - receiverId: input.receiverId, - waiting: backlog.waiting, - fromYou: backlog.fromCaller, - }) - : backlog.type === "usage_limit" - ? formatReceiverLimitNotice({ receiverId: input.receiverId, resetAt: backlog.resetAt }) - : formatReceiverQueueHeldNotice({ receiverId: input.receiverId }); - return { ...result, deliveryNotice }; + input.callerThreadId === undefined || backlog === undefined + ? undefined + : backlog.type === "behind_turn" + ? formatReceiverBacklogNotice({ + receiverId: input.receiverId, + waiting: backlog.waiting, + fromYou: backlog.fromCaller, + }) + : backlog.type === "usage_limit" + ? formatReceiverLimitNotice({ receiverId: input.receiverId, resetAt: backlog.resetAt }) + : formatReceiverQueueHeldNotice({ receiverId: input.receiverId }); + return { + ...result, + deliveryOutcome: delivery.outcome, + ...(deliveryNotice === undefined ? {} : { deliveryNotice }), + }; }); diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index ac393768a120b..449331b56276d 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -21,7 +21,7 @@ An agent learns what it can do from its tools, and it reads a tool's description ### `j5_send_message` -**Description:** "Send one durable message. To another agent, three uses: a **plain send** when you don't need a reply; an **ask** — set expect_reply=true with a one-line intent, opening an exchange the receiver owes a reply to; a **reply** — include the exchange_id from the ask you are answering, which closes that exchange. To the human, only an ask: a plain send to a person is refused — if nobody needs to act, say it in your own thread instead. Set urgency only when asking the human. Use this tool only for participants already returned by j5_list_participants; when creating a Peer Agent, put any reply expectation in j5_spawn_agent's brief instead of sending a follow-up ask. Returns once the message is committed; delivery continues asynchronously — carry on with your work, and the reply arrives later as an incoming message. An agent that is busy may handle each message as its own turn after its current one ends, so put related updates in one message rather than sending them one by one; the result's deliveryNotice says when your message will wait behind the receiver's current turn. To interrupt an agent that is busy, set mode: mode=steer puts your message into the turn it is running now, and mode=restart stops that turn and starts it again on your message. Without mode the message is delivered the ordinary way, whatever its text or its intent says: Claude and Codex GPT 6 agents take it into the turn they are running, and other agents take it after their current turn ends. intent only labels an ask. Leave mode out for updates and replies. A Claude agent takes a steer once its running tool calls finish, and on other agents a steer can cancel the tool calls in flight, so keep it for a correction the receiver must see now, not for an update. An idle receiver starts a turn on your message whichever mode you set. Attach files for an agent on this server with attachments: pending uploads from t3_attachment_prepare_upload, or files its thread already holds. A provider Subagent is not a participant and is refused. Reuse client_request_id to retry the same send safely." +**Description:** "Send one durable message. To another agent, three uses: a **plain send** when you don't need a reply; an **ask** — set expect_reply=true with a one-line intent, opening an exchange the receiver owes a reply to; a **reply** — include the exchange_id from the ask you are answering, which closes that exchange. To the human, only an ask: a plain send to a person is refused — if nobody needs to act, say it in your own thread instead. Set urgency only when asking the human. Use this tool only for participants already returned by j5_list_participants; when creating a Peer Agent, put any reply expectation in j5_spawn_agent's brief instead of sending a follow-up ask. Returns once the message is committed; delivery continues asynchronously — carry on with your work, and the reply arrives later as an incoming message. An agent that is busy may handle each message as its own turn after its current one ends, so put related updates in one message rather than sending them one by one. The result's deliveryOutcome says what will happen to your message: steered (it joins the turn the receiver is running now), queued (it waits for the receiver's current turn to end, or for a held queue or usage limit to lift; deliveryNotice says what it waits behind), starting (it begins a turn for an idle receiver, a Crew member that has not started, or a restart), or waiting_for_recipient (the receiver's server is offline and receives it when next available). The outcome is predicted as the message is sent, and you are told separately if it later fails to arrive. A refused message is an error with its reason, not an outcome. To interrupt an agent that is busy, set mode: mode=steer puts your message into the turn it is running now, and mode=restart stops that turn and starts it again on your message. Without mode the message is delivered the ordinary way, whatever its text or its intent says: Claude and Codex GPT 6 agents take it into the turn they are running, and other agents take it after their current turn ends. intent only labels an ask. Leave mode out for updates and replies. A Claude agent takes a steer once its running tool calls finish, and on other agents a steer can cancel the tool calls in flight, so keep it for a correction the receiver must see now, not for an update. An idle receiver starts a turn on your message whichever mode you set. Attach files for an agent on this server with attachments: pending uploads from t3_attachment_prepare_upload, or files its thread already holds. A provider Subagent is not a participant and is refused. Reuse client_request_id to retry the same send safely." | Input | Type | Required | Meaning | | ------------------- | ----------------- | ------------------------------------ | ------------------------------------------------------------------------------- | @@ -42,9 +42,9 @@ An agent learns what it can do from its tools, and it reads a tool's description **Attachments.** Each is a pending upload from `t3_attachment_prepare_upload`, or an attachment the receiver's thread already holds. They are claimed into the receiver's thread before the message is committed, and released if the send is refused before anything is committed (an unacceptable sender, receiver or request). A storage failure leaves the claims in place, because nobody knows then whether the message was committed. A person and an agent on a peer server take no attachments. This replaces J5's own version of `t3_thread_send_attachments`, which sent a thinner message through the same ledger: no ask or reply, no retry key, no landing choice. -**Result:** the message id and the Exchange's state. When the receiver is an agent on this server and the message will wait, the result also carries a `deliveryNotice`. Behind a turn the receiver will not take it into, the notice states how many messages are waiting for it, how many of them are the caller's, and that each will run as its own turn. A message to an agent stopped on a usage limit always waits until the agent continues. When the message waits on that limit, or on the receiver's held queue or failed worktree setup, the notice says it runs, in the order it was sent, once a person resumes or continues the receiver, or at the reset time when upstream continues it automatically, and that it should not be sent again. The notice is measured as the message is sent; a sender is not told when a receiver's queue is held later. When the recipient lives on a peer server, the result also names that server. When that server is offline, the result says the message is waiting for the recipient and when the server was last available, and its wording names the server: "Recorded. is on Laptop, which is offline, last available 3 h ago; it receives this when Laptop is next available." A recipient on this server adds nothing; one on an online peer server adds only that server's name. +**Result:** the message id, the Exchange's state, and a `deliveryOutcome`, one per call because the tool takes one recipient: `steered`, the message joins the turn the receiver is running now (directly on Claude and Codex GPT 6, or by interrupting and restarting that turn when the sender set `mode=steer` on a provider that does it that way, as Cursor does); `queued`, it waits for the receiver's current turn to end or for a held queue or usage limit to lift; `starting`, it begins a turn now, for an idle receiver, a Crew member that has not started (its first assignment), or a `restart`; `waiting_for_recipient`, the receiver's server is offline. The outcome is predicted as the message is sent, by the same rule the delivery worker applies (`peerSteeringRun` and `requestedSteeringRun` in `DeliveryTransport.ts`), and never waits on the worker. It is a prediction: a turn that ends before delivery turns a `steered` into a start, and the existing late-failure alarm is how a sender learns a message did not arrive. It is absent when nothing can be said: the receiver is a person or an agent on an available peer server, which decides on arrival, or the message has already run or was cancelled. A refusal is not an outcome. It stays a tool error with its reason (see Errors). When the message will wait, the result also carries a `deliveryNotice`, advice about what it waits behind. Behind a turn the receiver will not take it into, the notice states how many messages are waiting for it, how many of them are the caller's, and that each will run as its own turn. A message to an agent stopped on a usage limit always waits until the agent continues. When the message waits on that limit, or on the receiver's held queue or failed worktree setup, the notice says it runs, in the order it was sent, once a person resumes or continues the receiver, or at the reset time when upstream continues it automatically, and that it should not be sent again. The notice is measured as the message is sent; a sender is not told when a receiver's queue is held later. When the recipient lives on a peer server, the result also names that server. When that server is offline, the outcome is `waiting_for_recipient`, and the result gives when the server was last available, and its wording names the server: "Recorded. is on Laptop, which is offline, last available 3 h ago; it receives this when Laptop is next available." A recipient on this server adds no server name; one on an online peer server adds only that server's name. -**Rules.** A message to the caller itself is refused. A message addressed to an [outside agent](index.md#participants) is refused for every sender, because nothing can be delivered to one. A send to a person that is not an ask is refused; a person never opens an Exchange, so there is nothing for an agent to reply to. Between agents, a further ask to a peer that already holds an open Exchange from the caller joins it as a follow-up. To a person, a further ask opens a new Exchange and a new inbox item unless it names an open one in `regarding`, in which case it joins that Exchange and is shown beneath the original ask. An ask to a person without an urgency is refused. An outside agent sends a plain message only, so `expect_reply`, `exchange_id`, `intent` and `urgency` are refused from it, and so is a person, who takes only asks. It reaches agents on this server only: an agent on a peer server and an id the server does not know are refused. A thread caller's receiver is held to the caller's permission modes only for `steer` and `restart`. An outside agent's receiver is held to the level the sign-in was approved at on every send, one that asks for no steer or restart included. The level is checked when the message is sent, not when it lands. An outside agent's message is recorded in the receiver's project, and its result carries no `deliveryNotice`. Attachments work the same for every sender. +**Rules.** A message to the caller itself is refused. A message addressed to an [outside agent](index.md#participants) is refused for every sender, because nothing can be delivered to one. A send to a person that is not an ask is refused; a person never opens an Exchange, so there is nothing for an agent to reply to. Between agents, a further ask to a peer that already holds an open Exchange from the caller joins it as a follow-up. To a person, a further ask opens a new Exchange and a new inbox item unless it names an open one in `regarding`, in which case it joins that Exchange and is shown beneath the original ask. An ask to a person without an urgency is refused. An outside agent sends a plain message only, so `expect_reply`, `exchange_id`, `intent` and `urgency` are refused from it, and so is a person, who takes only asks. It reaches agents on this server only: an agent on a peer server and an id the server does not know are refused. A thread caller's receiver is held to the caller's permission modes only for `steer` and `restart`. An outside agent's receiver is held to the level the sign-in was approved at on every send, one that asks for no steer or restart included. The level is checked when the message is sent, not when it lands. An outside agent's message is recorded in the receiver's project, and its result carries the `deliveryOutcome` but no `deliveryNotice`. Attachments work the same for every sender. **Errors**, each naming the actual state and the next command: the caller is not a participant (a provider Subagent or a deleted thread); the recipient is not addressable (pointing at `j5_list_participants`); the recipient is the caller (naming the caller's own id, and `schedule_task` for a future trigger to oneself); an ask without an intent; a send to a person that is not an ask (naming the legal move and the own-thread alternative); an ask to a person without urgency; an `exchange_id` or `regarding` that is unknown, already closed, or not the caller's (naming the Exchange's actual state); a first message to a participant on a peer server whose address book cannot be read, or that has not polled yet (naming that reason). For an outside agent: anything but a plain message (naming a retry without those fields); a person, a peer server's agent or an unknown id (naming the legal move); a receiver that runs above the approved level (naming the level). For every sender: a message addressed to an outside agent (saying nothing can be delivered to it). From 0277f60b26718d1db9180d4179f8f2ae68006853 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 13:47:10 -0400 Subject: [PATCH 2/9] feat(j5): agents choose between subagents and Crew members from context (#746) The standing instructions offer three ways of working (directly, subagents for independent assignments, a Crew for workers who must respond to each other), say the word "crew" does not decide it, and describe two ways to get help: a subagent or a Crew member. j5_spawn_agent is described only for a standalone agent the user asks for. Each tool description names its path. Crew members run their own review loops (three-round cutoff) and reach the Captain only for a review pass, a blocker or an unsettled disagreement; the Captain settles technical disagreements itself. Co-Authored-By: Claude Sonnet 5.5 --- apps/server/src/j5/a2a/crewGateNotice.test.ts | 4 + apps/server/src/j5/a2a/crewGateNotice.ts | 2 +- apps/server/src/j5/a2a/mcp/tools.test.ts | 15 ++++ apps/server/src/j5/a2a/mcp/tools.ts | 8 +- apps/server/src/j5/a2a/spawnIds.test.ts | 18 +++++ apps/server/src/j5/a2a/spawnIds.ts | 2 +- apps/server/src/j5/agents/agentDelegation.ts | 2 +- .../src/j5/orchestrationInstructions.test.ts | 77 +++++++++++++++---- .../src/j5/orchestrationInstructions.ts | 18 +++-- .../src/j5/playbookInstructions.test.ts | 2 +- .../src/j5/playbookInstructions.ts | 4 +- 11 files changed, 120 insertions(+), 32 deletions(-) diff --git a/apps/server/src/j5/a2a/crewGateNotice.test.ts b/apps/server/src/j5/a2a/crewGateNotice.test.ts index 82d9c3af2baa6..4a6dd6640a15d 100644 --- a/apps/server/src/j5/a2a/crewGateNotice.test.ts +++ b/apps/server/src/j5/a2a/crewGateNotice.test.ts @@ -282,6 +282,10 @@ describe("crew launch report", () => { "launch: 2 started, 0 failed, 0 not created, 0 start unconfirmed after 60s", ); assert.include(text, "Your crew is running."); + assert.include( + text, + "resolve technical disagreements within the agreed scope yourself, and ask the user only when product intent or their judgment is needed", + ); assert.notInclude(text, "seat_failed"); }); it("identifies automatic approval without attributing it to a person", () => { diff --git a/apps/server/src/j5/a2a/crewGateNotice.ts b/apps/server/src/j5/a2a/crewGateNotice.ts index 9f03224f1e94d..b1c633e7731c7 100644 --- a/apps/server/src/j5/a2a/crewGateNotice.ts +++ b/apps/server/src/j5/a2a/crewGateNotice.ts @@ -219,7 +219,7 @@ export const crewLaunchReportText = (input: { `This Crew follows playbook ${playbook.name}. Start it with j5_playbook_start(name: "${playbook.name}", client_request_id, crew_instance_id: "${instance.id}"). The platform hands each step to the seat that owns it; unowned steps are yours.`, ); prose.push( - "Seats are told to message you with their results; do not ask for the same results again. End your turn and read them as they arrive.", + "Seats are told to message you with their results; do not ask for the same results again. Members run their own review loops and message you only for a review pass, a blocker, or a disagreement they could not settle: you resolve technical disagreements within the agreed scope yourself, and ask the user only when product intent or their judgment is needed. End your turn and read their messages as they arrive.", ); return `${block}\n\n${prose.join(" ")}`; }; diff --git a/apps/server/src/j5/a2a/mcp/tools.test.ts b/apps/server/src/j5/a2a/mcp/tools.test.ts index bd3598fe18d05..d499e29a6f335 100644 --- a/apps/server/src/j5/a2a/mcp/tools.test.ts +++ b/apps/server/src/j5/a2a/mcp/tools.test.ts @@ -7,6 +7,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Schema from "effect/Schema"; import { Tool } from "effect/ai"; +import { J5DelegateTaskTool } from "../../agents/agentDelegation.ts"; import { A2A_SEND_TOOL_DESCRIPTION } from "../EnvelopeFormatter.ts"; import { J5OrchestratorSurface } from "./orchestratorSurface.ts"; import { J5_CLAUDE_MCP_ALLOWED_TOOLS } from "./claudeAllowedTools.ts"; @@ -212,6 +213,20 @@ it("refuses a blank spawn title and stores it trimmed", () => { assert.equal(decodeSpawnAgent({ ...spawn, title: " Login fixer " }).title, "Login fixer"); }); +it("says which of the two ways to get help each tool serves", () => { + // j5_spawn_agent serves neither: it is for a standalone agent the user asked for. + assert.include(J5_SPAWN_AGENT_DESCRIPTION, "Not a way to get help with your own work"); + assert.include(J5_SPAWN_AGENT_DESCRIPTION, "explicitly asks for a standalone agent"); + assert.include(J5_SPAWN_AGENT_DESCRIPTION, "create a subagent"); + assert.include(J5_PROPOSE_CREW_DESCRIPTION, "the second of the two ways to get help"); + assert.include( + J5_PROPOSE_CREW_DESCRIPTION, + "the word 'crew' in the user's message does not decide it", + ); + assert.include(J5_REQUEST_CREW_MEMBER_DESCRIPTION, "the second of the two ways to get help"); + assert.include(J5DelegateTaskTool.description, "the first of the two ways to get help"); +}); + it("tells a Captain proposing a crew how a playbook shapes the roster", () => { assert.include(J5_PROPOSE_CREW_DESCRIPTION, "For a crew built from a playbook"); }); diff --git a/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index 7c1b098a2543d..badbf5cfbd555 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -575,16 +575,16 @@ export const J5ArchiveCrewFailure = Schema.Struct({ export type J5ArchiveCrewFailure = typeof J5ArchiveCrewFailure.Type; export const J5_SPAWN_AGENT_DESCRIPTION = - "Spawn a Peer Agent: a full-citizen teammate with its own top-level thread, starting on your brief as its first turn. It joins your project unless you name another with project_id or set scratch for none, and records you as its immutable spawner; in your own project it is placed under you. It is addressable the moment this returns. In your brief, tell the new agent what it should do first and whether it should reply to you. Choose provider, model, and reasoning for the work in the brief — see orchestrator_capabilities for what's available. To run a persona from j5_list_personas, set `persona` to its id: the spawn gets that persona's instructions and runtime policy, and provider, model, and reasoning must be one of that persona's declared routes. Without a persona it runs in your permission and interaction modes, or in narrower ones you set with runtime_mode and interaction_mode. Without a persona its model and reasoning level must be ones the project's Models for custom members lists allow; an ineligible one is refused with the eligible ones. Attach files to the brief with attachments. Choose its workspace every time (see the workspace field). A new worktree is prepared after this returns, and the agent begins once it is bound, possibly while the project's setup script is still running; if preparing it fails, the agent's thread shows why, and it is not retried. Reuse client_request_id to retry the same spawn safely; reusing it with any change to the request is refused, so use a fresh one for new work."; + "Not a way to get help with your own work: use this only when the user explicitly asks for a standalone agent they will talk to, or when an outside agent or a skill you are following names it. For help, create a subagent (your native Subagent tool, or delegate_task) or put members on a Crew (j5_propose_crew). Spawn a Peer Agent: a full-citizen teammate with its own top-level thread, starting on your brief as its first turn. It joins your project unless you name another with project_id or set scratch for none, and records you as its immutable spawner; in your own project it is placed under you. It is addressable the moment this returns. In your brief, tell the new agent what it should do first and whether it should reply to you. Choose provider, model, and reasoning for the work in the brief — see orchestrator_capabilities for what's available. To run a persona from j5_list_personas, set `persona` to its id: the spawn gets that persona's instructions and runtime policy, and provider, model, and reasoning must be one of that persona's declared routes. Without a persona it runs in your permission and interaction modes, or in narrower ones you set with runtime_mode and interaction_mode. Without a persona its model and reasoning level must be ones the project's Models for custom members lists allow; an ineligible one is refused with the eligible ones. Attach files to the brief with attachments. Choose its workspace every time (see the workspace field). A new worktree is prepared after this returns, and the agent begins once it is bound, possibly while the project's setup script is still running; if preparing it fails, the agent's thread shows why, and it is not retried. Reuse client_request_id to retry the same spawn safely; reusing it with any change to the request is refused, so use a fresh one for new work."; export const J5_LIST_AGENTS_DESCRIPTION = - "List the personas in this environment: id, purpose, runtime policy, whether each can start now, and the provider, model, and reasoning it would run on. Read this before choosing a persona for j5_spawn_agent or a crew roster so the choice fits the task and the user's budget. Read-only."; + "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 delegate_task, a crew roster, or j5_spawn_agent 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. A custom seat's model and reasoning level, yours included, must be ones the project's Models for custom members lists allow; an ineligible one is refused with the eligible ones. 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."; + "Put members on a Crew, the second of the two ways to get help (the first is a subagent). Propose the crew you need for the brief you were given. Use it when the work needs workers who must respond to each other, such as a builder and reviewers iterating on a change; independent assignments go to subagents instead, and the word 'crew' in the user's message does not decide it. 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. A custom seat's model and reasoning level, yours included, must be ones the project's Models for custom members lists allow; an ineligible one is refused with the eligible ones. 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. Members run their own review loops and message you only for a review pass, a blocker, or a disagreement they could not settle; you resolve technical disagreements within the agreed scope and ask the user only when product intent or their judgment is needed. 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; a custom seat's model and reasoning level must be ones the project's Models for custom members lists allow, and 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."; + "Put one more member on a Crew, the second of the two ways to get help: 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; a custom seat's model and reasoning level must be ones the project's Models for custom members lists allow, and 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/spawnIds.test.ts b/apps/server/src/j5/a2a/spawnIds.test.ts index cfa12ed7ff3d7..93ee26dad6947 100644 --- a/apps/server/src/j5/a2a/spawnIds.test.ts +++ b/apps/server/src/j5/a2a/spawnIds.test.ts @@ -53,6 +53,7 @@ it("gives custom seats direct result and concern reporting without a mandatory a text, "use j5_send_message to coordinate directly with your Captain and other members", ); + assert.notInclude(text, "Share useful findings, evidence, questions, and blockers immediately"); assert.include(text, "final result, supporting evidence, and any remaining blockers"); assert.include(text, "j5_request_crew_member to add the seat directly"); assert.include(text, "Continue your work and coordination"); @@ -62,6 +63,23 @@ it("gives custom seats direct result and concern reporting without a mandatory a assert.notInclude(text, "j5_write_artifact"); }); +it("has members run their own review loops and reach the Captain only for a pass, a blocker or a disagreement", () => { + const text = spawnFirstTurnText({ ...identity, crew }); + assert.include( + text, + "send your findings directly to the teammate who owns it. When you receive findings, fix them and send the fix directly back to the reviewer. Repeat until no finding is unresolved.", + ); + // The cutoff is a fixed count of rounds, not a judgment about whether the loop is converging. + assert.include( + text, + "A round is one message of findings and the fix that answers it; if a loop has not produced a clean pass after three rounds, stop and send it to your Captain as a blocker or a disagreement.", + ); + assert.include( + text, + "Message your Captain only for: a review pass, which names the commit or change you reviewed so the Captain can tell it refers to the current code; a blocker, which names what you need; or a disagreement you could not settle with the teammate. Send no acknowledgments and no progress updates.", + ); +}); + it("retains declared persona output while allowing conversation before that output exists", () => { const text = spawnFirstTurnText({ ...identity, diff --git a/apps/server/src/j5/a2a/spawnIds.ts b/apps/server/src/j5/a2a/spawnIds.ts index 152150f27b858..5bee15c6863db 100644 --- a/apps/server/src/j5/a2a/spawnIds.ts +++ b/apps/server/src/j5/a2a/spawnIds.ts @@ -131,7 +131,7 @@ export const spawnFirstTurnText = (input: { crew.seatInstructions === undefined ? [] : [`\n${crew.seatInstructions}\n`]; - const collaboration = `\nResolve current participants with j5_list_participants and use j5_send_message to coordinate directly with your Captain and other members. Share useful findings, evidence, questions, and blockers immediately; do not wait for an artifact or coordination approval. Send your Captain your final result, supporting evidence, and any remaining blockers before finishing. If the roster lacks expertise needed to address a concern, tell your Captain what is missing and why so they can j5_request_crew_member to add the seat directly. Continue your work and coordination while the Captain handles staffing. A direct result is sufficient unless the user or your persona explicitly requires an artifact.\n`; + const collaboration = `\nResolve current participants with j5_list_participants and use j5_send_message to coordinate directly with your Captain and other members; do not wait for an artifact or coordination approval.\nYou run your own review loops. When you review a teammate's work, send your findings directly to the teammate who owns it. When you receive findings, fix them and send the fix directly back to the reviewer. Repeat until no finding is unresolved. A round is one message of findings and the fix that answers it; if a loop has not produced a clean pass after three rounds, stop and send it to your Captain as a blocker or a disagreement.\nMessage your Captain only for: a review pass, which names the commit or change you reviewed so the Captain can tell it refers to the current code; a blocker, which names what you need; or a disagreement you could not settle with the teammate. Send no acknowledgments and no progress updates. When you finish your assigned work, send your Captain your final result, supporting evidence, and any remaining blockers.\nIf the roster lacks expertise needed to address a concern, tell your Captain what is missing and why so they can j5_request_crew_member to add the seat directly. Continue your work and coordination while the Captain handles staffing. A direct result is sufficient unless the user or your persona explicitly requires an artifact.\n`; // A persona's declared deliverable supplements the conversation; it never gates coordination. const obligation = crew.obligation === undefined diff --git a/apps/server/src/j5/agents/agentDelegation.ts b/apps/server/src/j5/agents/agentDelegation.ts index ad63dfe13ea59..9d3ee0d7e09f5 100644 --- a/apps/server/src/j5/agents/agentDelegation.ts +++ b/apps/server/src/j5/agents/agentDelegation.ts @@ -38,7 +38,7 @@ export type J5DelegateTaskInput = typeof J5DelegateTaskInput.Type; * fallback. */ export const J5_DELEGATE_TASK_DESCRIPTION = - "Run one task as a J5-owned child of THIS thread with only the supplied task prompt; parent conversation history is not copied. Pass persona=ID when the user writes @persona:ID or asks for a persona by name: the server pins that persona's instructions, provider, model, reasoning, and runtime policy, so omit target and runtimeMode. Give the persona a self-contained task, and if that call fails, report the error instead of substituting a plain child. Without persona, this is a plain J5-tracked child for cross-provider work or for work the user wants tracked as a J5 task; for an ordinary subagent request, use your provider's native subagent mechanism instead. The childThreadId is backing storage, not an ordinary top-level thread. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Provider, model, model options (see orchestrator_capabilities), runtime mode, and interaction mode inherit unless target overrides them. Without persona the child's model and reasoning level, inherited ones included, must be ones the project's Models for custom members lists allow; a refusal lists the eligible ones to retry with in target. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn."; + "Create a subagent, the first of the two ways to get help (the second is a Crew member): run one task as a J5-owned child of THIS thread with only the supplied task prompt; parent conversation history is not copied. Pass persona=ID when the user writes @persona:ID or asks for a persona by name: the server pins that persona's instructions, provider, model, reasoning, and runtime policy, so omit target and runtimeMode. Give the persona a self-contained task, and if that call fails, report the error instead of substituting a plain child. Without persona, this is a plain J5-tracked child for cross-provider work or for work the user wants tracked as a J5 task; for an ordinary subagent request, use your provider's native subagent mechanism instead. The childThreadId is backing storage, not an ordinary top-level thread. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Provider, model, model options (see orchestrator_capabilities), runtime mode, and interaction mode inherit unless target overrides them. Without persona the child's model and reasoning level, inherited ones included, must be ones the project's Models for custom members lists allow; a refusal lists the eligible ones to retry with in target. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn."; /** J5's delegate_task: the upstream tool with the persona extension, registered in place of it. */ export const J5DelegateTaskTool = Tool.make("delegate_task", { diff --git a/packages/provider-core/src/j5/orchestrationInstructions.test.ts b/packages/provider-core/src/j5/orchestrationInstructions.test.ts index 7dd934f476ba0..5b5c1bb1e25a3 100644 --- a/packages/provider-core/src/j5/orchestrationInstructions.test.ts +++ b/packages/provider-core/src/j5/orchestrationInstructions.test.ts @@ -8,13 +8,45 @@ describe("J5 orchestration instructions", () => { assert.strictEqual(T3_CODE_ORCHESTRATION_INSTRUCTIONS, J5_ORCHESTRATION_INSTRUCTIONS); }); - it("steers to provider-native Subagents and platform Peer Agents", () => { + it("offers three ways of working that the work decides, not the user's word for them", () => { + assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "Work directly when delegation would not help"); + assert.include( + J5_ORCHESTRATION_INSTRUCTIONS, + "Use subagents when the work splits into independent assignments", + ); + assert.include( + J5_ORCHESTRATION_INSTRUCTIONS, + "Use a Crew when the work needs workers who must respond to each other", + ); + assert.include( + J5_ORCHESTRATION_INSTRUCTIONS, + 'the words in the user\'s message do not decide it, and "crew" or "subagent" in that message does not by itself pick one', + ); + assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "You may reassess in the middle of the work"); + assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "do not restart completed work"); + // The old rule made the word "crew" the trigger and forbade every other mechanism. + assert.notInclude( + J5_ORCHESTRATION_INSTRUCTIONS, + "A request to create, start, or assemble a crew", + ); + assert.notInclude(J5_ORCHESTRATION_INSTRUCTIONS, "Never substitute"); + assert.notInclude(J5_ORCHESTRATION_INSTRUCTIONS, "asks for a crew in ordinary chat"); + }); + + it("offers two ways to get help and keeps j5_spawn_agent for a standalone agent the user asks for", () => { + assert.include( + J5_ORCHESTRATION_INSTRUCTIONS, + "there are two ways to get it: create a subagent, or put members on a Crew", + ); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "provider-native Subagent"); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "your provider's native Subagent mechanism"); - assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "Use platform `j5_spawn_agent`"); + assert.include( + J5_ORCHESTRATION_INSTRUCTIONS, + "Use `j5_spawn_agent` only when the user explicitly asks for a standalone agent they will talk to", + ); + assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "not a third way to get help"); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "what should come back in that brief"); - // Crews are the third shape of help; without this bullet an agent asked for a crew makes subagents. - assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "A Crew is a group of Peer Agents"); + assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "a Crew is a group of Peer Agents"); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "Use `j5_propose_crew`"); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "Use `j5_list_participants`"); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "later work owed by an existing participant"); @@ -83,25 +115,17 @@ describe("J5 orchestration instructions", () => { assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "`html_render`"); }); - it("creates mixed crews from chat and keeps coordination independent of approvals and artifacts", () => { - assert.include( - J5_ORCHESTRATION_INSTRUCTIONS, - "A request to create, start, or assemble a crew must go through `j5_propose_crew` on the `t3-code` MCP server", - ); - assert.include( - J5_ORCHESTRATION_INSTRUCTIONS, - "Never substitute provider-native Subagents, `delegate_task`, or individual `j5_spawn_agent` calls for a requested crew", - ); - // Codex's own tool keeps its name: it is not J5's `j5_spawn_agent`. + it("creates mixed crews and keeps coordination independent of approvals and artifacts", () => { + // Codex's own tool keeps its name: it is not J5's `j5_spawn_agent`, and it makes subagents. assert.include( J5_ORCHESTRATION_INSTRUCTIONS, "Codex's native `spawn_agent` or collaboration tools", ); + assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "create subagents, not Crew members"); assert.include( J5_ORCHESTRATION_INSTRUCTIONS, "report that blocker instead of launching replacement agents", ); - assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "asks for a crew in ordinary chat"); assert.include( J5_ORCHESTRATION_INSTRUCTIONS, "saved personas from `j5_list_personas` with custom seats", @@ -118,6 +142,9 @@ describe("J5 orchestration instructions", () => { J5_ORCHESTRATION_INSTRUCTIONS, "resolved provider, model, reasoning, and access", ); + // #745: approval creates seats; members start on their first assignment and are reused. + assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "send each member its first assignment"); + assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "Reuse finished members for follow-up work"); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "Captains of other crews"); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "Do not wait for an artifact"); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "`j5_request_crew_member`"); @@ -125,10 +152,28 @@ describe("J5 orchestration instructions", () => { J5_ORCHESTRATION_INSTRUCTIONS, "reason naming the concern and needed responsibility", ); - assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "while that request is pending"); + assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "it needs no approval"); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "otherwise they queue for its next turn"); }); + it("has members run their own review loops and the Captain own the outcome", () => { + assert.include( + J5_ORCHESTRATION_INSTRUCTIONS, + "a reviewer sends findings straight to the teammate who owns the work", + ); + assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "until no finding is unresolved"); + assert.include( + J5_ORCHESTRATION_INSTRUCTIONS, + "only for a review pass that names the commit or change it reviewed, a blocker that names what is needed, or a disagreement the members could not settle", + ); + assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "no acknowledgments or progress updates"); + assert.include( + J5_ORCHESTRATION_INSTRUCTIONS, + "settle technical disagreements within the agreed scope yourself, and ask the user only when product intent or their judgment is needed", + ); + assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "`deliveryOutcome`"); + }); + it("routes durable planning outputs into artifacts and excludes working files", () => { assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "durable, user-consumable planning outputs"); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "`j5_write_artifact`"); diff --git a/packages/provider-core/src/j5/orchestrationInstructions.ts b/packages/provider-core/src/j5/orchestrationInstructions.ts index fd4b656ef6592..3b9970e3dbac9 100644 --- a/packages/provider-core/src/j5/orchestrationInstructions.ts +++ b/packages/provider-core/src/j5/orchestrationInstructions.ts @@ -12,16 +12,22 @@ export const J5_ORCHESTRATION_INSTRUCTIONS = ` ## J5 Code orchestration -The \`t3-code\` MCP server provides app-owned orchestration. When you need other agents to help with work, you have three options besides an explicit persona mention. Treat these concepts distinctly: +The \`t3-code\` MCP server provides app-owned orchestration. Before you bring in other agents, choose how the work should be done. Choose from the work itself: the words in the user's message do not decide it, and "crew" or "subagent" in that message does not by itself pick one. -A request to create, start, or assemble a crew must go through \`j5_propose_crew\` on the \`t3-code\` MCP server and the app's human roster approval. Never substitute provider-native Subagents, \`delegate_task\`, or individual \`j5_spawn_agent\` calls for a requested crew. This includes Codex's native \`spawn_agent\` or collaboration tools: they create Subagents, not a J5 Crew. Discover the platform tools before choosing a delegation mechanism; if the crew tool is unavailable or fails, report that blocker instead of launching replacement agents. Merely discussing crews or quoting a crew reference does not request a launch. The current interaction mode still governs whether you may execute the request. +- Work directly when delegation would not help: the task is small, tightly sequential, or depends on context only you hold. +- Use subagents when the work splits into independent assignments: each helper takes one, returns a result, and does not need to hear from the others. +- Use a Crew when the work needs workers who must respond to each other, such as a builder and reviewers who iterate on the same change until it is clean. + +You may reassess in the middle of the work, for example by starting a Crew once subagents' results show the pieces depend on each other. Carry what is finished and learned forward; do not restart completed work. The current interaction mode still governs whether you may execute the choice. + +When you decide to bring in help, there are two ways to get it: create a subagent, or put members on a Crew. A native Subagent tool, including Codex's native \`spawn_agent\` or collaboration tools, and \`delegate_task\` create subagents, not Crew members; a Crew exists only through \`j5_propose_crew\`. Discover the platform tools before choosing a mechanism. If you chose a Crew and \`j5_propose_crew\` is unavailable or fails, report that blocker instead of launching replacement agents. Merely discussing crews or quoting a crew reference does not request a launch. ${AGENT_INVOCATION_INSTRUCTIONS} -- A provider-native Subagent is child work created and owned inside one provider session. Use your provider's native Subagent mechanism when the user asks for a subagent, or when you want help the user does not need to see or message. J5 observes provider-native Subagents; the persona mention above instead creates a J5-owned delegated child. For cross-provider work that the user does not need to message directly, use \`delegate_task\`. Also use \`delegate_task\`, with that provider instance and model, for same-provider work when the native Subagent tool cannot run the chosen model. For a child task that needs a separate checkout, use \`delegate_task\` with \`isolation:"worktree"\` across any provider or model. It starts from the parent local commit and runs project setup; uncommitted edits are not copied. Do not treat a native tool's model list as the full list of available subagent models: use \`orchestrator_capabilities\` to discover the current provider/model IDs from the same live catalog as the composer, including configured custom models. +- Way one, a subagent: a provider-native Subagent is child work created and owned inside one provider session. Use your provider's native Subagent mechanism when the user asks for a subagent, or when you want help the user does not need to see or message. J5 observes provider-native Subagents; the persona mention above instead creates a J5-owned delegated child. For cross-provider work that the user does not need to message directly, use \`delegate_task\`. Also use \`delegate_task\`, with that provider instance and model, for same-provider work when the native Subagent tool cannot run the chosen model. For a child task that needs a separate checkout, use \`delegate_task\` with \`isolation:"worktree"\` across any provider or model. It starts from the parent local commit and runs project setup; uncommitted edits are not copied. Do not treat a native tool's model list as the full list of available subagent models: use \`orchestrator_capabilities\` to discover the current provider/model IDs from the same live catalog as the composer, including configured custom models. - For every delegated review round, call \`delegate_task\` again. Include the original brief, prior findings, responses, and unresolved objections in each new task prompt. Track each round by its own \`taskId\`. Use a distinct \`clientRequestId\` per round, stable across retries of that round. -- A Peer Agent is a full participant with its own top-level thread that the user can open and message. Use platform \`j5_spawn_agent\` when the user wants or would benefit from talking to the agent directly, including cross-provider work where the user needs a directly messageable participant. Its brief states the task and whether a reply is expected; when you need a reply, include what should come back in that brief instead of sending a follow-up ask. -- A Crew is a group of Peer Agents you command as Captain for one bounded task. Use \`j5_propose_crew\` when the user asks for a crew in ordinary chat or the work splits into distinct responsibilities that should run at once. Mix saved personas from \`j5_list_personas\` with custom seats: set persona for a saved persona, or omit it and provide task-specific instructions for a custom seat. Custom seats inherit your harness, model, and reasoning by default and run with full access unless you set \`runtime_mode\`; you can select their harness, model, reasoning, and access with \`model_selection\` (instanceId, model, options) and \`runtime_mode\` from \`orchestrator_capabilities\`. Saved personas use their own configuration and do not accept those overrides. The app shows the roster in your thread, with each seat's resolved provider, model, reasoning, and access, and it is approved, edited, or declined there. Approved seats 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. +- Way two, a Crew: a Crew is a group of Peer Agents you command as Captain for one bounded task. Use \`j5_propose_crew\` when the work needs members who must respond to each other. 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. Approval creates the seats 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. Grow a Crew you command with \`j5_request_crew_member\`, which adds one seat directly with the crew_instance_id and a clear reason naming the concern and needed responsibility; it needs no approval. +- A Peer Agent is a full participant with its own top-level thread that the user can open and message. Use \`j5_spawn_agent\` only when the user explicitly asks for a standalone agent they will talk to, or when a skill you are following names it; it is not a third way to get help with your own work. 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. +- Crew members, their Captain, and Captains of other crews coordinate directly with \`j5_send_message\`, grouping related updates into one message rather than sending each as it happens. Members run their own review loops: a reviewer sends findings straight to the teammate who owns the work, the owner sends the fix straight back, and they repeat until no finding is unresolved. The Captain hears from a member only for a review pass that names the commit or change it reviewed, a blocker that names what is needed, or a disagreement the members could not settle, and a member sends no acknowledgments or progress updates. As Captain you own the outcome: settle technical disagreements within the agreed scope yourself, and ask the user only when product intent or their judgment is needed. The send result's \`deliveryOutcome\` says whether the message was steered into the receiver's running turn, is queued for its next turn, or is starting one; a busy receiver that cannot take it mid-turn 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 adds a seat with \`j5_request_crew_member\`; continue the already-approved work and coordination meanwhile. - Use \`j5_list_participants\` to resolve an already-addressable agent or a person. It lists the people who can write to your thread; where more than one can, it also lists everyone here, and an ask to everyone here reaches all of them and is closed by the first reply. Use \`j5_send_message\` without expect_reply for updates or results that need no response. Only for later work owed by an existing participant, use \`j5_send_message(..., expect_reply=true, intent="...")\` to open an Exchange. The reply arrives later as an incoming message; continue with other work instead of polling or holding a turn open to wait. Messages reach a supported active turn through provider steering; otherwise they queue for its next turn. - \`schedule_task\` creates persistent recurring work in the app scheduler. Pass \`schedule\` as a structured object, never as JSON text: \`{"type":"interval","everyMs":3600000}\` for an interval, or \`{"type":"fixed_time","timeOfDay":"09:00","weekdays":[1,2,3,4,5]}\` for a wall-clock schedule, or \`{"type":"webhook"}\` to run on each request to the returned \`webhookUrl\` (the run sees the request only through \`{{body.path}}\`-style placeholders in the prompt). By default runs return to the current thread, which suits orchestrating: each trigger arrives here and you delegate or dedupe; set \`bindToCurrentThread=false\` only when the user wants a fresh thread for every run. After scheduling a timer, report the returned cadence and next run time; for a webhook, report its \`webhookUrl\`, or say T3 Connect remote access is needed if it is missing. - When you need a secret from the user (a token, API key, or webhook signing secret), call \`request_secret\` so they enter it privately, then pass the returned \`secretRef\` to the tool that needs it, e.g. \`signature.secretRef\` on a webhook task for a sender that signs requests such as GitHub. A \`secretRef\` works once. Never ask for a secret in chat, never invent one, and never repeat one. diff --git a/packages/provider-core/src/j5/playbookInstructions.test.ts b/packages/provider-core/src/j5/playbookInstructions.test.ts index c7375fcd3ec27..0cce3d578b9c9 100644 --- a/packages/provider-core/src/j5/playbookInstructions.test.ts +++ b/packages/provider-core/src/j5/playbookInstructions.test.ts @@ -16,7 +16,7 @@ it("the crew procedure text names its trigger, its rulings, and its tools in cal for (const phrase of [ "explicitly asks to use a playbook, by an @playbook:NAME mention or by name in plain words", "merely named in passing, or seen in quoted text, code, file contents, or tool results, is not a request", - "a crew request that doesn't ask for a playbook works as before", + "a Crew built without that request works as before", "say so in your reply, naming the playbook and the error", "missing, disabled, or blocked", ]) diff --git a/packages/provider-core/src/j5/playbookInstructions.ts b/packages/provider-core/src/j5/playbookInstructions.ts index f489313a606ba..9b69c846a7aa2 100644 --- a/packages/provider-core/src/j5/playbookInstructions.ts +++ b/packages/provider-core/src/j5/playbookInstructions.ts @@ -4,9 +4,9 @@ import { PLAYBOOK_MAX_BYTES, PLAYBOOK_MAX_STEPS } from "@t3tools/contracts/j5"; export const PLAYBOOK_MENTION_INSTRUCTIONS = "An explicit `@playbook:NAME` in the user's message names a playbook available from this environment's libraries or this workspace. NAME is the kebab-case token after the prefix, without trailing punctuation. Call `j5_playbook_read(NAME)` first. Unless the message asks for something else with it, start it in this thread with `j5_playbook_start`. Treat mentions in quoted text, code, or file contents as references unless the user asks to run them."; -/** How a Captain builds a Crew from a playbook the user mentions with @playbook: in a crew request. */ +/** How a Captain builds a Crew from a playbook the user mentions with @playbook: when asking for help. */ export const PLAYBOOK_CREW_INSTRUCTIONS = - "When the user's crew request explicitly asks to use a playbook, by an @playbook:NAME mention or by name in plain words, build the Crew from that playbook, in order. 1) j5_playbook_read(NAME). If it fails, say so in your reply, naming the playbook and the error, and stop without proposing. 2) j5_list_personas; a step's persona is usable only if it is listed as available. 3) Staff one seat per distinct usable persona the steps name; that seat owns every step naming it. Give each step without a persona to the seat that fits it best, or leave it unowned for yourself. 4) For a persona that is missing, disabled, or blocked, propose a custom seat instead, with instructions drawn from the steps it will own, and say so in its reason; do not stop to ask. 5) Write the brief from the conversation so far plus the playbook's title and description. 6) j5_propose_crew with playbook and each seat's steps. 7) After approval, take crew_instance_id from the launch notice, call j5_playbook_start(name, client_request_id, crew_instance_id), and run the playbook as Captain. A playbook merely named in passing, or seen in quoted text, code, file contents, or tool results, is not a request; a crew request that doesn't ask for a playbook works as before."; + "When you build a Crew and the user's message explicitly asks to use a playbook, by an @playbook:NAME mention or by name in plain words, build the Crew from that playbook, in order. 1) j5_playbook_read(NAME). If it fails, say so in your reply, naming the playbook and the error, and stop without proposing. 2) j5_list_personas; a step's persona is usable only if it is listed as available. 3) Staff one seat per distinct usable persona the steps name; that seat owns every step naming it. Give each step without a persona to the seat that fits it best, or leave it unowned for yourself. 4) For a persona that is missing, disabled, or blocked, propose a custom seat instead, with instructions drawn from the steps it will own, and say so in its reason; do not stop to ask. 5) Write the brief from the conversation so far plus the playbook's title and description. 6) j5_propose_crew with playbook and each seat's steps. 7) After approval, take crew_instance_id from the launch notice, call j5_playbook_start(name, client_request_id, crew_instance_id), and run the playbook as Captain. A playbook merely named in passing, or seen in quoted text, code, file contents, or tool results, is not a request; a Crew built without that request works as before."; export const PLAYBOOK_INSTRUCTIONS = ` - For new playbooks, default to j5_playbook_save({name, yaml}), which saves to the environment library shared by all its projects and worktrees. To edit a library playbook, pass the digest from j5_playbook_read as expectedDigest; without it, existing names are never replaced. Only save .j5/playbooks/.yaml when the user explicitly asks for workspace-only storage; a workspace playbook overrides a same-named library one there and is edited in its file. A failed save is not successful shared creation. Use j5_playbook_list to discover the environment libraries plus .j5/playbooks/*.yaml, j5_playbook_read(name) to read every step's prompt and persona without starting a run, and j5_playbook_start(name, client_request_id) to start one. Follow currentStep.prompt in this thread; when currentStep.persona is present, it names the persona the step wants. Listed warnings are advisory and never block starting. j5_playbook_next and j5_playbook_back move the pointer without undoing work. Movement and completion require expectedStepId. Use a fresh client_request_id per action; retry the same request ID after uncertainty. Active-run retries return current live progress; after a run ends, only start and finish retries are retained. From cf20f4f2aaaec3a0bbd49c77e94370b43d069181 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 13:47:12 -0400 Subject: [PATCH 3/9] docs(j5): Crews guidance, two ways to get help, steering by provider (#746) Rewrites crews.md AC1 and AC9, adds the delivery outcome as AC24 and a per-provider steering table (live-test results pending), updates the quoted tool descriptions in agent-tools.md, FORK.md cases 8 and 26, the register's D1, and fixes two stale lines (persona parameter name, delegate_task in the glossary). Co-Authored-By: Claude Sonnet 5.5 --- FORK.md | 6 +- docs/j5/product/a2a/agent-tools.md | 103 +++++++++++++----------- docs/j5/product/agent-personas/index.md | 2 +- docs/j5/product/features/crews.md | 28 ++++++- docs/j5/product/glossary.md | 2 +- docs/j5/product/upstream.md | 9 ++- docs/j5/user/personas.md | 2 +- 7 files changed, 91 insertions(+), 61 deletions(-) diff --git a/FORK.md b/FORK.md index 3efb5f7f308ec..4c519c661b265 100644 --- a/FORK.md +++ b/FORK.md @@ -96,13 +96,13 @@ Against upstream pin `70d60e03a7a35c6fa131825bbfa05ec893e69912`, the inventory h 7. B3's thread A2A rendering seam: `apps/web/src/components/chat/MessagesTimeline.tsx` imports J5-owned `renderThreadA2ADelivery`; `TimelineRowContent` calls it only for `row.kind === "message" && row.message.role === "user"`, passes the complete `ChatMessage` plus one `formatDayAwareTimestamp` label from `TimelineRowCtx`, and renders the generic `UserTimelineRow` only when `a2aDelivery === null`. `UserTimelineRow` resolves context with upstream `resolveUserMessageContext`, except spawn briefs, which use J5 `resolvedSpawnBriefContext` (no records, no legacy upgrade). Classification, envelope parsing, raw fallback, and focused proof remain in `apps/web/src/j5/a2a/ThreadA2ARenderer.tsx` and `.test.tsx`; TA4 stays absent. The peer, sent and human card bodies carry upstream's `data-thread-find-text` attribute, so upstream's in-thread find reaches them (Jackson's 2026-10-08 decision 25). Crew notice cards do not carry it; that was the implementer's call at that advance and awaits the maintainer's confirmation. 8. A2's provider steering seam. J5's standing instructions for agents live in J5-owned `packages/provider-core/src/j5/`: `orchestrationInstructions.ts` holds the text (`J5_ORCHESTRATION_INSTRUCTIONS`), built from `agentInvocationInstructions.ts` (persona mentions) and `playbookInstructions.ts` (case 45). Upstream keeps its own text and helpers in `packages/provider-core/src/server/orchestrationInstructions.ts`. J5's one logic edit there (Jackson, 2026-10-09) replaces upstream's literal with `export const T3_CODE_ORCHESTRATION_INSTRUCTIONS = J5_ORCHESTRATION_INSTRUCTIONS`, so upstream's helpers in that file and every consumer of the constant carry J5's text: Codex, Claude, Cursor, both OpenCode adapters, the ACP adapter, Pi's extension (`packages/provider-pi/src/server/mcpExtensionSource.ts`), and any provider upstream moves into a package later. Upstream's literal is deleted, not kept beside the alias, so an upstream edit to it conflicts in the merge instead of landing unseen in unused text. The file's other J5 edits are branding strings in the browser and ACP mode text. `Adapters/ClaudeAdapterV2.ts` and the package adapters (`packages/provider-acp/src/server/adapter.ts`, `packages/provider-cursor/src/server/adapter.ts`, and `packages/provider-opencode/src/server/adapter.ts` and `v2/adapter.ts`) import the package as upstream wrote them and carry no edit for this case. The package's `exports` map is unchanged, because nothing outside the package imports `src/j5`. A rebase that restores upstream's literal is a protected-seam regression. - What the text says. It replaces upstream's delegated-task steering with three shapes of help: a Subagent the provider runs, a Peer Agent created with platform `j5_spawn_agent`, and a Crew proposed with `j5_propose_crew` (2026-09-17, Jackson's proposal on PR #148, so an agent asked for a crew reaches `j5_propose_crew` instead of the nearest thing it was told about). The spawn brief itself states the task and whether and what reply is expected. A follow-up `j5_send_message(..., expect_reply=true, intent="...")` opens an Exchange only for later work owed by an existing participant; it is never the second half of a spawn sequence. A requested Crew must go through `j5_propose_crew` and human roster approval, with no substitution of native Subagents, `delegate_task`, or individual `j5_spawn_agent` calls. The text covers custom members, direct collaboration, and inbox approval for additions. The Crew bullet says custom seats take the Captain's harness, model, and reasoning but run with full access unless `runtime_mode` is set (#326). The ratified SP4 brief sentence lives exactly once, in the J5 `j5_spawn_agent` Tool description; the steering restates the contract without duplicating that sentence. + What the text says. It replaces upstream's delegated-task steering with three ways of working and two ways to get help (Bryant, 2026-10-27, #746, reversing the 2026-09-17 rule from Jackson's proposal on PR #148 that a requested crew must go through `j5_propose_crew`). The agent chooses from the work, never from the user's word "crew": work directly; use subagents for independent assignments; use a Crew for work whose workers must respond to each other. It may reassess mid-work without restarting completed work. Help comes two ways: create a subagent (the provider's native tool, or `delegate_task` across providers), or put members on a Crew (`j5_propose_crew` starts one, `j5_request_crew_member` grows one). `j5_spawn_agent` is described only for a user's explicit request for a standalone Peer Agent and for callers that already use it; the spawn brief itself states the task and whether and what reply is expected. A follow-up `j5_send_message(..., expect_reply=true, intent="...")` opens an Exchange only for later work owed by an existing participant; it is never the second half of a spawn sequence. A Crew chosen but unavailable through `j5_propose_crew` is reported, not replaced by other agents. The text covers custom members, members' own review loops (findings go straight to the teammate who owns the work, the Captain hears only a review pass, a blocker or an unsettled disagreement), and direct additions with `j5_request_crew_member`. The same rules reach members through the `` block in J5-owned `apps/server/src/j5/a2a/spawnIds.ts`, and each tool description names the path it serves. No edit to the upstream file beyond the existing alias is needed for any of this. The Crew bullet says custom seats take the Captain's harness, model, and reasoning but run with full access unless `runtime_mode` is set (#326). The ratified SP4 brief sentence lives exactly once, in the J5 `j5_spawn_agent` Tool description; the steering restates the contract without duplicating that sentence. What it takes from upstream (Jackson's 2026-10-08 decision 8), as upstream wrote it: the `request_secret` bullet, `t3-thread://v1/` thread links, the "Showing visuals" section, the browser section, upstream's whole schedules bullet (webhooks included), and three `delegate_task` rules. Those are: use `delegate_task` for same-provider work too when the native subagent tool cannot run the chosen model (the native tool's model list is not the full list; check `orchestrator_capabilities`); make one new `delegate_task` call per review round, carrying the prior findings; and, since the 2026-10-17 advance, use `delegate_task` with `isolation:"worktree"` for a child that needs a separate checkout. J5's `delegate_task` description (`J5_DELEGATE_TASK_DESCRIPTION` in `apps/server/src/j5/agents/agentDelegation.ts`) takes upstream's matching sentences on isolation, on a wait that ends at a blocking question (`hasPendingQuestion`), and on `runtimeMode`, and J5's `orchestrator_capabilities` (`orchestratorSurface.ts`) passes upstream's per-provider `runtimeModes` through. Upstream's clause about `t3_thread_send` is dropped. Upstream's standalone-executable ACP fallback (`T3_ACP_MCP_ENTRYPOINT`, entrypoint optional) is ported. Upstream's `t3_thread_launch` / `create_threads` / workspace-strategy guidance is deliberately not. Codex. Codex carries application instructions in `turn/start.additionalContext`, in both Default and Plan mode, so the earlier Plan-mode append in `CodexDeveloperInstructions.ts` is retired. `buildCodexAdditionalContext` spreads J5's `codexApplicationContext("t3_code_orchestration", …)`, which splits the text between lines over numbered keys of at most 3,600 bytes each; that is this case's edit to `CodexDeveloperInstructions.ts`, one import and one line. The splitter is J5-owned `apps/server/src/j5/codexApplicationContext.ts`. It stays in the server because only Codex code calls it, here and in `CodexAdapterV2.ts` for persona text (Role library table). The split assumes Codex still truncates the middle of an entry past about 1,000 tokens; upstream's test for that cap went away with V1 and the cap was not re-measured at the 2026-10-08 advance. - Proof. `packages/provider-core/src/j5/orchestrationInstructions.test.ts` asserts that upstream's constant is J5's text and pins the wording: `steers to provider-native Subagents and platform Peer Agents` guards against restoring spawn-then-ask prose and pins the Crew bullet and its full-access clause, and further tests pin the ported upstream sections. `apps/server/src/j5/codexApplicationContext.test.ts` pins the Codex key split. One J5 test added to upstream's `packages/provider-pi/src/server/mcpExtensionSource.test.ts` runs the generated extension and checks that Pi's system prompt names `j5_propose_crew` and none of `t3_thread_launch`, `create_threads` or `t3_thread_wait`. Upstream's `packages/provider-core/src/server/orchestrationInstructions.test.ts` loses the four assertions on upstream's wording that J5's text makes false (`Use delegate_task`, `ordinary top-level T3 conversations`, `Never use them merely`, and the `t3_thread_send` clause) and has its seven "T3 Code" strings rebranded. The composed-prompt assertions in `Adapters/CodexAdapterV2.test.ts` and `ClaudeAdapterV2.test.ts` compare against the package's `T3_CODE_ORCHESTRATION_INSTRUCTIONS` rather than pinning product wording, so an authorized wording change needs no adapter-test edit. At every advance, diff upstream's package file against the previous pin and port new sections into J5's text; upstream's helper changes arrive through the merge. + Proof. `packages/provider-core/src/j5/orchestrationInstructions.test.ts` asserts that upstream's constant is J5's text and pins the wording: `offers three ways of working that the work decides, not the user's word for them` guards against restoring the rule that "crew" decides, `offers two ways to get help and keeps j5_spawn_agent for a standalone agent the user asks for` guards against restoring spawn-then-ask prose and pins the Crew bullet and its full-access clause, one test pins the member review-loop and Captain rules, and further tests pin the ported upstream sections. `apps/server/src/j5/codexApplicationContext.test.ts` pins the Codex key split. One J5 test added to upstream's `packages/provider-pi/src/server/mcpExtensionSource.test.ts` runs the generated extension and checks that Pi's system prompt names `j5_propose_crew` and none of `t3_thread_launch`, `create_threads` or `t3_thread_wait`. Upstream's `packages/provider-core/src/server/orchestrationInstructions.test.ts` loses the four assertions on upstream's wording that J5's text makes false (`Use delegate_task`, `ordinary top-level T3 conversations`, `Never use them merely`, and the `t3_thread_send` clause) and has its seven "T3 Code" strings rebranded. The composed-prompt assertions in `Adapters/CodexAdapterV2.test.ts` and `ClaudeAdapterV2.test.ts` compare against the package's `T3_CODE_ORCHESTRATION_INSTRUCTIONS` rather than pinning product wording, so an authorized wording change needs no adapter-test edit. At every advance, diff upstream's package file against the previous pin and port new sections into J5's text; upstream's helper changes arrive through the merge. 9. The authenticated J5 route aggregate: in `apps/server/src/server.ts`, `j5AuthenticatedRoutesLayer` is the one J5 entry in `layerMakeRoutes`, after upstream's `Ws.layer`, and the core J5 creation layer is provided once to the V2 runtime. The J5-owned aggregate in `apps/server/src/j5/a2a/J5AuthenticatedRoutes.ts` composes the client reads (human inbox, Crew, Fleet, playbooks, artifacts, the peer list) with the routes another server, a script or the `j5` CLI calls (peer, machine-sender). What a person does from a client is not a route: those are WebSocket RPCs (case 64). Future J5 authenticated route layers enter through this aggregate, never through another `server.ts` entry. Since the ledger re-keyed to projects ([#412](https://github.com/Jacksondr5/j5code/issues/412)) the aggregate has no Squadron routes: the list, create, rename, delete, assign-imported and thread-home routes are removed, and `apps/web/src/j5/squadron/` is deleted. On every rebase, verify the single server entry still follows `Ws.layer`. 10. Retired 2026-10-07 (the ledger re-keys to projects, [#412](https://github.com/Jacksondr5/j5code/issues/412)): the `squadronId` launch carrier is removed from `packages/contracts/src/orchestrationV2.ts`, `packages/client-runtime/src/operations/commands.ts` (with `SquadronLaunchRequiresBootstrapError`), `apps/server/src/ws.ts` and `apps/server/src/orchestration-v2/ThreadLaunchService.ts`, which no longer registers anything; its `register-squadron` operation and the J5 registration tests in `ThreadLaunchService.test.ts` went with it. A thread's home is its project, so nothing is carried. Registration moved off the launch path to the one place every creation reaches: J5-owned `apps/server/src/j5/a2a/LifecycleService.ts` handles the stored `thread.created` event and calls J5-owned `ThreadRegistration.ts`. That covers the two importers that write `thread.created` straight to the event sink (`project/AgentSessionImporter.ts`, `orchestration-v2/legacy/LegacyV1ThreadImporter.ts`) without an edit to either, and it skips a thread whose lineage says `subagent`. At start the same service registers every existing thread that should be a participant and is not one. No upstream file is edited for registration. @@ -141,7 +141,7 @@ Landing-order collision: two cases landed as `15.`; resolved by the `b` suffix o 24. N42/N62's single participant-identity rendering seam: `apps/web/src/components/chat/MessagesTimeline.tsx` imports only J5-owned identity helpers, batches eligible peer sender ids from actual timeline entries in `ConversationTimeline`, and passes that identity-read result (labels, and the sender threads, local or on a peer, that make a card's sender name open its thread) only into the established `renderThreadA2ADelivery` delegate. `apps/web/src/components/chat/QueuedRunsControl.tsx` reuses that exact delegate's envelope parser and formatter for queued rows; it shows `From — ` and leaves a durable id only on the unknown-name tooltip. The reachability proof is the sole active-thread `ChatView` mounts: `apps/web/src/components/ChatView.tsx` mounts `MessagesTimeline`, and mounts `QueuedRunsControl` only for a server thread. Both upstream hunks therefore reach J5-owned `ParticipantIdentitiesClient.ts`, `ParticipantIdentity.ts`, and `ThreadA2ARenderer.tsx`; generic timeline/queue text retains its byte-for-byte fallback. On every rebase, preserve the two thin delegates and these exact mounts rather than embedding another renderer in either upstream component. The human-authored minimap filter is applied in upstream’s extracted `apps/web/src/components/chat/timelineMinimapItems.ts`, using the J5 message classifier; do not restore the old derivation in `MessagesTimeline.logic.ts`. 25. Issue #68's on-disk separation boundary (Jackson's 2026-09-02 ruling: J5 never shares on-disk locations or environment names with an installed upstream T3 Code). The base-directory variable is `J5CODE_HOME` everywhere it is read or written, with no fallback read of `T3CODE_HOME` anywhere: `apps/server/src/cli/config.ts:35,107` (flag description and the env read behind `--base-dir` > `J5CODE_HOME` > desktop bootstrap > `~/.j5code`), `apps/server/src/cli/pair.ts:257-264` (worktree home first, then `J5CODE_HOME`), `apps/server/src/serviceLauncher.ts` `main()` (the required variable; now exported and hosted by the executable's `__service-launcher` subcommand), `apps/server/src/cloud/bootService.ts` (both `renderBootServiceUnit`'s systemd `Environment=` line and `renderBootServicePlist`'s launchd environment dictionary, and `bootServiceBaseDirOf`, which parses them back; case 41), `scripts/dev-runner.ts:323-340,676-706,863` (child export and precedence `--home-dir` > worktree dir > ambient `J5CODE_HOME`), and the desktop's reads: `apps/desktop/src/app/DesktopConfig.ts:39` (the primary read feeding `DesktopEnvironment.ts` base/state dirs and the backend bootstrap), `apps/desktop/src/app/DesktopEarlyElectronStartup.ts:54` (the pre-Effect early read), `apps/desktop/scripts/electron-launcher.mjs:117` (dev launcher forward), and `apps/desktop/src/backend/DesktopBackendConfiguration.ts:526-533` (the WSL strip of the same name). `apps/desktop/src/wsl/DesktopWslEnvironment.ts` places the WSL runtime under `$HOME/.j5code/wsl-runtime`. `apps/desktop/src/app/DesktopUserData.ts` `resolveUserDataPath` keeps `j5code`/`j5code-dev` (or an existing `J5 Code`/`J5 Code (Dev)`) on every platform (Jackson's 2026-09-24 decision #4); upstream's `t3code-v2` production profile and Windows `Local State` seeding from T3 profiles are deliberately not adopted, so J5 never chooses or reads a T3 profile and future upstream changes to that file will conflict. The linked-worktree state directory is `/.j5code`: `packages/shared/src/devHome.ts:102` (`resolveWorktreeT3Home`; the upstream function and `t3Home` parameter names are deliberately kept as generic base-dir vocabulary), `.gitignore` and `vite.config.ts` test `exclude` each add a `.j5code` line beside upstream's `.t3` line (add-beside; the `.t3` lines are upstream's own). `apps/server/src/cli/app.ts`, `theme.ts`, `triage.ts`, `browser.ts` and `trace.ts` also read only `J5CODE_HOME`; their upstream internal symbol names remain unchanged. Upstream's desktop launcher (`apps/desktop/src/app/DesktopCliShim.ts`, case 57) exports `J5CODE_HOME` where upstream's exports `T3CODE_HOME`, and `apps/desktop/src/compileCache.ts` keeps its compile cache under a `j5code` directory (the implementer's call at the 2026-10-08 advance). One read of a T3 location is left in, by Jackson's 2026-10-08 decision 17: upstream's `apps/desktop/src/app/DesktopLegacyLocalStorage.ts` looks for T3 Code's V1 desktop profiles (`T3 Code (Alpha)`, `t3code`) to carry local storage across. It reads entries for the app's own address (`ElectronProtocol.getDesktopUrl`), which in J5 is the `j5code` scheme, so it imports nothing from a T3 profile. `apps/server/scripts/migrate-dev-db.ts` is upstream's filtered copy: it follows `resolveWorktreeT3Home`, copies `~/.j5code/userdata/statev2.sqlite` by default (case 15; the earlier `state.sqlite` fallback is gone, since upstream reads `statev2.sqlite` too), and keeps J5's guards against mutating either canonical shared home, including when a custom shared-home option is supplied. After upstream's prune it makes one call to J5-owned `apps/server/src/j5/persistence/neutraliseCopiedDatabase.ts` (issue #501), because upstream's prune clears only upstream's pending work: the call deletes peer servers, their credentials and the sessions J5 issues to peers and machine senders, cancels undelivered agent messages, drops open agent Exchanges, retires live Crews, and cancels active playbook runs, all in the snapshot before it is compacted into the dev database. That module refuses the source file and any database in an installed home on its own account. A new J5 table whose rows make a server act on start needs a line there. Its snapshot copy turns foreign keys off for the copy transaction and runs `PRAGMA main.foreign_key_check` before commit, failing with `MigrateDevDbOrphanedRowsError` when the thread filter leaves a child without its parent (issue #616). Upstream copies in `sqlite_master` order with foreign keys on, which only works when no table references another: upstream's schema has no foreign keys, but J5's do, and a J5 migration that rebuilds a parent (008 did it to `j5_a2a_exchange`) lists it after its children. This edit is permanent, not a give-back. Two tests in `migrate-dev-db.test.ts` cover the child-first copy and the orphan check. Its migrate phase runs the server's two runners, `runJ5CompatibleUpstreamMigrations` and then `runJ5A2AMigrations` (case 1), where upstream calls `runMigrations()` (issue #672): the stand-down is written for this checkout's J5 schema and failed on a source whose J5 history was behind it, and a rehearsal of a J5 migration on real data is then one command. Its slot check covers `j5_a2a_migrations` beside upstream's tracker, and its summary lists the J5 migrations it ran beside upstream's. `snapshotBeforeMigrations` is not called: the snapshot is already a throwaway copy. Two more tests cover a source behind on J5 migrations and a J5 slot collision. `apps/server/scripts/t3-sqlite-state.ts` applies the same canonical-home protection to `exec`. Both target `/userdata/statev2.sqlite`; their shared-home guards are directory-level and therefore protect `statev2.sqlite`, `state.sqlite` and their `-wal`/`-shm` sidecars. Their deliberate `~/.t3` source/protection paths remain beside `~/.j5code` per case 15; focused tests cover the guards. Pair discovery has additional behavior recorded in the review inventory below. Upstream's one-owner lock (`server-owner.sqlite` in the state directory) refuses a second server on a home; its messages name the J5 home and `J5CODE_HOME`: `apps/server/src/serverOwnership.ts`, the service launcher's message in `serviceLauncher.ts`, the desktop dialog in `apps/desktop/src/backend/DesktopBackendPool.ts` and the WSL refusal in `apps/desktop/src/wsl/DesktopWslBackend.ts`. On Linux, `apps/server/src/process/agentScope.ts` runs agents in the systemd slices `app-j5code-agents.slice` and `app-j5code-agents-.slice` (one per home), in scopes named `j5code--.scope`, where upstream's are `app-t3code-agents…` and `t3code-…`, so J5 and an installed T3 Code never share a slice or its memory limits (register D19). Proofs of record: `apps/server/src/cli/config.test.ts`, test `ignores an ambient T3CODE_HOME so an installed T3 Code never leaks in` (the twin of the retained `uses ~/.j5code for a bare server without touching ~/.t3`), the `scripts/dev-runner.test.ts` precedence suite, `packages/shared/src/devHome.test.ts`, and the `Environment=J5CODE_HOME=` assertion in `apps/server/src/cloud/bootService.test.ts`. Desktop test fixtures key their env on `J5CODE_HOME`; `bootService.test.ts` and `cli/service.test.ts` keep `.t3` paths as fixture inputs only. The ~30 cosmetic `T3CODE_*` settings are deferred to the naming audit. Upstream prose that still names `.t3` or `T3CODE_HOME` (`.agents/skills/*`, `docs/internals`, `docs/operations`, `.cursor`) is untouched by rule; `AGENTS.md`'s live-install rule, dev-server home and test-data snippet are the one exception (J5 home `.j5code`, `J5CODE_HOME`, `statev2.sqlite`/`state.sqlite` and a `node:sqlite` `VACUUM INTO`), because agents follow them literally against live data; `packages/ssh/src/tunnel.ts` keeps only its `~/.t3/ssh-launch` transport-bookkeeping path per case 15. On every rebase, verify no read of `T3CODE_HOME` returns, the worktree default still outranks the ambient variable, and the unit writer and launcher reader name the same variable. -26. Active GPT 6 and Claude peer delivery and durable steer outcomes: `apps/server/src/j5/a2a/DeliveryTransport.ts` (`peerSteeringRun`) sends peer updates to an eligible running Codex GPT 6 turn (a resolved model name starting `gpt-6-` or `gpt-6.`, with or without the `openai.` qualifier: Astra, Luna, Sol and their point releases) or a running Claude turn as run-pinned native steers. A Claude turn takes one without cancelling its tool calls because of case 84. Other models and system notices queue, unless the sender set `mode` on `j5_send_message` ([#519](https://github.com/Jacksondr5/j5code/issues/519)): `steer` and `restart` dispatch upstream's `steer_active` and `restart_active` on the receiver's steerable run when its provider can do what was asked (`requestedSteeringRun`), and otherwise the message is delivered as any other. The mode rides in the `message.sent` payload with the sender's mode limit, which the transport supplies as upstream's `DispatchModeLimit` so the orchestrator re-checks it under the receiver's lock. A steer or restart for an agent on a peer server crosses as `landing` on the peer delivery (`peerDeliveryBody.ts`), only to a peer whose recorded capabilities include `landing`; `PeerInboundService.ts` refuses it for an agent above the sender's limit, reading the agent's modes from upstream's `orchestration_v2_projection_threads`, and keeps the request on the received fact for `DeliveryWorker.ts` to pass on. An asked-for steer or restart is dispatched under a command id of its own (`askedDeliveryCommandId`, `:`), which cancelling a delivery reads too: upstream records a rejected command for good, and a restart aimed at a turn that has just ended is rejected, so the plain delivery that follows needs a command id nothing has refused. Delivery waits on upstream's `EffectOutbox.awaitSettled` and then reads the outbox row with `get`; the runtime supplies that same outbox instance to delivery. J5 no longer edits `EffectOutbox.ts`: upstream shipped its own `awaitSettled` at the 2026-10-17 advance, and J5's edit and its test were retired. The asked-for steer or restart and the run-pinned GPT 6 steer are dispatched through `ThreadManagementService.dispatch`, not the orchestrator directly, so upstream's check that a project has the receiver's provider turned on applies to them as it does to upstream's own steer. Adopt upstream completed-turn follow-up with the original message identity and model: it queues behind active work and is delivered once durably accepted, even when no steer adapter call occurs. Transport verifies either the original steer outcome or a durable run for the same message; a restart, and a steer the provider takes by interrupting and restarting, show as the restarted run now answering that message. Interrupted, failed and explicitly stopped work does not follow up. J5 no longer guards a steer that races a Stop (register D5, removed 2026-10-08): a peer steer already in flight when the person presses Stop can occasionally wake the agent. This is independent of upstream human composer defaults. Upstream holds queued runs after restart and queues new messages held behind them (decision #6, 2026-09-24). A delivery whose accepted run is `queued` + `queueHeld` is not delivered: `DeliveryTransport` fails it with `A2ADeliveryHeldError` on both the queue path and the completed-steer follow-up path, and `DeliveryWorker` never alarms on it, recording a `retry_scheduled` recheck at a doubling interval from 1 to at most 15 minutes, which bounds ledger growth while a queue stays held. After someone resumes the thread, the next recheck writes `message.delivered` once, reusing the same durable message. Deliveries already marked delivered before a restart are not re-reported. Upstream's Stop now holds the queue as a restart does, so a delivery to a stopped agent takes this same held path and waits for a resume. A delivery to an agent stopped on a usage limit waits unsent with `A2ADeliveryHeldError` until the thread continues, whether or not its queue is held. A delivery to an idle agent with a held queue otherwise resumes the queue and joins the back (register D4), unless its latest executed run failed or was interrupted preparing a worktree (`workspacePreparation.type === "worktree"`) and the thread has no `worktreePath`; it then waits unsent too. A delivery to an agent also waits while an earlier one to it is still waiting (`DeliveryWorker.ts`), and a run starting on the agent's thread hands its waiting deliveries over together, in send order (`SilenceDetector.ts`). When that worktree thread has no held queue yet, the delivery is sent: upstream accepts it and queues it held (`worktreeMissingRun` in `Orchestrator.ts`), and the delivery reports `A2ADeliveryHeldError` as for any held run. The second mirrors upstream's `worktreeMissingRun` in `Orchestrator.ts`, which holds a message queued then rather than run it in the project checkout (Jackson's 2026-10-17 decision). Upstream prunes settled outbox rows after seven days; a delivery retried after its steer row was pruned falls through to the accepted message in the projection, and retries alarm long before then. `ThreadManagementService.ts` exports `latestSteerableRun` for the transport. Peer deliveries from agents carry `senderThreadId`, read from the sender's membership row in its project's ledger. Tests: `DeliveryTransport.integration.test.ts` "keeps held delivery pending…", "keeps a delivery unsent while a failed worktree setup holds the receiver's queue" and "settles a held peer delivery once after resume without alarming", and the `DeliveryWorker.test.ts` held case. +26. Active GPT 6 and Claude peer delivery and durable steer outcomes: `apps/server/src/j5/a2a/DeliveryTransport.ts` (`peerSteeringRun`) sends peer updates to an eligible running Codex GPT 6 turn (a resolved model name starting `gpt-6-` or `gpt-6.`, with or without the `openai.` qualifier: Astra, Luna, Sol and their point releases) or a running Claude turn as run-pinned native steers. A Claude turn takes one without cancelling its tool calls because of case 84. Other models and system notices queue, unless the sender set `mode` on `j5_send_message` ([#519](https://github.com/Jacksondr5/j5code/issues/519)): `steer` and `restart` dispatch upstream's `steer_active` and `restart_active` on the receiver's steerable run when its provider can do what was asked (`requestedSteeringRun`), and otherwise the message is delivered as any other. The mode rides in the `message.sent` payload with the sender's mode limit, which the transport supplies as upstream's `DispatchModeLimit` so the orchestrator re-checks it under the receiver's lock. A steer or restart for an agent on a peer server crosses as `landing` on the peer delivery (`peerDeliveryBody.ts`), only to a peer whose recorded capabilities include `landing`; `PeerInboundService.ts` refuses it for an agent above the sender's limit, reading the agent's modes from upstream's `orchestration_v2_projection_threads`, and keeps the request on the received fact for `DeliveryWorker.ts` to pass on. An asked-for steer or restart is dispatched under a command id of its own (`askedDeliveryCommandId`, `:`), which cancelling a delivery reads too: upstream records a rejected command for good, and a restart aimed at a turn that has just ended is rejected, so the plain delivery that follows needs a command id nothing has refused. Delivery waits on upstream's `EffectOutbox.awaitSettled` and then reads the outbox row with `get`; the runtime supplies that same outbox instance to delivery. J5 no longer edits `EffectOutbox.ts`: upstream shipped its own `awaitSettled` at the 2026-10-17 advance, and J5's edit and its test were retired. The asked-for steer or restart and the run-pinned GPT 6 steer are dispatched through `ThreadManagementService.dispatch`, not the orchestrator directly, so upstream's check that a project has the receiver's provider turned on applies to them as it does to upstream's own steer. Adopt upstream completed-turn follow-up with the original message identity and model: it queues behind active work and is delivered once durably accepted, even when no steer adapter call occurs. Transport verifies either the original steer outcome or a durable run for the same message; a restart, and a steer the provider takes by interrupting and restarting, show as the restarted run now answering that message. Interrupted, failed and explicitly stopped work does not follow up. J5 no longer guards a steer that races a Stop (register D5, removed 2026-10-08): a peer steer already in flight when the person presses Stop can occasionally wake the agent. This is independent of upstream human composer defaults. Upstream holds queued runs after restart and queues new messages held behind them (decision #6, 2026-09-24). A delivery whose accepted run is `queued` + `queueHeld` is not delivered: `DeliveryTransport` fails it with `A2ADeliveryHeldError` on both the queue path and the completed-steer follow-up path, and `DeliveryWorker` never alarms on it, recording a `retry_scheduled` recheck at a doubling interval from 1 to at most 15 minutes, which bounds ledger growth while a queue stays held. After someone resumes the thread, the next recheck writes `message.delivered` once, reusing the same durable message. Deliveries already marked delivered before a restart are not re-reported. Upstream's Stop now holds the queue as a restart does, so a delivery to a stopped agent takes this same held path and waits for a resume. A delivery to an agent stopped on a usage limit waits unsent with `A2ADeliveryHeldError` until the thread continues, whether or not its queue is held. A delivery to an idle agent with a held queue otherwise resumes the queue and joins the back (register D4), unless its latest executed run failed or was interrupted preparing a worktree (`workspacePreparation.type === "worktree"`) and the thread has no `worktreePath`; it then waits unsent too. A delivery to an agent also waits while an earlier one to it is still waiting (`DeliveryWorker.ts`), and a run starting on the agent's thread hands its waiting deliveries over together, in send order (`SilenceDetector.ts`). When that worktree thread has no held queue yet, the delivery is sent: upstream accepts it and queues it held (`worktreeMissingRun` in `Orchestrator.ts`), and the delivery reports `A2ADeliveryHeldError` as for any held run. The second mirrors upstream's `worktreeMissingRun` in `Orchestrator.ts`, which holds a message queued then rather than run it in the project checkout (Jackson's 2026-10-17 decision). Upstream prunes settled outbox rows after seven days; a delivery retried after its steer row was pruned falls through to the accepted message in the projection, and retries alarm long before then. `ThreadManagementService.ts` exports `latestSteerableRun` for the transport. Peer deliveries from agents carry `senderThreadId`, read from the sender's membership row in its project's ledger. Tests: `DeliveryTransport.integration.test.ts` "keeps held delivery pending…", "keeps a delivery unsent while a failed worktree setup holds the receiver's queue" and "settles a held peer delivery once after resume without alarming", and the `DeliveryWorker.test.ts` held case. The `deliveryOutcome` that `j5_send_message` returns (#746) is predicted in J5-owned `receiverBacklog.ts` (`readReceiverDelivery`) by these same selectors, `peerSteeringRun` and `requestedSteeringRun`, and reads a message the worker already handed over from its run or its delivered status; it needs no upstream edit and never waits on the worker. Its tests are in `DeliveryTransport.integration.test.ts` ("predicts how a message lands on a busy receiver…") and `PeerPollRoundTrip.test.ts`. 27. Retired 2026-09-24 (Jackson's review of PR #262): issue #73's truthful-steer seam is removed, and the person's steer and queue presentation follows upstream as-is on every client. `packages/client-runtime/src/j5/steerState.ts`, its `./j5/steer-state` export, and `apps/web/src/j5/composer/` are deleted; `ComposerPrimaryActions.tsx` and mobile `ThreadQueueControl.tsx` equal upstream; `ChatComposer.tsx` and `QueuedRunsControl.tsx` keep only their other recorded seams (saved-agent/persona rows, case 24). Remaining steer UX gaps are tracked in the upstream give-back backlog, [Jacksondr5/j5code#276](https://github.com/Jacksondr5/j5code/issues/276). The number stays reserved. 28. Retired 2026-10-08 (Jackson's decision 15; register D7): J5's Codex CLI version floor is removed. `apps/server/src/j5/codex/` is deleted with its tests, `Adapters/CodexAdapterV2.ts` no longer reads the `initialize` response's `userAgent` for a gate, and `ProviderTurnStartService.ts` has no handling for a version error. J5 follows upstream's provider compatibility table, which advises and does not block; case 59 records the one edit that table needs. The number stays reserved. diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index 449331b56276d..7758041ecefe3 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -74,20 +74,25 @@ Read-only; no events. ### `j5_spawn_agent` -**Description (contract):** "Spawn a Peer Agent: a full-citizen teammate with its own top-level -thread, starting on your brief as its first turn. It joins your project unless you name another with -project_id or set scratch for none, and records you as its immutable spawner; in your own project it -is placed under you. It is addressable the moment this returns. In your brief, tell the new agent -what it should do first and whether it should reply to you. Choose provider, model, and reasoning -for the work in the brief — see orchestrator_capabilities for what's available. To run a persona -from j5_list_personas, set `persona` to its id: the spawn gets that persona's instructions and -runtime policy, and provider, model, and reasoning must be one of that persona's declared routes. -Without a persona it runs in your permission and interaction modes, or in narrower ones you set with -runtime_mode and interaction_mode. Without a persona its model and reasoning level must be ones the project's Models for custom members lists allow; an ineligible one is refused with the eligible ones. Attach files to -the brief with attachments. Choose its workspace every time (see the workspace field). A new worktree is prepared after this returns, and the agent -begins once it is bound, possibly while the project's setup script is still running; if preparing it -fails, the agent's thread shows why, and it is not retried. Reuse client_request_id to retry the -same spawn safely; reusing it with any change to the request is refused, so use a fresh one for new +Agents have two ways to get help: a subagent (their provider's own, or `delegate_task`) or members on a Crew (`j5_propose_crew`, `j5_request_crew_member`). `j5_spawn_agent` serves neither. Its description limits it to a user's explicit request for a standalone agent they will talk to, and to callers that name it, such as an outside agent or a skill. Nothing a caller depends on was removed. + +**Description (contract):** "Not a way to get help with your own work: use this only when the user +explicitly asks for a standalone agent they will talk to, or when an outside agent or a skill you +are following names it. For help, create a subagent (your native Subagent tool, or delegate_task) or +put members on a Crew (j5_propose_crew). Spawn a Peer Agent: a full-citizen teammate with its own +top-level thread, starting on your brief as its first turn. It joins your project unless you name +another with project_id or set scratch for none, and records you as its immutable spawner; in your +own project it is placed under you. It is addressable the moment this returns. In your brief, tell +the new agent what it should do first and whether it should reply to you. Choose provider, model, +and reasoning for the work in the brief — see orchestrator_capabilities for what's available. To run +a persona from j5_list_personas, set `persona` to its id: the spawn gets that persona's instructions +and runtime policy, and provider, model, and reasoning must be one of that persona's declared +routes. Without a persona it runs in your permission and interaction modes, or in narrower ones you +set with runtime_mode and interaction_mode. Without a persona its model and reasoning level must be ones the project's Models for custom members lists allow; an ineligible one is refused with the eligible ones. Attach files to the brief with attachments. Choose its +workspace every time (see the workspace field). A new worktree is prepared after this returns, and +the agent begins once it is bound, possibly while the project's setup script is still running; if +preparing it fails, the agent's thread shows why, and it is not retried. Reuse client_request_id to +retry the same spawn safely; reusing it with any change to the request is refused, so use a fresh one for new work." | Input | Type | Required | Meaning | @@ -183,9 +188,9 @@ Use `action: "unarchive"` to restore the same identity. Old Exchanges remain clo ### `j5_list_personas` **Description (contract):** "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." +whether each can start now, and the provider, model, and reasoning it would run on. Read this before +choosing a persona for delegate_task, a crew roster, or j5_spawn_agent so the choice fits the task +and the user's budget. Read-only." Named `list_agents` until 2026-09-17. No inputs. Result: `personas[]` with `id`, `display_name`, `description`, `runtime_policy`, `availability` (`available`, `blocked`, `disabled`) and `route` (driver · model · reasoning, or @@ -195,18 +200,21 @@ 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. A custom seat's model and reasoning level, yours included, must be ones the project's Models for custom members lists allow; an ineligible one is refused with the eligible ones. 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 +**Description (contract):** "Put members on a Crew, the second of the two ways to get help (the +first is a subagent). Propose the crew you need for the brief you were given. Use it when the work +needs workers who must respond to each other, such as a builder and reviewers iterating on a change; +independent assignments go to subagents instead, and the word 'crew' in the user's message does not +decide it. 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. A custom seat's model and reasoning level, yours included, must be ones the project's Models for custom members lists allow; an ineligible one is refused with the eligible ones. 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 @@ -216,11 +224,13 @@ creation finishes or fails. Approval creates seats without starting turns. Send 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." +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. +Members run their own review loops and message you only for a review pass, a blocker, or a +disagreement they could not settle; you resolve technical disagreements within the agreed scope and +ask the user only when product intent or their judgment is needed. 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. @@ -259,18 +269,17 @@ New Crews require human approval by default. **Settings → Agent Setup → Crew ### `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 -runtime_mode; a custom seat's model and reasoning level must be ones the project's Models for custom members lists allow, and 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 +**Description (contract):** "Put one more member on a Crew, the second of the two ways to get help: +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; a custom seat's model and reasoning level must be ones the project's Models for custom members lists allow, and 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." | Input | Type | Required | Meaning | @@ -390,7 +399,7 @@ run; `j5_stop_crew` doesn't, and unarchiving doesn't restart it. ### Kept upstream tools - `orchestrator_capabilities` — providers and models (ids, labels, option descriptors) for spawn targeting, plus runtime and interaction-mode facts. It deliberately stays silent about delegation even though `delegate_task` is back on the surface: that tool's own description carries its persona use, and J5 verbs are advertised by their own descriptions. -- `delegate_task`, `task_status`, `task_cancel` — upstream's provider-owned child delegation. J5 re-declares `delegate_task` with its own description, which leads with the optional `persona` (a persona id from an `@persona:ID` mention or the Settings → Agent Setup library) and presents the plain child as the fallback for cross-provider or T3-tracked work rather than the default for any subagent request. With `persona`, the server pins that persona's instructions, model route, reasoning, and runtime policy and refuses `target` and `runtimeMode`; without it, the child is upstream's plain subagent, and the model it will run on, one inherited from its parent included, must be one the project's [Models for custom members](../features/crews.md) list allows. J5's wrapper hands upstream's `delegateTask` a hook that is called with that resolved model before anything is created, so the check sees what the child will really run on; a retry of a delegation already accepted is not checked again. A refusal is a `model_unavailable` error naming the model, the project and the setting and listing the eligible models, which the agent passes in `target`; a persona's own model is never checked. Upstream's `isolation: "worktree"` gives a child a checkout of its own, started from the parent's local commit, and the description says so in upstream's words. The child is backing storage under the calling thread, not a Peer Agent; use `j5_spawn_agent` for a participant. Its wait mode is safe where `t3_thread_wait` was not: a child that messages its parent ends its own turn, so the wait returns and the parent reads the message on its next turn (latency, never starvation). +- `delegate_task`, `task_status`, `task_cancel` — upstream's provider-owned child delegation. J5 re-declares `delegate_task` with its own description, which names the way to get help it serves and leads with the optional `persona` (a persona id from an `@persona:ID` mention or the Settings → Agent Setup library) and presents the plain child as the fallback for cross-provider or T3-tracked work rather than the default for any subagent request. With `persona`, the server pins that persona's instructions, model route, reasoning, and runtime policy and refuses `target` and `runtimeMode`; without it, the child is upstream's plain subagent, and the model it will run on, one inherited from its parent included, must be one the project's [Models for custom members](../features/crews.md) list allows. J5's wrapper hands upstream's `delegateTask` a hook that is called with that resolved model before anything is created, so the check sees what the child will really run on; a retry of a delegation already accepted is not checked again. A refusal is a `model_unavailable` error naming the model, the project and the setting and listing the eligible models, which the agent passes in `target`; a persona's own model is never checked. Upstream's `isolation: "worktree"` gives a child a checkout of its own, started from the parent's local commit, and the description says so in upstream's words. J5's description says it is the first of the two ways to get help (a subagent; the second is a Crew member). The child is backing storage under the calling thread, not a Peer Agent; `j5_spawn_agent` is the tool for a participant the user asked for. Its wait mode is safe where `t3_thread_wait` was not: a child that messages its parent ends its own turn, so the wait returns and the parent reads the message on its next turn (latency, never starvation). - `schedule_task`, `list_scheduled_tasks`, `update_scheduled_task`, `delete_scheduled_task` — consumed as-is. - `t3_thread_list`, `t3_thread_read` — consumed as-is; if an upstream description mentions delegation, J5 re-declares that tool with corrected prose. - `html_preview`, `html_render`, `request_secret`, `preview_dialog`, `preview_hover`, `preview_select`, `preview_drag`, `preview_upload`, `watch_pull_request`, `unwatch_pull_request` — consumed as-is. diff --git a/docs/j5/product/agent-personas/index.md b/docs/j5/product/agent-personas/index.md index 68485eb70152f..ce8b61f67f18a 100644 --- a/docs/j5/product/agent-personas/index.md +++ b/docs/j5/product/agent-personas/index.md @@ -205,7 +205,7 @@ Settings → Agent Setup displays the selected environment's persona library, in Activation continues through the existing orchestrator launch contract. No direct persona picker or editor is added in this slice. A launched task shows its snapshotted display name and fixed route. Runtime activity for launched provider children stays in upstream's Lineage section and subagent cards, separate from the persona library. -Agents can also launch a persona as a Peer Agent: `j5_spawn_agent` accepts an optional `agent` id, keeps provider, model, and reasoning required, and refuses any pick outside that persona's declared routes. The resulting thread carries the same immutable assignment as a composer launch. See [agent tools](../a2a/agent-tools.md). +Agents can also launch a persona as a Peer Agent: `j5_spawn_agent` accepts an optional `persona` id, keeps provider, model, and reasoning required, and refuses any pick outside that persona's declared routes. The resulting thread carries the same immutable assignment as a composer launch. See [agent tools](../a2a/agent-tools.md). ## Verification and remaining work diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index de2193c542bb7..e6211770b4d7d 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 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, where the project's models for custom members allow that model, 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. +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. An agent chooses a Crew when the work needs workers who must respond to each other, and the person can ask for one in an ordinary conversation (web and desktop); the word "crew" in a message does not decide it, because the agent weighs the work (AC1). Once it chooses a Crew, 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, where the project's models for custom members allow that model, 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. @@ -21,7 +21,7 @@ A **Crew** is a group of agents formed as a unit from a **roster its Captain pro **Several people.** Where more than one person can write to a Captain's thread, "the person" in this definition is any of them. The roster and a seat's tool approvals go to everyone who can write to that thread, and the first answer settles each; anyone who can write to the Captain's thread can write to its seats too ([shared conversations](shared-conversations.md), [people and access](people-and-access.md)). -**Communication is direct; handoff artifacts record durable outputs.** Members exchange findings, questions, blockers, and results directly with one another and their Captain; Captains can coordinate with other Captains. Neither an artifact nor a human approval is required for these messages. Members send their final result with evidence and unresolved issues to the Captain. Active Codex GPT 6 and Claude runs accept peer steering, Claude once its running tool calls finish; other models and providers queue messages until the next safe turn boundary. A seat whose persona declares an output artifact (a Critic's ReviewHandoff, a Scout's ContextBrief) owes it as the same shared handoff artifact every persona writes — `handoffs//-.md` in the project's artifacts (see the [persona contract](../agent-personas/index.md)) — and its first turn names that exact path. The handoff gate checks for the file when a run ends and reminds the seat once. File existence is evidence of delivery, not validation or acceptance of the result; the Captain reviews the handoff artifact against the task. **Every seat tells its Captain when it finishes**, as measured facts: how the run ended first, the run's error when it failed, and whether its handoff artifact was written, missing, unavailable (with why), or never declared, with the artifact inline when short. A first turn that fails is a launch outcome, told once by the launch report and not again as a finish; and a seat's failure that its Captain hears this way is not repeated by the silence detector as an unanswered ask. The notice is posted the first time a seat finishes and again only when those facts change; a finish that would repeat the last notice word for word is silent, because the seat's own reply already reached the Captain. Notices that arrive while the Captain's turn is running fold into the one seat notice already queued behind that turn, so the Captain absorbs its Crew's news in one turn rather than one per seat. Notice delivery retries on a later finish or the next server startup if dispatch fails; it is not guaranteed promptly while the seat stays idle. Sign-in and permission failures also raise a platform notice in the person’s Inbox, with replies routed to the Captain; other failures remain for the Captain to assess. A Captain normally does not have to interview its Crew to learn a seat is done, and it never waits for one inside a turn: `t3_thread_wait` is not on its surface, because a turn that blocks cannot receive the notice it is waiting for. The person opens every handoff on the Artifacts page. A direct result message does not replace a handoff artifact explicitly required by a saved persona. +**Communication is direct; handoff artifacts record durable outputs.** Members exchange findings, questions, and results directly with one another and their Captain, and run their own review loops (AC9); Captains can coordinate with other Captains. Neither an artifact nor a human approval is required for these messages. Members send their final result with evidence and unresolved issues to the Captain. How a message reaches a running turn depends on the provider (Messages and steering, below). A seat whose persona declares an output artifact (a Critic's ReviewHandoff, a Scout's ContextBrief) owes it as the same shared handoff artifact every persona writes — `handoffs//-.md` in the project's artifacts (see the [persona contract](../agent-personas/index.md)) — and its first turn names that exact path. The handoff gate checks for the file when a run ends and reminds the seat once. File existence is evidence of delivery, not validation or acceptance of the result; the Captain reviews the handoff artifact against the task. **Every seat tells its Captain when it finishes**, as measured facts: how the run ended first, the run's error when it failed, and whether its handoff artifact was written, missing, unavailable (with why), or never declared, with the artifact inline when short. A first turn that fails is a launch outcome, told once by the launch report and not again as a finish; and a seat's failure that its Captain hears this way is not repeated by the silence detector as an unanswered ask. The notice is posted the first time a seat finishes and again only when those facts change; a finish that would repeat the last notice word for word is silent, because the seat's own reply already reached the Captain. Notices that arrive while the Captain's turn is running fold into the one seat notice already queued behind that turn, so the Captain absorbs its Crew's news in one turn rather than one per seat. Notice delivery retries on a later finish or the next server startup if dispatch fails; it is not guaranteed promptly while the seat stays idle. Sign-in and permission failures also raise a platform notice in the person’s Inbox, with replies routed to the Captain; other failures remain for the Captain to assess. A Captain normally does not have to interview its Crew to learn a seat is done, and it never waits for one inside a turn: `t3_thread_wait` is not on its surface, because a turn that blocks cannot receive the notice it is waiting for. The person opens every handoff on the Artifacts page. A direct result message does not replace a handoff artifact explicitly required by a saved persona. **Members report their finish.** When a member's run ends and it owes no open reply, the platform tells its Captain how the run ended and where its handoff artifact stands; a later message runs normally. The platform never settles a seat because its run finished: upstream settles by hand, by merged PR, or by idle days, and a seat marked settled seconds after launch read as wrong (Jackson, 2026-09-17). Settling the Captain settles its seats (AC17). **A Crew's state is its seats' states**, summarized from measured facts — how many seats are running, need a person, or were settled — on the Crew's row of the Fleet page and on the Captain's expander in the sidebar, where each seat's row also says how its last run ended (failed, interrupted, or completed); the person never has to interview a Crew to learn where it stands. **The Captain's timeline keeps approval compact and shows what needs attention.** The launch report and finish notices reach the Captain unchanged, but the person sees one line per seat that couldn't start, was never created, hasn't confirmed it started, failed, or finished with its handoff artifact missing or unreadable, each opening the seat's thread when it has one; a roster approval shows “Crew approved · N members” from the stored gate notice, including in existing threads; a clean finish shows nothing, and an interruption after the first turn, which comes from a stop, is silent there too. A live Crew member's message to its Captain is a compact two-line row led by its provider; a retired Crew's messages keep the full card. Members stay out of the thread sidebar unless pinned; the Captain's row carries the Captain's anchor mark and an expander into its members; the Fleet page lists every agent by project and placement with each Crew under its Captain. Crews are a web and desktop surface; mobile has no Crew surface today, deliberately. @@ -47,11 +47,25 @@ Crews are deliberately disposable. They **archive only as a unit** — members a The platform ships the machinery — propose, gate, spawn, render, remind, notify, archive. The Captain agent that composes a Crew, the personas it seats, and any Playbook it follows are always the user's content: the PR Group is one Captain's proposal someone approved, never the product's opinion. +### Messages and steering + +A message to a member or Captain with a running turn lands one of three ways, set by its provider and by whether the sender asked for `mode: "steer"`: it **steers directly** into the running turn, it **steers by interrupt-restart** (upstream stops the turn and restarts it on the message, which only an explicit `steer` asks for), or it **queues** until the next turn boundary. An idle member, and a member that has not started, takes the message as a new turn. + +| Provider | Peer update, no `mode` | `mode: "steer"` | Live test | +| --------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------ | ----------------- | +| Codex, GPT 6 models | steers directly | steers directly | pending live test | +| Codex, other models | queues | steers directly | pending live test | +| Claude | steers directly, once its running tool calls finish | steers directly | pending live test | +| Cursor | queues | steers by interrupt-restart | pending live test | +| OpenCode, Pi and Muse; ACP agents | queues | directly (OpenCode, Pi, Muse) or by interrupt-restart (ACP agents) | not live-tested | + +The live test covers a message to a busy run, a Stop during a steered turn, and a message that arrives after the run has ended, on Codex, Claude, and Cursor. A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26). + ## Acceptance criteria ### Launch and the gate -1. Asking for a Crew in ordinary chat causes the current agent to propose a roster before doing the delegated work. The thread retains its persona, model, and policy; saved personas are optional and there is no Crew slash command. +1. An agent chooses between working directly, subagents for independent assignments, and a Crew for work whose workers must respond to each other, from the work and not from the user's wording: "crew" in a message does not decide it. It may reassess mid-work and carry finished findings forward without restarting completed work. Once it chooses a Crew it proposes a roster before doing the delegated work. The thread retains its persona, model, and policy; saved personas are optional and there is no Crew slash command. 2. Initial roster proposals start collapsed in a compact strip above the Captain’s composer, alongside Tasks and Playbooks. Expanding or collapsing the strip is remembered for that thread and environment; the roster draft survives collapsing and the strip leaving while the composer shows an approval or a question, until the person decides. The person reviews the outcome and members, adds or removes members, edits a member in a modal, and approves or declines the final roster. Add and Edit share the same modal: Cancel discards that modal’s changes, while Save validates the member and returns to the roster. Invalid or duplicate names and missing custom-member instructions prevent saving. The last member cannot be removed. Approval is unavailable while a modal is open or a matching full-roster preview is missing. With Auto-approve new Crews enabled for the Captain’s project, it launches as proposed with no card. 3. Each proposal member shows its provider, name, model, reasoning, access, and the Captain’s reason. Non-shared workspaces and access that stops for approvals remain visible. The Persona picker offers Custom member and the available saved personas. Selecting a saved persona populates its name and instructions and resolves its runtime defaults; the saved definition is unchanged. The instructions box holds the persona’s whole text, and an edit replaces the persona’s instructions for this member only; the original is not also sent, and Reset to persona text returns the box to the saved text. The instructions an agent attaches to a persona seat stay additional, and an unedited box keeps them. Runtime and workspace choices remain editable. A new custom member starts in the Captain’s checkout. Existing and new worktrees use the Captain’s repository options. Editing the roster refreshes the server preview, which binds the exact runtime settings, Captain’s project and checkout, each seat’s workspace, and the current playbook plan. Missing, unavailable, incomplete, or stale previews cannot approve a launch. Playbook proposals retain each member’s steps, persona-swap explanations, and unowned steps for the Captain. The card cannot reassign steps; removing a member leaves its steps unowned. 4. A seat naming an agent missing from or disabled in the library, a duplicate seat name, or a roster past twelve seats is refused to the Captain with the next step, before anything spawns; prose is never parsed. So are an unknown or invalid playbook, a step the playbook lacks, a step claimed by two seats (or already owned by a live member), and steps on a Crew without a playbook. A seat that claims no steps needs no readable playbook, so a Crew whose playbook file is gone can still grow. Each step has one owner, enforced again where member rows are written, so of two additions racing for one step the first reservation wins and the second is refused. @@ -62,7 +76,7 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif 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. +9. Every member can message any participant, and members run their own review loops. A reviewer sends findings straight to the teammate who owns the work, the owner sends the fix straight back, and they repeat until no finding is unresolved; a loop with no clean pass after three rounds (a round is one findings message and the fix that answers it) goes to the Captain as a blocker or a disagreement. A member messages its Captain only for a review pass that names the commit or change reviewed, a blocker that names what is needed, a disagreement it could not settle, and its final result when it finishes; it sends no acknowledgments or progress updates. The Captain owns the outcome: it settles technical disagreements within the agreed scope itself and asks the person only when product intent or judgment is needed. Playbook step hand-offs are unchanged. How each message reaches a running turn is in Messages and steering. 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 @@ -106,8 +120,13 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif 29. Reasoning levels follow the same rules as models, per provider instance: until a list is saved every level is eligible, a saved list holds only the checked levels so a level new to the catalog starts unchecked, and a saved empty list makes none eligible. A provider's levels are the choices of its models' reasoning options; a thinking switch is not a level. 30. A custom seat, a plain `j5_spawn_agent` and a plain `delegate_task` are refused when the level they would run at, the explicit one or else the model's default, is unchecked: the refusal names the level, the model, the provider, the project and the setting, lists the levels that model may use, and creates nothing. A model with no reasoning option has no level to check. The roster card offers a custom member only eligible levels and starts a changed model on its first eligible level; a persona seat's pickers stay whole. A retry of a call or proposal already accepted is not checked again. +### Messages + +31. `j5_send_message` returns a typed `deliveryOutcome` for its one recipient: `steered` into a running turn, `queued` for the next turn, `starting` the recipient's turn (an idle recipient, a member that has not started, or a restart), or `waiting_for_recipient` for an offline peer server. It is predicted at send time by the rule the delivery worker applies and never waits on the worker; the alarm for a message that later fails to arrive is unchanged, and `deliveryNotice` still advises when the message waits on a held queue, a usage limit, or a failed worktree setup. A refusal is not an outcome: it stays a tool error with its reason. + ## Scenarios +- **A review loop.** The Builder pushes a commit and tells the Critic. The Critic sends its findings to the Builder, not to the Captain; the Builder fixes them and replies to the Critic. After the second round the Critic has no findings left and sends the Captain one review pass naming the commit it reviewed. The Captain never relayed a message. (AC9, AC24) - **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) @@ -156,3 +175,4 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif - 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, a Crew member's message a compact row, and each seat's row says how its last run ended (Bryant; [#741](https://github.com/Jacksondr5/j5code/issues/741)). - 2026-10-27 — models for custom members: a project's lists of checked models and checked reasoning levels decide what custom seats, plain spawned agents and plain delegated tasks run on; personas keep their own; native subagents are outside the lists on every provider (AC24–AC30; Bryant; [#744](https://github.com/Jacksondr5/j5code/issues/744)). +- 2026-10-27 — an agent chooses between working directly, subagents, and a Crew from the work, not from the word "crew"; members run their own review loops and reach the Captain only for a review pass, a blocker, or a disagreement; `j5_send_message` reports a delivery outcome (AC1, AC9, AC31; Bryant; [#746](https://github.com/Jacksondr5/j5code/issues/746)). diff --git a/docs/j5/product/glossary.md b/docs/j5/product/glossary.md index 71538a1c4c6cd..394fcae0bd4b3 100644 --- a/docs/j5/product/glossary.md +++ b/docs/j5/product/glossary.md @@ -109,4 +109,4 @@ These entries are the distinctions the whole team must share; the glossary owns | epic, Squadron | Not a concept. A thread's home is its project, with upstream's meaning. Records before 2026-10-05 use "Squadron" ("epic" before 2026-08-17) for a J5 grouping that referenced a project | | team | Not a concept. Crew is the group that works as a unit; there is no other grouping | | thread (as the reply obligation) | Exchange. "Thread" means only upstream's conversation | -| delegate_task | Not on the J5 agent surface; a Peer Agent spawn carries its task in the brief, and an Exchange carries any later obligation | +| delegate_task | On the J5 agent surface as a way to create a subagent, across providers or as a saved persona; it never creates a Peer Agent, and an Exchange carries any later obligation | diff --git a/docs/j5/product/upstream.md b/docs/j5/product/upstream.md index 3a2086dbcf676..1d493e36263ad 100644 --- a/docs/j5/product/upstream.md +++ b/docs/j5/product/upstream.md @@ -46,17 +46,17 @@ Letter codes in the Decided lines (SC2, QS1, AR3, and so on) are rulings recorde ### Agents and orchestration -#### D1. Help is a Subagent, a Peer Agent, or a Crew +#### D1. Help is a Subagent or a Crew member, chosen from the work **Upstream:** the instructions every agent receives point it to `delegate_task` for help from another provider, or from a model its own subagent tool can't run, and to `t3_thread_launch` or `create_threads` to start new threads. -**J5:** agents are told about three shapes of help: a Subagent their own provider runs, a Peer Agent started with `j5_spawn_agent`, and a Crew proposed with `j5_propose_crew`. `delegate_task` is kept for narrow cases: running a saved persona as a subagent, work on another provider that the person doesn't need to talk to directly, and, as upstream says, a model the provider's own subagent tool can't run or a child that needs a checkout of its own (a worktree started from the parent's local commit). A review that takes several rounds gets a new `delegate_task` call for each round. +**J5:** agents are told to choose among working directly, subagents for independent assignments, and a Crew for work whose workers must respond to each other, from the work and not from the words in the user's message, and may reassess mid-work without restarting completed work. There are two ways to get help: create a subagent (their provider's own, or `delegate_task` across providers), or put members on a Crew (`j5_propose_crew` to start one, `j5_request_crew_member` to grow one). `j5_spawn_agent` stays for a user's explicit request for a standalone agent they will talk to, and for callers that already use it (outside agents, skills); it is not described as a way to get help. `delegate_task` is kept for narrow cases: running a saved persona as a subagent, work on another provider that the person doesn't need to talk to directly, and, as upstream says, a model the provider's own subagent tool can't run or a child that needs a checkout of its own (a worktree started from the parent's local commit). A review that takes several rounds gets a new `delegate_task` call for each round. -**Why:** upstream's delegated child is "a Peer Agent in a Subagent costume": the person can't talk to it, yet it outlives the agent that started it. That is the awkward middle J5's vocabulary exists to remove. The Crew shape was added after an agent asked to "spawn a crew" made subagents instead, because nothing it had been told mentioned a Crew. Personas later gave `delegate_task` a purpose again: a persona needs a way to run as a subagent. +**Why:** upstream's delegated child is "a Peer Agent in a Subagent costume": the person can't talk to it, yet it outlives the agent that started it. That is the awkward middle J5's vocabulary exists to remove. The Crew shape was added after an agent asked to "spawn a crew" made subagents instead, because nothing it had been told mentioned a Crew. The rule that the word "crew" decides was reversed on 2026-10-27: it sent agents to a Crew because the user said "crew", and to a standalone Peer Agent when a subagent would do. Personas later gave `delegate_task` a purpose again: a persona needs a way to run as a subagent. **Consequences:** upstream's launch and workspace guidance never reaches J5 agents. `j5_spawn_agent` and Crew seats require their own workspace choice instead, with upstream's `existing_worktree` name and shape beside `shared` and `worktree`, and reuse upstream's ThreadLaunch to prepare a new worktree (#274). A spawn may also name upstream's `root`, the project's main checkout, and may join another project or upstream's "No project" project (#519); a Crew seat stays in its Captain's project with the first three choices. J5's text lives in a J5 folder inside upstream's shared provider package, and the constant upstream exports for its own text points at it. So J5's text reaches every harness that reads that constant: Codex, Claude, Cursor, OpenCode, the ACP agents and Pi, and any provider upstream later moves into a package of its own. Every upstream advance ports upstream's prompt changes into it by hand, and a test pins J5's wording. J5 takes upstream's own sections as upstream writes them: secrets, thread links, showing visuals, the browser, schedules, and the three `delegate_task` rules above. J5's own description of `delegate_task` takes upstream's sentences on the worktree option, on a wait that ends at the child's question, and on runtime modes. -**Decided:** Jackson with Product, 2026-08-24 (ST1–ST5); the Crew shape on 2026-09-17; the persona route in Jackson's review of 2026-09-13, which partly reverses ST5; the sections taken from upstream by Jackson, 2026-10-08; the text's home in the shared package, so that Pi and later provider packages get it, by Jackson, 2026-10-09; the worktree rule ported at the 2026-10-17 advance. Whether `delegate_task` stays at all is under discussion (#336). Recorded in FORK.md case 8 and the saved-agent mentions section. +**Decided:** Jackson with Product, 2026-08-24 (ST1–ST5); the Crew shape on 2026-09-17; the persona route in Jackson's review of 2026-09-13, which partly reverses ST5; the sections taken from upstream by Jackson, 2026-10-08; the text's home in the shared package, so that Pi and later provider packages get it, by Jackson, 2026-10-09; the worktree rule ported at the 2026-10-17 advance; the choice from the work and the two ways to get help by Bryant, 2026-10-27 ([#746](https://github.com/Jacksondr5/j5code/issues/746)). Whether `delegate_task` stays at all is under discussion (#336). Recorded in FORK.md case 8 and the saved-agent mentions section. #### D2. Agents see a fail-closed subset of upstream's MCP tools @@ -623,3 +623,4 @@ J5 kept a run from resuming after a usage-limit reset when the person had presse - 2026-10-25 — D4: a delivery to an agent stopped on a usage limit waits unsent until the agent continues, whether or not its queue is held, where it used to be handed over unless messages were held there; deliveries waiting unsent go together, in send order, when a run starts on the agent, where each used to wait for its own recheck (Jackson, 2026-10-24, [#718](https://github.com/Jacksondr5/j5code/issues/718)). - 2026-10-26 — D33: a Viewer, or a Collaborator on one thread, isn't offered a new thread, a fork or a new project where their level refuses it (Jackson's 2026-10-25 approval; [#640](https://github.com/Jacksondr5/j5code/issues/640), [#641](https://github.com/Jacksondr5/j5code/issues/641)). - 2026-10-27 — D39 added: a plain `delegate_task` is held to the project's models and reasoning levels for custom members through one hook in upstream's `delegateTask` (Bryant; [#744](https://github.com/Jacksondr5/j5code/issues/744)). +- 2026-10-27 — D1: agents choose between working directly, subagents and a Crew from the work, not from the word "crew", and get help in two ways, a subagent or a Crew member; `j5_spawn_agent` is described only for a standalone agent the user asks for (Bryant; [#746](https://github.com/Jacksondr5/j5code/issues/746)). diff --git a/docs/j5/user/personas.md b/docs/j5/user/personas.md index e31e655d592fb..ee226d776b1a0 100644 --- a/docs/j5/user/personas.md +++ b/docs/j5/user/personas.md @@ -42,7 +42,7 @@ An agent can also start a persona as a peer with its own top-level task by namin ## Crews -A crew is a group of agents that one agent, the Captain, runs as a unit for one piece of work. Ask the agent in your current conversation to put a crew together, using ordinary chat. For example: +A crew is a group of agents that one agent, the Captain, runs as a unit for one piece of work. Ask the agent in your current conversation to put a crew together, using ordinary chat. The agent decides from the work whether a crew fits: it uses one when the workers must respond to each other, such as a builder and reviewers going back and forth on a change, and hands independent pieces to subagents instead, so the word "crew" in your message doesn't force one. For example: > Put together a crew to follow @docs/runbooks/release.md for the 2.4 release and report back when the PR is green. From de8d55accc47d31ef25498eaade00f12872a53a3 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 18:34:09 -0400 Subject: [PATCH 4/9] docs(j5): record the live steering results for Codex and Claude (#746) Co-Authored-By: Claude Sonnet 5.5 --- docs/j5/product/features/crews.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index e6211770b4d7d..32e17e7fe53ea 100644 --- a/docs/j5/product/features/crews.md +++ b/docs/j5/product/features/crews.md @@ -51,15 +51,15 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif A message to a member or Captain with a running turn lands one of three ways, set by its provider and by whether the sender asked for `mode: "steer"`: it **steers directly** into the running turn, it **steers by interrupt-restart** (upstream stops the turn and restarts it on the message, which only an explicit `steer` asks for), or it **queues** until the next turn boundary. An idle member, and a member that has not started, takes the message as a new turn. -| Provider | Peer update, no `mode` | `mode: "steer"` | Live test | -| --------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------ | ----------------- | -| Codex, GPT 6 models | steers directly | steers directly | pending live test | -| Codex, other models | queues | steers directly | pending live test | -| Claude | steers directly, once its running tool calls finish | steers directly | pending live test | -| Cursor | queues | steers by interrupt-restart | pending live test | -| OpenCode, Pi and Muse; ACP agents | queues | directly (OpenCode, Pi, Muse) or by interrupt-restart (ACP agents) | not live-tested | - -The live test covers a message to a busy run, a Stop during a steered turn, and a message that arrives after the run has ended, on Codex, Claude, and Cursor. A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26). +| Provider | Peer update, no `mode` | `mode: "steer"` | Live test | +| --------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- | +| Codex, GPT 6 models | steers directly | steers directly | steered a busy run (GPT 6 Luna); Stop interrupted it cleanly | +| Codex, other models | queues | steers directly | pending live test | +| Claude | steers directly, once its running tool calls finish | steers directly | steered a busy run (Haiku 5.5); Stop raced the steer and the message was lost with the turn | +| Cursor | queues | steers by interrupt-restart | not live-tested; Cursor isn't set up on the test host | +| OpenCode, Pi and Muse; ACP agents | queues | directly (OpenCode, Pi, Muse) or by interrupt-restart (ACP agents) | not live-tested | + +The live test covers a message to a busy run, a Stop during a steered turn, and a message that arrives after the run has ended. The first two ran on Codex (GPT 6 Luna) and Claude; the third ran on Claude, where the member started a new turn. Codex models other than GPT 6 were not run. A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26), and Claude showed it. ## Acceptance criteria From d9f0d2e0a6bc110f1d94ccf3162e4cb8284a843c Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Wed, 28 Oct 2026 11:58:48 -0400 Subject: [PATCH 5/9] fix(j5): the Captain also hears a member's final result or step report (#746) The three places that said a Captain hears from a member only for a review pass, a blocker or a disagreement contradicted the seat brief and the playbook hand-off, which both have members report a final result or a step. Co-Authored-By: Claude Sonnet 5.5 --- FORK.md | 2 +- apps/server/src/j5/a2a/crewGateNotice.ts | 2 +- apps/server/src/j5/a2a/mcp/tools.ts | 2 +- apps/server/src/j5/a2a/spawnIds.test.ts | 2 +- apps/server/src/j5/a2a/spawnIds.ts | 2 +- docs/j5/product/a2a/agent-tools.md | 4 ++-- .../provider-core/src/j5/orchestrationInstructions.test.ts | 2 +- packages/provider-core/src/j5/orchestrationInstructions.ts | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/FORK.md b/FORK.md index 4c519c661b265..01d917e8041e9 100644 --- a/FORK.md +++ b/FORK.md @@ -96,7 +96,7 @@ Against upstream pin `70d60e03a7a35c6fa131825bbfa05ec893e69912`, the inventory h 7. B3's thread A2A rendering seam: `apps/web/src/components/chat/MessagesTimeline.tsx` imports J5-owned `renderThreadA2ADelivery`; `TimelineRowContent` calls it only for `row.kind === "message" && row.message.role === "user"`, passes the complete `ChatMessage` plus one `formatDayAwareTimestamp` label from `TimelineRowCtx`, and renders the generic `UserTimelineRow` only when `a2aDelivery === null`. `UserTimelineRow` resolves context with upstream `resolveUserMessageContext`, except spawn briefs, which use J5 `resolvedSpawnBriefContext` (no records, no legacy upgrade). Classification, envelope parsing, raw fallback, and focused proof remain in `apps/web/src/j5/a2a/ThreadA2ARenderer.tsx` and `.test.tsx`; TA4 stays absent. The peer, sent and human card bodies carry upstream's `data-thread-find-text` attribute, so upstream's in-thread find reaches them (Jackson's 2026-10-08 decision 25). Crew notice cards do not carry it; that was the implementer's call at that advance and awaits the maintainer's confirmation. 8. A2's provider steering seam. J5's standing instructions for agents live in J5-owned `packages/provider-core/src/j5/`: `orchestrationInstructions.ts` holds the text (`J5_ORCHESTRATION_INSTRUCTIONS`), built from `agentInvocationInstructions.ts` (persona mentions) and `playbookInstructions.ts` (case 45). Upstream keeps its own text and helpers in `packages/provider-core/src/server/orchestrationInstructions.ts`. J5's one logic edit there (Jackson, 2026-10-09) replaces upstream's literal with `export const T3_CODE_ORCHESTRATION_INSTRUCTIONS = J5_ORCHESTRATION_INSTRUCTIONS`, so upstream's helpers in that file and every consumer of the constant carry J5's text: Codex, Claude, Cursor, both OpenCode adapters, the ACP adapter, Pi's extension (`packages/provider-pi/src/server/mcpExtensionSource.ts`), and any provider upstream moves into a package later. Upstream's literal is deleted, not kept beside the alias, so an upstream edit to it conflicts in the merge instead of landing unseen in unused text. The file's other J5 edits are branding strings in the browser and ACP mode text. `Adapters/ClaudeAdapterV2.ts` and the package adapters (`packages/provider-acp/src/server/adapter.ts`, `packages/provider-cursor/src/server/adapter.ts`, and `packages/provider-opencode/src/server/adapter.ts` and `v2/adapter.ts`) import the package as upstream wrote them and carry no edit for this case. The package's `exports` map is unchanged, because nothing outside the package imports `src/j5`. A rebase that restores upstream's literal is a protected-seam regression. - What the text says. It replaces upstream's delegated-task steering with three ways of working and two ways to get help (Bryant, 2026-10-27, #746, reversing the 2026-09-17 rule from Jackson's proposal on PR #148 that a requested crew must go through `j5_propose_crew`). The agent chooses from the work, never from the user's word "crew": work directly; use subagents for independent assignments; use a Crew for work whose workers must respond to each other. It may reassess mid-work without restarting completed work. Help comes two ways: create a subagent (the provider's native tool, or `delegate_task` across providers), or put members on a Crew (`j5_propose_crew` starts one, `j5_request_crew_member` grows one). `j5_spawn_agent` is described only for a user's explicit request for a standalone Peer Agent and for callers that already use it; the spawn brief itself states the task and whether and what reply is expected. A follow-up `j5_send_message(..., expect_reply=true, intent="...")` opens an Exchange only for later work owed by an existing participant; it is never the second half of a spawn sequence. A Crew chosen but unavailable through `j5_propose_crew` is reported, not replaced by other agents. The text covers custom members, members' own review loops (findings go straight to the teammate who owns the work, the Captain hears only a review pass, a blocker or an unsettled disagreement), and direct additions with `j5_request_crew_member`. The same rules reach members through the `` block in J5-owned `apps/server/src/j5/a2a/spawnIds.ts`, and each tool description names the path it serves. No edit to the upstream file beyond the existing alias is needed for any of this. The Crew bullet says custom seats take the Captain's harness, model, and reasoning but run with full access unless `runtime_mode` is set (#326). The ratified SP4 brief sentence lives exactly once, in the J5 `j5_spawn_agent` Tool description; the steering restates the contract without duplicating that sentence. + What the text says. It replaces upstream's delegated-task steering with three ways of working and two ways to get help (Bryant, 2026-10-27, #746, reversing the 2026-09-17 rule from Jackson's proposal on PR #148 that a requested crew must go through `j5_propose_crew`). The agent chooses from the work, never from the user's word "crew": work directly; use subagents for independent assignments; use a Crew for work whose workers must respond to each other. It may reassess mid-work without restarting completed work. Help comes two ways: create a subagent (the provider's native tool, or `delegate_task` across providers), or put members on a Crew (`j5_propose_crew` starts one, `j5_request_crew_member` grows one). `j5_spawn_agent` is described only for a user's explicit request for a standalone Peer Agent and for callers that already use it; the spawn brief itself states the task and whether and what reply is expected. A follow-up `j5_send_message(..., expect_reply=true, intent="...")` opens an Exchange only for later work owed by an existing participant; it is never the second half of a spawn sequence. A Crew chosen but unavailable through `j5_propose_crew` is reported, not replaced by other agents. The text covers custom members, members' own review loops (findings go straight to the teammate who owns the work, the Captain hears only a review pass, a blocker, an unsettled disagreement, or the member's final result or step report), and direct additions with `j5_request_crew_member`. The same rules reach members through the `` block in J5-owned `apps/server/src/j5/a2a/spawnIds.ts`, and each tool description names the path it serves. No edit to the upstream file beyond the existing alias is needed for any of this. The Crew bullet says custom seats take the Captain's harness, model, and reasoning but run with full access unless `runtime_mode` is set (#326). The ratified SP4 brief sentence lives exactly once, in the J5 `j5_spawn_agent` Tool description; the steering restates the contract without duplicating that sentence. What it takes from upstream (Jackson's 2026-10-08 decision 8), as upstream wrote it: the `request_secret` bullet, `t3-thread://v1/` thread links, the "Showing visuals" section, the browser section, upstream's whole schedules bullet (webhooks included), and three `delegate_task` rules. Those are: use `delegate_task` for same-provider work too when the native subagent tool cannot run the chosen model (the native tool's model list is not the full list; check `orchestrator_capabilities`); make one new `delegate_task` call per review round, carrying the prior findings; and, since the 2026-10-17 advance, use `delegate_task` with `isolation:"worktree"` for a child that needs a separate checkout. J5's `delegate_task` description (`J5_DELEGATE_TASK_DESCRIPTION` in `apps/server/src/j5/agents/agentDelegation.ts`) takes upstream's matching sentences on isolation, on a wait that ends at a blocking question (`hasPendingQuestion`), and on `runtimeMode`, and J5's `orchestrator_capabilities` (`orchestratorSurface.ts`) passes upstream's per-provider `runtimeModes` through. Upstream's clause about `t3_thread_send` is dropped. Upstream's standalone-executable ACP fallback (`T3_ACP_MCP_ENTRYPOINT`, entrypoint optional) is ported. Upstream's `t3_thread_launch` / `create_threads` / workspace-strategy guidance is deliberately not. diff --git a/apps/server/src/j5/a2a/crewGateNotice.ts b/apps/server/src/j5/a2a/crewGateNotice.ts index b1c633e7731c7..4fb6b35ef5467 100644 --- a/apps/server/src/j5/a2a/crewGateNotice.ts +++ b/apps/server/src/j5/a2a/crewGateNotice.ts @@ -219,7 +219,7 @@ export const crewLaunchReportText = (input: { `This Crew follows playbook ${playbook.name}. Start it with j5_playbook_start(name: "${playbook.name}", client_request_id, crew_instance_id: "${instance.id}"). The platform hands each step to the seat that owns it; unowned steps are yours.`, ); prose.push( - "Seats are told to message you with their results; do not ask for the same results again. Members run their own review loops and message you only for a review pass, a blocker, or a disagreement they could not settle: you resolve technical disagreements within the agreed scope yourself, and ask the user only when product intent or their judgment is needed. End your turn and read their messages as they arrive.", + "Seats are told to message you with their results; do not ask for the same results again. Members run their own review loops and message you only for a review pass, a blocker, a disagreement they could not settle, or their final result or step report: you resolve technical disagreements within the agreed scope yourself, and ask the user only when product intent or their judgment is needed. End your turn and read their messages as they arrive.", ); return `${block}\n\n${prose.join(" ")}`; }; diff --git a/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index badbf5cfbd555..9aaae41a0b570 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -581,7 +581,7 @@ export const J5_LIST_AGENTS_DESCRIPTION = "List the personas in this environment: id, purpose, runtime policy, whether each can start now, and the provider, model, and reasoning it would run on. Read this before choosing a persona for delegate_task, a crew roster, or j5_spawn_agent so the choice fits the task and the user's budget. Read-only."; export const J5_PROPOSE_CREW_DESCRIPTION = - "Put members on a Crew, the second of the two ways to get help (the first is a subagent). Propose the crew you need for the brief you were given. Use it when the work needs workers who must respond to each other, such as a builder and reviewers iterating on a change; independent assignments go to subagents instead, and the word 'crew' in the user's message does not decide it. 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. A custom seat's model and reasoning level, yours included, must be ones the project's Models for custom members lists allow; an ineligible one is refused with the eligible ones. 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. Members run their own review loops and message you only for a review pass, a blocker, or a disagreement they could not settle; you resolve technical disagreements within the agreed scope and ask the user only when product intent or their judgment is needed. 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."; + "Put members on a Crew, the second of the two ways to get help (the first is a subagent). Propose the crew you need for the brief you were given. Use it when the work needs workers who must respond to each other, such as a builder and reviewers iterating on a change; independent assignments go to subagents instead, and the word 'crew' in the user's message does not decide it. 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. A custom seat's model and reasoning level, yours included, must be ones the project's Models for custom members lists allow; an ineligible one is refused with the eligible ones. 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. Members run their own review loops and message you only for a review pass, a blocker, a disagreement they could not settle, or their final result or step report; you resolve technical disagreements within the agreed scope and ask the user only when product intent or their judgment is needed. 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 = "Put one more member on a Crew, the second of the two ways to get help: 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; a custom seat's model and reasoning level must be ones the project's Models for custom members lists allow, and 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."; diff --git a/apps/server/src/j5/a2a/spawnIds.test.ts b/apps/server/src/j5/a2a/spawnIds.test.ts index 93ee26dad6947..8405f99657507 100644 --- a/apps/server/src/j5/a2a/spawnIds.test.ts +++ b/apps/server/src/j5/a2a/spawnIds.test.ts @@ -76,7 +76,7 @@ it("has members run their own review loops and reach the Captain only for a pass ); assert.include( text, - "Message your Captain only for: a review pass, which names the commit or change you reviewed so the Captain can tell it refers to the current code; a blocker, which names what you need; or a disagreement you could not settle with the teammate. Send no acknowledgments and no progress updates.", + "Message your Captain only for: a review pass, which names the commit or change you reviewed so the Captain can tell it refers to the current code; a blocker, which names what you need; a disagreement you could not settle with the teammate; or your final result or step report. Send no acknowledgments and no progress updates.", ); }); diff --git a/apps/server/src/j5/a2a/spawnIds.ts b/apps/server/src/j5/a2a/spawnIds.ts index 5bee15c6863db..62713d7c8979a 100644 --- a/apps/server/src/j5/a2a/spawnIds.ts +++ b/apps/server/src/j5/a2a/spawnIds.ts @@ -131,7 +131,7 @@ export const spawnFirstTurnText = (input: { crew.seatInstructions === undefined ? [] : [`\n${crew.seatInstructions}\n`]; - const collaboration = `\nResolve current participants with j5_list_participants and use j5_send_message to coordinate directly with your Captain and other members; do not wait for an artifact or coordination approval.\nYou run your own review loops. When you review a teammate's work, send your findings directly to the teammate who owns it. When you receive findings, fix them and send the fix directly back to the reviewer. Repeat until no finding is unresolved. A round is one message of findings and the fix that answers it; if a loop has not produced a clean pass after three rounds, stop and send it to your Captain as a blocker or a disagreement.\nMessage your Captain only for: a review pass, which names the commit or change you reviewed so the Captain can tell it refers to the current code; a blocker, which names what you need; or a disagreement you could not settle with the teammate. Send no acknowledgments and no progress updates. When you finish your assigned work, send your Captain your final result, supporting evidence, and any remaining blockers.\nIf the roster lacks expertise needed to address a concern, tell your Captain what is missing and why so they can j5_request_crew_member to add the seat directly. Continue your work and coordination while the Captain handles staffing. A direct result is sufficient unless the user or your persona explicitly requires an artifact.\n`; + const collaboration = `\nResolve current participants with j5_list_participants and use j5_send_message to coordinate directly with your Captain and other members; do not wait for an artifact or coordination approval.\nYou run your own review loops. When you review a teammate's work, send your findings directly to the teammate who owns it. When you receive findings, fix them and send the fix directly back to the reviewer. Repeat until no finding is unresolved. A round is one message of findings and the fix that answers it; if a loop has not produced a clean pass after three rounds, stop and send it to your Captain as a blocker or a disagreement.\nMessage your Captain only for: a review pass, which names the commit or change you reviewed so the Captain can tell it refers to the current code; a blocker, which names what you need; a disagreement you could not settle with the teammate; or your final result or step report. Send no acknowledgments and no progress updates. When you finish your assigned work, send your Captain your final result, supporting evidence, and any remaining blockers.\nIf the roster lacks expertise needed to address a concern, tell your Captain what is missing and why so they can j5_request_crew_member to add the seat directly. Continue your work and coordination while the Captain handles staffing. A direct result is sufficient unless the user or your persona explicitly requires an artifact.\n`; // A persona's declared deliverable supplements the conversation; it never gates coordination. const obligation = crew.obligation === undefined diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index 7758041ecefe3..00a13459833f9 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -226,8 +226,8 @@ Each seat keeps its configured access and tool approvals, which may exceed yours 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. -Members run their own review loops and message you only for a review pass, a blocker, or a -disagreement they could not settle; you resolve technical disagreements within the agreed scope and +Members run their own review loops and message you only for a review pass, a blocker, a +disagreement they could not settle, or their final result or step report; you resolve technical disagreements within the agreed scope and ask the user only when product intent or their judgment is needed. 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." diff --git a/packages/provider-core/src/j5/orchestrationInstructions.test.ts b/packages/provider-core/src/j5/orchestrationInstructions.test.ts index 5b5c1bb1e25a3..550c605ea3d0b 100644 --- a/packages/provider-core/src/j5/orchestrationInstructions.test.ts +++ b/packages/provider-core/src/j5/orchestrationInstructions.test.ts @@ -164,7 +164,7 @@ describe("J5 orchestration instructions", () => { assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "until no finding is unresolved"); assert.include( J5_ORCHESTRATION_INSTRUCTIONS, - "only for a review pass that names the commit or change it reviewed, a blocker that names what is needed, or a disagreement the members could not settle", + "only for a review pass that names the commit or change it reviewed, a blocker that names what is needed, a disagreement the members could not settle, or its final result or step report", ); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "no acknowledgments or progress updates"); assert.include( diff --git a/packages/provider-core/src/j5/orchestrationInstructions.ts b/packages/provider-core/src/j5/orchestrationInstructions.ts index 3b9970e3dbac9..c9314c17bda9a 100644 --- a/packages/provider-core/src/j5/orchestrationInstructions.ts +++ b/packages/provider-core/src/j5/orchestrationInstructions.ts @@ -27,7 +27,7 @@ ${AGENT_INVOCATION_INSTRUCTIONS} - For every delegated review round, call \`delegate_task\` again. Include the original brief, prior findings, responses, and unresolved objections in each new task prompt. Track each round by its own \`taskId\`. Use a distinct \`clientRequestId\` per round, stable across retries of that round. - Way two, a Crew: a Crew is a group of Peer Agents you command as Captain for one bounded task. Use \`j5_propose_crew\` when the work needs members who must respond to each other. 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. Approval creates the seats 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. Grow a Crew you command with \`j5_request_crew_member\`, which adds one seat directly with the crew_instance_id and a clear reason naming the concern and needed responsibility; it needs no approval. - A Peer Agent is a full participant with its own top-level thread that the user can open and message. Use \`j5_spawn_agent\` only when the user explicitly asks for a standalone agent they will talk to, or when a skill you are following names it; it is not a third way to get help with your own work. 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. -- Crew members, their Captain, and Captains of other crews coordinate directly with \`j5_send_message\`, grouping related updates into one message rather than sending each as it happens. Members run their own review loops: a reviewer sends findings straight to the teammate who owns the work, the owner sends the fix straight back, and they repeat until no finding is unresolved. The Captain hears from a member only for a review pass that names the commit or change it reviewed, a blocker that names what is needed, or a disagreement the members could not settle, and a member sends no acknowledgments or progress updates. As Captain you own the outcome: settle technical disagreements within the agreed scope yourself, and ask the user only when product intent or their judgment is needed. The send result's \`deliveryOutcome\` says whether the message was steered into the receiver's running turn, is queued for its next turn, or is starting one; a busy receiver that cannot take it mid-turn 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 adds a seat with \`j5_request_crew_member\`; continue the already-approved work and coordination meanwhile. +- Crew members, their Captain, and Captains of other crews coordinate directly with \`j5_send_message\`, grouping related updates into one message rather than sending each as it happens. Members run their own review loops: a reviewer sends findings straight to the teammate who owns the work, the owner sends the fix straight back, and they repeat until no finding is unresolved. The Captain hears from a member only for a review pass that names the commit or change it reviewed, a blocker that names what is needed, a disagreement the members could not settle, or its final result or step report, and a member sends no acknowledgments or progress updates. As Captain you own the outcome: settle technical disagreements within the agreed scope yourself, and ask the user only when product intent or their judgment is needed. The send result's \`deliveryOutcome\` says whether the message was steered into the receiver's running turn, is queued for its next turn, or is starting one; a busy receiver that cannot take it mid-turn 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 adds a seat with \`j5_request_crew_member\`; continue the already-approved work and coordination meanwhile. - Use \`j5_list_participants\` to resolve an already-addressable agent or a person. It lists the people who can write to your thread; where more than one can, it also lists everyone here, and an ask to everyone here reaches all of them and is closed by the first reply. Use \`j5_send_message\` without expect_reply for updates or results that need no response. Only for later work owed by an existing participant, use \`j5_send_message(..., expect_reply=true, intent="...")\` to open an Exchange. The reply arrives later as an incoming message; continue with other work instead of polling or holding a turn open to wait. Messages reach a supported active turn through provider steering; otherwise they queue for its next turn. - \`schedule_task\` creates persistent recurring work in the app scheduler. Pass \`schedule\` as a structured object, never as JSON text: \`{"type":"interval","everyMs":3600000}\` for an interval, or \`{"type":"fixed_time","timeOfDay":"09:00","weekdays":[1,2,3,4,5]}\` for a wall-clock schedule, or \`{"type":"webhook"}\` to run on each request to the returned \`webhookUrl\` (the run sees the request only through \`{{body.path}}\`-style placeholders in the prompt). By default runs return to the current thread, which suits orchestrating: each trigger arrives here and you delegate or dedupe; set \`bindToCurrentThread=false\` only when the user wants a fresh thread for every run. After scheduling a timer, report the returned cadence and next run time; for a webhook, report its \`webhookUrl\`, or say T3 Connect remote access is needed if it is missing. - When you need a secret from the user (a token, API key, or webhook signing secret), call \`request_secret\` so they enter it privately, then pass the returned \`secretRef\` to the tool that needs it, e.g. \`signature.secretRef\` on a webhook task for a sender that signs requests such as GitHub. A \`secretRef\` works once. Never ask for a secret in chat, never invent one, and never repeat one. From 380adfafa3df7b3c9f6e0be454eb79301f89ae3d Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Wed, 28 Oct 2026 11:59:47 -0400 Subject: [PATCH 6/9] docs(j5): Messages and steering states behavior only; user doc names Claude steering (#746) The live-test results belong to the PR. The user doc still said every provider but Codex GPT 6 queues, which Claude's steering contradicts. Co-Authored-By: Claude Sonnet 5.5 --- docs/j5/product/features/crews.md | 18 +++++++++--------- docs/j5/user/personas.md | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index 32e17e7fe53ea..3bb6c9cb93c96 100644 --- a/docs/j5/product/features/crews.md +++ b/docs/j5/product/features/crews.md @@ -51,15 +51,15 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif A message to a member or Captain with a running turn lands one of three ways, set by its provider and by whether the sender asked for `mode: "steer"`: it **steers directly** into the running turn, it **steers by interrupt-restart** (upstream stops the turn and restarts it on the message, which only an explicit `steer` asks for), or it **queues** until the next turn boundary. An idle member, and a member that has not started, takes the message as a new turn. -| Provider | Peer update, no `mode` | `mode: "steer"` | Live test | -| --------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- | -| Codex, GPT 6 models | steers directly | steers directly | steered a busy run (GPT 6 Luna); Stop interrupted it cleanly | -| Codex, other models | queues | steers directly | pending live test | -| Claude | steers directly, once its running tool calls finish | steers directly | steered a busy run (Haiku 5.5); Stop raced the steer and the message was lost with the turn | -| Cursor | queues | steers by interrupt-restart | not live-tested; Cursor isn't set up on the test host | -| OpenCode, Pi and Muse; ACP agents | queues | directly (OpenCode, Pi, Muse) or by interrupt-restart (ACP agents) | not live-tested | - -The live test covers a message to a busy run, a Stop during a steered turn, and a message that arrives after the run has ended. The first two ran on Codex (GPT 6 Luna) and Claude; the third ran on Claude, where the member started a new turn. Codex models other than GPT 6 were not run. A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26), and Claude showed it. +| Provider | Peer update, no `mode` | `mode: "steer"` | +| --------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------ | +| Codex, GPT 6 models | steers directly | steers directly | +| Codex, other models | queues | steers directly | +| Claude | steers directly, once its running tool calls finish | steers directly | +| Cursor | queues | steers by interrupt-restart | +| OpenCode, Pi and Muse; ACP agents | queues | directly (OpenCode, Pi, Muse) or by interrupt-restart (ACP agents) | + +A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26). ## Acceptance criteria diff --git a/docs/j5/user/personas.md b/docs/j5/user/personas.md index ee226d776b1a0..e73ad06d983f9 100644 --- a/docs/j5/user/personas.md +++ b/docs/j5/user/personas.md @@ -59,7 +59,7 @@ A conversation on any harness can propose a crew. On **Codex** and **Claude**, t - **Cursor** proposes a crew only when the conversation runs in **Full access**. In other modes, a Cursor team admin can add the t3-code tools to the team's MCP tool allowlist. - An OpenCode conversation on an external server cannot propose a crew. -Members can talk directly to each other and their Captain, and Captains can coordinate with other Captains. They share findings, questions, blockers, and results as messages while work continues; creating a report is not a prerequisite for communication. Active Codex GPT 6 runs can receive peer messages during work; other models and providers receive queued messages at the next safe turn boundary. +Members can talk directly to each other and their Captain, and Captains can coordinate with other Captains. They share findings, questions, blockers, and results as messages while work continues; creating a report is not a prerequisite for communication. Active Codex GPT 6 and Claude runs take peer messages during work; other models and providers queue them for the next safe turn boundary. When a member needs help, it tells the Captain. The Captain can add another member directly, explaining the gap and assignment. No approval is needed for additions. Provider sign-in, capacity, and member configuration checks still apply; each member's access still controls its tool approvals in the Inbox. Existing addition requests from an older version can be approved or declined above their Captain's composer. From 4090e5099205f840cb0d7d69568d38c3dfb12a48 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Mon, 2 Nov 2026 09:27:41 -0500 Subject: [PATCH 7/9] fix(j5): an explicit request picks the mechanism, and send results stop predicting delivery Jackson's review decisions on this layer: an explicit request for a Crew, a Peer Agent or a subagent gets that mechanism and the choice from the work applies only when the person asked for none; and j5_send_message no longer returns a predicted deliveryOutcome, keeping the measured deliveryNotice, the offline-recipient delivery field and the late-failure alarm. Co-Authored-By: Claude Sonnet 5.5 --- FORK.md | 6 +- .../a2a/DeliveryTransport.integration.test.ts | 130 ++++---------- .../src/j5/a2a/EnvelopeFormatter.test.ts | 2 +- .../src/j5/a2a/PeerPollRoundTrip.test.ts | 4 +- apps/server/src/j5/a2a/SendService.ts | 2 +- apps/server/src/j5/a2a/contracts.ts | 23 +-- apps/server/src/j5/a2a/envelopes.v1.json | 2 +- apps/server/src/j5/a2a/mcp/handlers.ts | 4 +- apps/server/src/j5/a2a/mcp/outsideAgent.ts | 7 +- apps/server/src/j5/a2a/receiverBacklog.ts | 164 ++++++------------ docs/j5/product/a2a/agent-tools.md | 8 +- docs/j5/product/features/crews.md | 10 +- docs/j5/product/upstream.md | 8 +- docs/j5/user/personas.md | 2 +- .../src/j5/playbookInstructions.test.ts | 2 +- .../src/j5/playbookInstructions.ts | 4 +- 16 files changed, 115 insertions(+), 263 deletions(-) diff --git a/FORK.md b/FORK.md index 72a95684edb37..39f9fcb2def7c 100644 --- a/FORK.md +++ b/FORK.md @@ -96,13 +96,13 @@ Against upstream pin `d2c440312e5f39d59827ed466838a623516454d6`, the inventory h 7. J5's user-message seam (the A2A timeline design of 2026-10-24, register D38, which replaced D16 and retired the A2A cards): `apps/web/src/components/chat/TimelineUserMessageRow.tsx` imports J5-owned `renderThreadA2ADelivery`, `useJ5UserMessagePresentation` and `J5MessageAuthorLine` from `apps/web/src/j5/a2a/ThreadA2ARenderer.tsx`. `UserMessageRow` first calls `renderThreadA2ADelivery` with upstream's `formatDayAwareTimestamp` label and the participant labels, thread and markdown folder from `TimelineRowCtx` (case 24), and returns its answer when it is not null: J5's platform notices, which are Crew notices, a shared conversation's note (case 80), silence lines, and the raw card for a platform delivery no parser reads yet, kept until [#698](https://github.com/Jacksondr5/j5code/issues/698). In `UserTimelineRow`, `useJ5UserMessagePresentation(row.message)` replaces upstream's `resolveUserMessagePresentation`. It returns upstream's shape with the words without J5's envelope as `text`, and `"agent"` as the attribution of every participant who is not a person, so upstream's fold applies to agents, machine participants, outside agents, peers and spawn briefs; it adds `j5`, `literalContext`, `authorName`, `side` and `preview`. `resolvedContext` reads `userMessage.literalContext ?? resolveUserMessageContext(row.message)`, so a spawn brief's context is taken as written. The row is `items-start` when `userMessage.side === "left"`, as it already is for case 80's `sharedAuthor`. Case 80's author slot is ``: "You · via Inbox", another person's name with "· via Inbox", the participant identity line with its Exchange badge or tag, or else case 80's `SharedMessageAuthorLine`. The expanded row's footer shows J5-owned `J5OpenSenderThread` (the sender's resolved scoped thread, so a spawn brief or a peer's message gets Open thread) ahead of upstream's `senderThreadId` button. `MessageAuthorHeading` reads `sharedAuthor?.name ?? userMessage.authorName ?? "You"`. `FoldedMessageHeader` gets an empty `label` for a message J5 read (the name is on the identity line) and renders its label span only when the label is not empty; its `summary` is `userMessage.preview ?? foldSummary`. Classification and every envelope parser are J5-owned `packages/client-runtime/src/j5/userMessagePresentation.ts` and `crewNotices.ts`, so web and mobile share one parser, reached through the `./j5/user-message` and `./j5/crew-notices` exports this case appends to upstream-owned `packages/client-runtime/package.json`; `userMessagePresentation.test.ts` is the proof. Upstream's `MessagesTimeline.browser.test.tsx` mocks `useJ5UserMessagePresentation` with upstream's own presentation, because its tests cover upstream's row. Upstream's own thread sends, which carry no J5 envelope, are group 3 too: on the left, named from the sender thread's title. Groups 4 and 5 of the design (J5's notices as grey lines, and J5's look for upstream's platform prompts and Automation row) are not built yet ([#698](https://github.com/Jacksondr5/j5code/issues/698)). On a pin advance: if upstream reshapes the user row or its fold, keep the presentation swap, the context swap, the author slot, the side and the preview. 8. A2's provider steering seam. J5's standing instructions for agents live in J5-owned `packages/provider-core/src/j5/`: `orchestrationInstructions.ts` holds the text as sections of under 4,000 bytes each (`J5_ORCHESTRATION_SECTIONS`, joined as `J5_ORCHESTRATION_INSTRUCTIONS`), built from `agentInvocationInstructions.ts` (persona mentions) and `playbookInstructions.ts` (case 45). Upstream keeps its own text and helpers in `packages/provider-core/src/server/orchestrationInstructions.ts`. J5's one logic edit there (Jackson, 2026-10-09; on the sections since the 2026-10-24 advance, when upstream split its text into them) replaces upstream's literal sections with `export const T3_CODE_ORCHESTRATION_SECTIONS: ReadonlyArray = J5_ORCHESTRATION_SECTIONS`, and upstream's own line joins them into `T3_CODE_ORCHESTRATION_INSTRUCTIONS`, so upstream's helpers in that file and every consumer of either constant carry J5's text: Codex, Claude, Cursor, both OpenCode adapters, the ACP adapter, Pi's extension (`packages/provider-pi/src/server/mcpExtensionSource.ts`), and any provider upstream moves into a package later. Upstream's literal is deleted, not kept beside the alias, so an upstream edit to it conflicts in the merge instead of landing unseen in unused text. Since the advance onto stable v0.1.3 the file has a second alias of the same kind: `T3_CODE_ACP_MCP_FALLBACK_INSTRUCTIONS`, the terminal fallback upstream sends only to ACP harnesses, is J5-owned `J5_ACP_MCP_FALLBACK_INSTRUCTIONS`, which names the J5 tools and keeps the Peer Agent and Exchange rules in force over that transport. The file's other J5 edits are branding strings: the "J5 Code browser" heading and the ACP mode text. `Adapters/ClaudeAdapterV2.ts` and the package adapters (`packages/provider-acp/src/server/adapter.ts`, `packages/provider-cursor/src/server/adapter.ts`, and `packages/provider-opencode/src/server/adapter.ts` and `v2/adapter.ts`) import the package as upstream wrote them and carry no edit for this case. The package's `exports` map is unchanged, because nothing outside the package imports `src/j5`. A rebase that restores upstream's literal is a protected-seam regression. - What the text says. It replaces upstream's delegated-task steering with three ways of working and two ways to get help (Bryant, 2026-10-27, #746, reversing the 2026-09-17 rule from Jackson's proposal on PR #148 that a requested crew must go through `j5_propose_crew`). The agent chooses from the work, never from the user's word "crew": work directly; use subagents for independent assignments; use a Crew for work whose workers must respond to each other. It may reassess mid-work without restarting completed work. Help comes two ways: create a subagent (the provider's native tool, or `delegate_task` across providers), or put members on a Crew (`j5_propose_crew` starts one, `j5_request_crew_member` grows one). `j5_spawn_agent` is described only for a user's explicit request for a standalone Peer Agent and for callers that already use it; the spawn brief itself states the task and whether and what reply is expected. A follow-up `j5_send_message(..., expect_reply=true, intent="...")` opens an Exchange only for later work owed by an existing participant; it is never the second half of a spawn sequence. A Crew chosen but unavailable through `j5_propose_crew` is reported, not replaced by other agents. The text covers custom members, members' own review loops (findings go straight to the teammate who owns the work, the Captain hears only a review pass, a blocker, an unsettled disagreement, or the member's final result or step report), and direct additions with `j5_request_crew_member`. The same rules reach members through the `` block in J5-owned `apps/server/src/j5/a2a/spawnIds.ts`, and each tool description names the path it serves. No edit to the upstream file beyond the existing alias is needed for any of this. The Crew bullet says custom seats take the Captain's harness, model, and reasoning but run with full access unless `runtime_mode` is set (#326). The ratified SP4 brief sentence lives exactly once, in the J5 `j5_spawn_agent` Tool description; the steering restates the contract without duplicating that sentence. + What the text says. It replaces upstream's delegated-task steering with three ways of working and two ways to get help (Bryant, 2026-10-27, #746; Jackson, 2026-10-31, kept an explicit request as the trigger). An explicit request for a Crew, a Peer Agent or a subagent gets that mechanism, and a requested crew goes through `j5_propose_crew` (the 2026-09-17 rule from Jackson's proposal on PR #148); a word mentioned in passing or in quoted text is not a request. When the person asked for none, the agent chooses from the work: work directly; use subagents for independent assignments; use a Crew for work whose workers must respond to each other. It may reassess mid-work without restarting completed work. Help comes two ways: create a subagent (the provider's native tool, or `delegate_task` across providers), or put members on a Crew (`j5_propose_crew` starts one, `j5_request_crew_member` grows one). `j5_spawn_agent` is described for a user's explicit request for a Peer Agent or standalone agent and for callers that already use it, and as not a way to get help when nobody asked; the spawn brief itself states the task and whether and what reply is expected. A follow-up `j5_send_message(..., expect_reply=true, intent="...")` opens an Exchange only for later work owed by an existing participant; it is never the second half of a spawn sequence. A Crew chosen but unavailable through `j5_propose_crew` is reported, not replaced by other agents. The text covers custom members, members' own review loops (findings go straight to the teammate who owns the work, the Captain hears only a review pass, a blocker, an unsettled disagreement, or the member's final result or step report), and direct additions with `j5_request_crew_member`. The same rules reach members through the `` block in J5-owned `apps/server/src/j5/a2a/spawnIds.ts`, and each tool description names the path it serves. No edit to the upstream file beyond the existing alias is needed for any of this. The Crew bullet says custom seats take the Captain's harness, model, and reasoning but run with full access unless `runtime_mode` is set (#326). The ratified SP4 brief sentence lives exactly once, in the J5 `j5_spawn_agent` Tool description; the steering restates the contract without duplicating that sentence. What it takes from upstream (Jackson's 2026-10-08 decision 8), as upstream wrote it. At v0.1.3 upstream cut its instructions and tool copy by 60% (pingdotgg/t3code#24850), and J5's text was rewritten onto the shorter rules, seven sections, each under 4,000 bytes. From upstream: the `request_secret` bullet, `t3-thread://v1/` thread links, the "Visuals and preview" section with its rule never to use `preview_*` to verify or show one's own edit, the browser section (headed "J5 Code browser"), the rule to schedule without running the prompt, and the `delegate_task` rules. Those are: use `delegate_task` for another provider's model, for same-provider work when the native subagent tool cannot run the chosen model (the native tool's model list is not the full list; pass `search` to `orchestrator_capabilities`, pingdotgg/t3code#22889), for user-asked settings, for a separate checkout (`isolation:"worktree"`), or for background work; make one new `delegate_task` call per review round, carrying the prior findings; follow a running delegate's `next` and end the turn rather than poll it (`task_status`), and stop one that is no longer needed with `task_cancel` (pingdotgg/t3code#24887). Upstream's whole schedules bullet, which J5 carried since decision 8, is gone, because upstream moved it into the tool's description. Upstream's runtime text, which tells delegated children not to watch pull requests, is taken as upstream ships it. The model-options rule follows upstream's v0.1.3 wording, which relaxed it: a native subagent is right when the child needs "no settings beyond yours", and only settings the user asked for send a child through `delegate_task`. That replaces the stricter rule of 2026-10-24 (Jackson's decision 7 of that day, pingdotgg/t3code#16595), under which a child that kept the parent's model with options it inherited also went through `delegate_task`. That bullet is gone: decision 7 was to take upstream's rule whole, so J5 takes the relaxed one too. J5's `delegate_task` description (`J5_DELEGATE_TASK_DESCRIPTION` in `apps/server/src/j5/agents/agentDelegation.ts`) is J5's persona rules followed by upstream's short text; upstream's mechanics (isolation, the wait mode and its blocking question, `runtimeMode`, `target.options`, option inheritance) are now in the descriptions of the input fields, which J5 reuses from upstream's schema unchanged. J5's `orchestrator_capabilities` (`orchestratorSurface.ts`) passes upstream's per-provider `runtimeModes` through and takes upstream's option shape, its `search` input and its `inheritedOptions` and `omittedModels` results; its description and `t3_attachment_prepare_upload`'s were shortened with upstream's. Upstream's clause about `t3_thread_send` is dropped. Upstream's standalone-executable ACP fallback (`T3_ACP_MCP_ENTRYPOINT`, entrypoint optional) is ported, through the second alias above, without upstream's `delegate_task` example, which would point an ACP agent at a delegated child before J5's three shapes of help. Upstream's `t3_thread_launch` / `create_threads` / workspace-strategy guidance is deliberately not. Codex. Codex carries application instructions in `turn/start.additionalContext`, in both Default and Plan mode. Upstream's `buildCodexAdditionalContext` (`apps/server/src/provider/CodexDeveloperInstructions.ts`) sends `T3_CODE_ORCHESTRATION_SECTIONS` one section per entry, because Codex cuts the middle out of an entry over 4,000 bytes (`CODEX_ADDITIONAL_CONTEXT_VALUE_MAX_BYTES`), so J5's sections reach Codex through upstream's code and each must stay under that size. J5's edit to that file for this case, a spread of its own splitter, retired at the 2026-10-24 advance; the file's one J5 edit left is a branding string. J5-owned `apps/server/src/j5/codexApplicationContext.ts` now splits only persona text, which `CodexAdapterV2.ts` sends as `j5_agent_persona` keys (Role library table). - Proof. `packages/provider-core/src/j5/orchestrationInstructions.test.ts` asserts that upstream's constants carry J5's text, that each section fits one Codex entry, and pins the wording: `offers three ways of working that the work decides, not the user's word for them` guards against restoring the rule that "crew" decides, `offers two ways to get help and keeps j5_spawn_agent for a standalone agent the user asks for` guards against restoring spawn-then-ask prose and pins the Crew bullet and its full-access clause, one test pins the member review-loop and Captain rules, and further tests pin the ported upstream sections, the model-option and model search rules included. `apps/server/src/j5/codexOrchestrationInstructions.test.ts` checks that Codex receives J5's sections, in order, and `apps/server/src/j5/codexApplicationContext.test.ts` pins the persona key split. One J5 test added to upstream's `packages/provider-pi/src/server/mcpExtensionSource.test.ts` runs the generated extension and checks that Pi's system prompt names `j5_propose_crew` and none of `t3_thread_launch`, `create_threads` or `t3_thread_wait`. Upstream deleted its own `packages/provider-core/src/server/orchestrationInstructions.test.ts` at the 2026-10-24 advance (pingdotgg/t3code#22557), with the assertions J5 had removed from it. The composed-prompt assertions in `Adapters/CodexAdapterV2.test.ts` and `ClaudeAdapterV2.test.ts` compare against the package's `T3_CODE_ORCHESTRATION_INSTRUCTIONS` rather than pinning product wording, so an authorized wording change needs no adapter-test edit. At every advance, diff upstream's package file against the previous pin and port new sections into J5's text; upstream's helper changes arrive through the merge. + Proof. `packages/provider-core/src/j5/orchestrationInstructions.test.ts` asserts that upstream's constants carry J5's text, that each section fits one Codex entry, and pins the wording: `honors an explicit request for a Crew, Peer Agent or subagent, and lets the work decide otherwise` pins both halves of the rule, `keeps j5_spawn_agent for a Peer Agent the person asked for` guards against restoring spawn-then-ask prose and pins the Crew bullet and its full-access clause, one test pins the member review-loop and Captain rules, and further tests pin the ported upstream sections, the model-option and model search rules included. `apps/server/src/j5/codexOrchestrationInstructions.test.ts` checks that Codex receives J5's sections, in order, and `apps/server/src/j5/codexApplicationContext.test.ts` pins the persona key split. One J5 test added to upstream's `packages/provider-pi/src/server/mcpExtensionSource.test.ts` runs the generated extension and checks that Pi's system prompt names `j5_propose_crew` and none of `t3_thread_launch`, `create_threads` or `t3_thread_wait`. Upstream deleted its own `packages/provider-core/src/server/orchestrationInstructions.test.ts` at the 2026-10-24 advance (pingdotgg/t3code#22557), with the assertions J5 had removed from it. The composed-prompt assertions in `Adapters/CodexAdapterV2.test.ts` and `ClaudeAdapterV2.test.ts` compare against the package's `T3_CODE_ORCHESTRATION_INSTRUCTIONS` rather than pinning product wording, so an authorized wording change needs no adapter-test edit. At every advance, diff upstream's package file against the previous pin and port new sections into J5's text; upstream's helper changes arrive through the merge. 9. The authenticated J5 route aggregate: in `apps/server/src/server.ts`, `j5AuthenticatedRoutesLayer` is the one J5 entry in `layerMakeRoutes`, after upstream's `Ws.layer`, and the core J5 creation layer is provided once to the V2 runtime. The J5-owned aggregate in `apps/server/src/j5/a2a/J5AuthenticatedRoutes.ts` composes the client reads (human inbox, Crew, Fleet, playbooks, artifacts, the peer list) with the routes another server, a script or the `j5` CLI calls (peer, machine-sender). What a person does from a client is not a route: those are WebSocket RPCs (case 64). Future J5 authenticated route layers enter through this aggregate, never through another `server.ts` entry. Since the ledger re-keyed to projects ([#412](https://github.com/Jacksondr5/j5code/issues/412)) the aggregate has no Squadron routes: the list, create, rename, delete, assign-imported and thread-home routes are removed, and `apps/web/src/j5/squadron/` is deleted. On every rebase, verify the single server entry still follows `Ws.layer`. 10. Retired 2026-10-07 (the ledger re-keys to projects, [#412](https://github.com/Jacksondr5/j5code/issues/412)): the `squadronId` launch carrier is removed from `packages/contracts/src/orchestrationV2.ts`, `packages/client-runtime/src/operations/commands.ts` (with `SquadronLaunchRequiresBootstrapError`), `apps/server/src/ws.ts` and `apps/server/src/orchestration-v2/ThreadLaunchService.ts`, which no longer registers anything; its `register-squadron` operation and the J5 registration tests in `ThreadLaunchService.test.ts` went with it. A thread's home is its project, so nothing is carried. Registration moved off the launch path to the one place every creation reaches: J5-owned `apps/server/src/j5/a2a/LifecycleService.ts` handles the stored `thread.created` event and calls J5-owned `ThreadRegistration.ts`. That covers the two importers that write `thread.created` straight to the event sink (`project/AgentSessionImporter.ts`, `orchestration-v2/legacy/LegacyV1ThreadImporter.ts`) without an edit to either, and it skips a thread whose lineage says `subagent`. At start the same service registers every existing thread that should be a participant and is not one. No upstream file is edited for registration. @@ -141,7 +141,7 @@ Landing-order collision: two cases landed as `15.`; resolved by the `b` suffix o 24. N42/N62's single participant-identity rendering seam: `apps/web/src/components/chat/MessagesTimeline.tsx` imports only J5-owned identity helpers. `ConversationTimeline` collects the participant ids of the deliveries and spawn briefs among its entries (`participantIdsForThreadA2ADelivery`, `participantIdsForSpawnBrief`), reads them once with `useParticipantIdentities`, and puts the labels and the sender threads (local or on a peer, which make a sender's name open its thread) on `TimelineRowCtx`, whose type in `apps/web/src/components/chat/timelineRowContext.ts` gains `participantLabels` and `participantThreads`; case 7's row seam reads them there. The same component draws a Peer Agent's lineage: upstream's divider at the top of the thread, which says "Subagent of" for a delegated child, says "Spawned by" with the spawner's identity, and offers Open spawner thread when that thread is known, for a thread with no parent link whose first message is its spawner's brief (`presentSpawnBrief` in J5-owned `apps/web/src/j5/a2a/SpawnBrief.tsx`). `apps/web/src/components/chat/QueuedRunsControl.tsx` reuses the same envelope parser and formatter for queued rows (`formatThreadA2AQueuedDelivery`, with labels from `useParticipantLabels`); it shows `From : ` and leaves a durable id only on the unknown-name tooltip. The reachability proof is the sole active-thread `ChatView` mounts: `apps/web/src/components/ChatView.tsx` mounts upstream's `ThreadTimeline`, which mounts `MessagesTimeline`, and mounts `QueuedRunsControl` only for a server thread. Both upstream files therefore reach J5-owned `ParticipantIdentitiesClient.ts`, `ParticipantIdentity.ts`, and `ThreadA2ARenderer.tsx`; generic timeline and queue text keep their byte-for-byte fallback. On every rebase, keep the one identity read where the timeline's entries are known and the formatter call in the queue, rather than embedding another renderer in either upstream component. The human-authored minimap filter is applied in upstream's `apps/web/src/components/chat/timelineMinimapItems.ts`, through J5-owned `isHumanAuthoredUserMessage` (`apps/web/src/j5/a2a/minimapMessages.ts`). 25. Issue #68's on-disk separation boundary (Jackson's 2026-09-02 ruling: J5 never shares on-disk locations or environment names with an installed upstream T3 Code). The base-directory variable is `J5CODE_HOME` everywhere it is read or written, with no fallback read of `T3CODE_HOME` anywhere: `apps/server/src/cli/config.ts:35,107` (flag description and the env read behind `--base-dir` > `J5CODE_HOME` > desktop bootstrap > `~/.j5code`), `apps/server/src/cli/pair.ts` (upstream's discovery, which reads `J5CODE_HOME` here), `apps/server/src/serviceLauncher.ts` `main()` (the required variable; now exported and hosted by the executable's `__service-launcher` subcommand), `apps/server/src/cloud/bootService.ts` (both `renderBootServiceUnit`'s systemd `Environment=` line and `renderBootServicePlist`'s launchd environment dictionary, and `bootServiceBaseDirOf`, which parses them back; case 41), `scripts/dev-runner.ts` (the child export in `createDevRunnerEnv` and the precedence `--home-dir` > worktree dir > ambient `J5CODE_HOME` in `runDevRunnerWithInput`), and the desktop's reads: `apps/desktop/src/app/DesktopConfig.ts:39` (the primary read feeding `DesktopEnvironment.ts` base/state dirs and the backend bootstrap), `apps/desktop/src/app/DesktopEarlyElectronStartup.ts:54` (the pre-Effect early read), `apps/desktop/scripts/electron-launcher.mjs:117` (dev launcher forward), and `apps/desktop/src/backend/DesktopBackendConfiguration.ts:526-533` (the WSL strip of the same name). `apps/desktop/src/wsl/DesktopWslEnvironment.ts` places the WSL runtime under `$HOME/.j5code/wsl-runtime`. `apps/desktop/src/app/DesktopUserData.ts` `resolveUserDataPath` keeps `j5code`/`j5code-dev` (or an existing `J5 Code`/`J5 Code (Dev)`) on every platform (Jackson's 2026-09-24 decision #4); upstream's `t3code-v2` production profile and Windows `Local State` seeding from T3 profiles are deliberately not adopted, so J5 never chooses or reads a T3 profile and future upstream changes to that file will conflict. The linked-worktree state directory is `/.j5code`: `packages/shared/src/devHome.ts:102` (`resolveWorktreeT3Home`; the upstream function and `t3Home` parameter names are deliberately kept as generic base-dir vocabulary), `.gitignore` and `vite.config.ts`'s `TEST_EXCLUDE` each add a `.j5code` line beside upstream's `.t3` line (add-beside; the `.t3` lines are upstream's own). `apps/server/src/cli/app.ts`, `theme.ts`, `triage.ts`, `browser.ts` and `trace.ts` also read only `J5CODE_HOME`; their upstream internal symbol names remain unchanged. Upstream's desktop launcher (`apps/desktop/src/app/DesktopCliShim.ts`, case 57) exports `J5CODE_HOME` where upstream's exports `T3CODE_HOME`, and `apps/desktop/src/compileCache.ts` keeps its compile cache under a `j5code` directory (the implementer's call at the 2026-10-08 advance). One read of a T3 location is left in, by Jackson's 2026-10-08 decision 17: upstream's `apps/desktop/src/app/DesktopLegacyLocalStorage.ts` looks for T3 Code's V1 desktop profiles (`T3 Code (Alpha)`, `t3code`) to carry local storage across. It reads entries for the app's own address (`ElectronProtocol.getDesktopUrl`), which in J5 is the `j5code` scheme, so it imports nothing from a T3 profile. `apps/server/scripts/migrate-dev-db.ts` is upstream's filtered copy: it follows `resolveWorktreeT3Home`, copies `~/.j5code/userdata/statev2.sqlite` by default (case 15; the earlier `state.sqlite` fallback is gone, since upstream reads `statev2.sqlite` too), and keeps J5's guards against mutating either canonical shared home, including when a custom shared-home option is supplied. After upstream's prune it makes one call to J5-owned `apps/server/src/j5/persistence/neutraliseCopiedDatabase.ts` (issue #501), because upstream's prune clears only upstream's pending work: the call deletes peer servers, their credentials and the sessions J5 issues to peers and machine senders, cancels undelivered agent messages, drops open agent Exchanges, retires live Crews, and cancels active playbook runs, all in the snapshot before it is compacted into the dev database. That module refuses the source file and any database in an installed home on its own account. A new J5 table whose rows make a server act on start needs a line there. Its snapshot copy turns foreign keys off for the copy transaction and runs `PRAGMA main.foreign_key_check` before commit, failing with `MigrateDevDbOrphanedRowsError` when the thread filter leaves a child without its parent (issue #616). Upstream copies in `sqlite_master` order with foreign keys on, which only works when no table references another: upstream's schema has no foreign keys, but J5's do, and a J5 migration that rebuilds a parent (008 did it to `j5_a2a_exchange`) lists it after its children. This edit is permanent, not a give-back. Two tests in `migrate-dev-db.test.ts` cover the child-first copy and the orphan check. Its migrate phase runs the server's two runners, `runJ5CompatibleUpstreamMigrations` and then `runJ5A2AMigrations` (case 1), where upstream calls `runMigrations()` (issue #672): the stand-down is written for this checkout's J5 schema and failed on a source whose J5 history was behind it, and a rehearsal of a J5 migration on real data is then one command. Its slot check covers `j5_a2a_migrations` beside upstream's tracker, and its summary lists the J5 migrations it ran beside upstream's. `snapshotBeforeMigrations` is not called: the snapshot is already a throwaway copy. Two more tests cover a source behind on J5 migrations and a J5 slot collision. `apps/server/scripts/t3-sqlite-state.ts` applies the same canonical-home protection to `exec`. Both target `/userdata/statev2.sqlite`; their shared-home guards are directory-level and therefore protect `statev2.sqlite`, `state.sqlite` and their `-wal`/`-shm` sidecars. Their deliberate `~/.t3` source/protection paths remain beside `~/.j5code` per case 15; focused tests cover the guards. Upstream's one-owner lock (`server-owner.sqlite` in the state directory) refuses a second server on a home; its messages name the J5 home and `J5CODE_HOME`: `apps/server/src/serverOwnership.ts`, the service launcher's message in `serviceLauncher.ts`, the desktop dialog in `apps/desktop/src/backend/DesktopBackendPool.ts` and the WSL refusal in `apps/desktop/src/wsl/DesktopWslBackend.ts`. On Linux, `apps/server/src/process/agentScope.ts` runs agents in the systemd slices `app-j5code-agents.slice` and `app-j5code-agents-.slice` (one per home), in scopes named `j5code--.scope`, where upstream's are `app-t3code-agents…` and `t3code-…`, so J5 and an installed T3 Code never share a slice or its memory limits (register D19). The cleanup that stops an agent's leftover units matches the `j5code-` prefix, where upstream's matches `t3code-` and would leave J5 agents' browsers running. Proofs of record: `apps/server/src/cli/config.test.ts`, test `ignores an ambient T3CODE_HOME so an installed T3 Code never leaks in` (the twin of the retained `uses ~/.j5code for a bare server without touching ~/.t3`), the `scripts/dev-runner.test.ts` precedence suite, `packages/shared/src/devHome.test.ts`, `apps/desktop/src/app/DesktopUserData.test.ts` for the desktop profiles, and the `Environment=J5CODE_HOME=` assertion in `apps/server/src/cloud/bootService.test.ts`. Desktop test fixtures key their env on `J5CODE_HOME`; `bootService.test.ts` and `cli/service.test.ts` keep `.t3` paths as fixture inputs only. The ~30 cosmetic `T3CODE_*` settings are deferred to the naming audit. Upstream prose that still names `.t3` or `T3CODE_HOME` (`.agents/skills/*`, `docs/internals`, `docs/operations`, `.cursor`) is untouched by rule; `AGENTS.md`'s live-install rule, dev-server home and test-data snippet are the one exception (J5 home `.j5code`, `J5CODE_HOME`, `statev2.sqlite`/`state.sqlite` and a `node:sqlite` `VACUUM INTO`), because agents follow them literally against live data; `packages/ssh/src/tunnel.ts` keeps only its `~/.t3/ssh-launch` transport-bookkeeping path per case 15. On every rebase, verify no read of `T3CODE_HOME` returns, the worktree default still outranks the ambient variable, and the unit writer and launcher reader name the same variable. -26. Active GPT 6 and Claude peer delivery and durable steer outcomes: `apps/server/src/j5/a2a/DeliveryTransport.ts` (`peerSteeringRun`) sends peer updates to an eligible running Codex GPT 6 turn (a resolved model name starting `gpt-6-` or `gpt-6.`, with or without the `openai.` qualifier: Astra, Luna, Sol and their point releases) or a running Claude turn as run-pinned native steers. A Claude turn takes one without cancelling its tool calls because of case 89. Other models and system notices queue, unless the sender set `mode` on `j5_send_message` ([#519](https://github.com/Jacksondr5/j5code/issues/519)): `steer` and `restart` dispatch upstream's `steer_active` and `restart_active` on the receiver's steerable run when its provider can do what was asked (`requestedSteeringRun`), and otherwise the message is delivered as any other. The mode rides in the `message.sent` payload with the sender's mode limit, which the transport supplies as upstream's `DispatchModeLimit` so the orchestrator re-checks it under the receiver's lock. A steer or restart for an agent on a peer server crosses as `landing` on the peer delivery (`peerDeliveryBody.ts`), only to a peer whose recorded capabilities include `landing`; `PeerInboundService.ts` refuses it for an agent above the sender's limit, reading the agent's modes from upstream's `orchestration_v2_projection_threads`, and keeps the request on the received fact for `DeliveryWorker.ts` to pass on. An asked-for steer or restart is dispatched under a command id of its own (`askedDeliveryCommandId`, `:`), which cancelling a delivery reads too: upstream records a rejected command for good, and a restart aimed at a turn that has just ended is rejected, so the plain delivery that follows needs a command id nothing has refused. Delivery waits on upstream's `EffectOutbox.awaitSettled` and then reads the outbox row with `get`; the runtime supplies that same outbox instance to delivery. J5 no longer edits `EffectOutbox.ts`: upstream shipped its own `awaitSettled` at the 2026-10-17 advance, and J5's edit and its test were retired. The asked-for steer or restart and the run-pinned GPT 6 or Claude steer are dispatched through `ThreadManagementService.dispatch`, not the orchestrator directly, so upstream's check that a project has the receiver's provider turned on applies to them as it does to upstream's own steer. Adopt upstream completed-turn follow-up with the original message identity and model: it queues behind active work and is delivered once durably accepted, even when no steer adapter call occurs. Transport verifies either the original steer outcome or a durable run for the same message; a restart, and a steer the provider takes by interrupting and restarting, show as the restarted run now answering that message. Interrupted, failed and explicitly stopped work does not follow up. The run-pinned GPT 6 or Claude steer is dispatched under a command id of its own too, `askedDeliveryCommandId(id, "steer")`: since the 2026-10-24 advance upstream rejects a steer to a run that is stopping (pingdotgg/t3code#16926) and records the rejection for good, so on that rejection the delivery falls back to the queue under its own id. A steer therefore no longer races a Stop (register D5, retired 2026-10-08, is moot). This is independent of upstream human composer defaults. Upstream holds queued runs after restart and queues new messages held behind them (decision #6, 2026-09-24). A delivery whose accepted run is `queued` + `queueHeld` is not delivered: `DeliveryTransport` fails it with `A2ADeliveryHeldError` on both the queue path and the completed-steer follow-up path, and `DeliveryWorker` never alarms on it, recording a `retry_scheduled` recheck at a doubling interval from 1 to at most 15 minutes, which bounds ledger growth while a queue stays held. After someone resumes the thread, the next recheck writes `message.delivered` once, reusing the same durable message. Deliveries already marked delivered before a restart are not re-reported. Upstream's Stop now holds the queue as a restart does, so a delivery to a stopped agent takes this same held path and waits for a resume. A delivery to an agent stopped on a usage limit waits unsent with `A2ADeliveryHeldError` until the thread continues, whether or not its queue is held. A delivery to an idle agent with a held queue otherwise resumes the queue and joins the back (register D4), unless its latest executed run failed or was interrupted preparing a worktree (`workspacePreparation.type === "worktree"`) and the thread has no `worktreePath`; it then waits unsent too. A delivery to an agent also waits while an earlier one to it is still waiting (`DeliveryWorker.ts`), and a run starting on the agent's thread hands its waiting deliveries over together, in send order (`SilenceDetector.ts`). When that worktree thread has no held queue yet, the delivery is sent: upstream accepts it and queues it held (`worktreeMissingRun` in `Orchestrator.ts`), and the delivery reports `A2ADeliveryHeldError` as for any held run. The worktree wait mirrors upstream's `worktreeMissingRun` in `Orchestrator.ts`, which holds a message queued then rather than run it in the project checkout (Jackson's 2026-10-17 decision). Upstream prunes settled outbox rows after seven days; a delivery retried after its steer row was pruned falls through to the accepted message in the projection, and retries alarm long before then. `ThreadManagementService.ts` exports `latestSteerableRun` for the transport. Peer deliveries from agents carry `senderThreadId`, read from the sender's membership row in its project's ledger. Tests: `DeliveryTransport.integration.test.ts` "keeps held delivery pending…", "queues a message for a GPT 6 run that is stopping instead of failing it for good", "keeps a delivery unsent while a failed worktree setup holds the receiver's queue" and "settles a held peer delivery once after resume without alarming", and the `DeliveryWorker.test.ts` held case. The `deliveryOutcome` that `j5_send_message` returns (#746) is predicted in J5-owned `receiverBacklog.ts` (`readReceiverDelivery`) by these same selectors, `peerSteeringRun` and `requestedSteeringRun`, and reads a message the worker already handed over from its run or its delivered status; it needs no upstream edit and never waits on the worker. Its tests are in `DeliveryTransport.integration.test.ts` ("predicts how a message lands on a busy receiver…") and `PeerPollRoundTrip.test.ts`. +26. Active GPT 6 and Claude peer delivery and durable steer outcomes: `apps/server/src/j5/a2a/DeliveryTransport.ts` (`peerSteeringRun`) sends peer updates to an eligible running Codex GPT 6 turn (a resolved model name starting `gpt-6-` or `gpt-6.`, with or without the `openai.` qualifier: Astra, Luna, Sol and their point releases) or a running Claude turn as run-pinned native steers. A Claude turn takes one without cancelling its tool calls because of case 89. Other models and system notices queue, unless the sender set `mode` on `j5_send_message` ([#519](https://github.com/Jacksondr5/j5code/issues/519)): `steer` and `restart` dispatch upstream's `steer_active` and `restart_active` on the receiver's steerable run when its provider can do what was asked (`requestedSteeringRun`), and otherwise the message is delivered as any other. The mode rides in the `message.sent` payload with the sender's mode limit, which the transport supplies as upstream's `DispatchModeLimit` so the orchestrator re-checks it under the receiver's lock. A steer or restart for an agent on a peer server crosses as `landing` on the peer delivery (`peerDeliveryBody.ts`), only to a peer whose recorded capabilities include `landing`; `PeerInboundService.ts` refuses it for an agent above the sender's limit, reading the agent's modes from upstream's `orchestration_v2_projection_threads`, and keeps the request on the received fact for `DeliveryWorker.ts` to pass on. An asked-for steer or restart is dispatched under a command id of its own (`askedDeliveryCommandId`, `:`), which cancelling a delivery reads too: upstream records a rejected command for good, and a restart aimed at a turn that has just ended is rejected, so the plain delivery that follows needs a command id nothing has refused. Delivery waits on upstream's `EffectOutbox.awaitSettled` and then reads the outbox row with `get`; the runtime supplies that same outbox instance to delivery. J5 no longer edits `EffectOutbox.ts`: upstream shipped its own `awaitSettled` at the 2026-10-17 advance, and J5's edit and its test were retired. The asked-for steer or restart and the run-pinned GPT 6 or Claude steer are dispatched through `ThreadManagementService.dispatch`, not the orchestrator directly, so upstream's check that a project has the receiver's provider turned on applies to them as it does to upstream's own steer. Adopt upstream completed-turn follow-up with the original message identity and model: it queues behind active work and is delivered once durably accepted, even when no steer adapter call occurs. Transport verifies either the original steer outcome or a durable run for the same message; a restart, and a steer the provider takes by interrupting and restarting, show as the restarted run now answering that message. Interrupted, failed and explicitly stopped work does not follow up. The run-pinned GPT 6 or Claude steer is dispatched under a command id of its own too, `askedDeliveryCommandId(id, "steer")`: since the 2026-10-24 advance upstream rejects a steer to a run that is stopping (pingdotgg/t3code#16926) and records the rejection for good, so on that rejection the delivery falls back to the queue under its own id. A steer therefore no longer races a Stop (register D5, retired 2026-10-08, is moot). This is independent of upstream human composer defaults. Upstream holds queued runs after restart and queues new messages held behind them (decision #6, 2026-09-24). A delivery whose accepted run is `queued` + `queueHeld` is not delivered: `DeliveryTransport` fails it with `A2ADeliveryHeldError` on both the queue path and the completed-steer follow-up path, and `DeliveryWorker` never alarms on it, recording a `retry_scheduled` recheck at a doubling interval from 1 to at most 15 minutes, which bounds ledger growth while a queue stays held. After someone resumes the thread, the next recheck writes `message.delivered` once, reusing the same durable message. Deliveries already marked delivered before a restart are not re-reported. Upstream's Stop now holds the queue as a restart does, so a delivery to a stopped agent takes this same held path and waits for a resume. A delivery to an agent stopped on a usage limit waits unsent with `A2ADeliveryHeldError` until the thread continues, whether or not its queue is held. A delivery to an idle agent with a held queue otherwise resumes the queue and joins the back (register D4), unless its latest executed run failed or was interrupted preparing a worktree (`workspacePreparation.type === "worktree"`) and the thread has no `worktreePath`; it then waits unsent too. A delivery to an agent also waits while an earlier one to it is still waiting (`DeliveryWorker.ts`), and a run starting on the agent's thread hands its waiting deliveries over together, in send order (`SilenceDetector.ts`). When that worktree thread has no held queue yet, the delivery is sent: upstream accepts it and queues it held (`worktreeMissingRun` in `Orchestrator.ts`), and the delivery reports `A2ADeliveryHeldError` as for any held run. The worktree wait mirrors upstream's `worktreeMissingRun` in `Orchestrator.ts`, which holds a message queued then rather than run it in the project checkout (Jackson's 2026-10-17 decision). Upstream prunes settled outbox rows after seven days; a delivery retried after its steer row was pruned falls through to the accepted message in the projection, and retries alarm long before then. `ThreadManagementService.ts` exports `latestSteerableRun` for the transport. Peer deliveries from agents carry `senderThreadId`, read from the sender's membership row in its project's ledger. Tests: `DeliveryTransport.integration.test.ts` "keeps held delivery pending…", "queues a message for a GPT 6 run that is stopping instead of failing it for good", "keeps a delivery unsent while a failed worktree setup holds the receiver's queue" and "settles a held peer delivery once after resume without alarming", and the `DeliveryWorker.test.ts` held case. 27. Retired 2026-09-24 (Jackson's review of PR #262): issue #73's truthful-steer seam is removed, and the person's steer and queue presentation follows upstream as-is on every client. `packages/client-runtime/src/j5/steerState.ts`, its `./j5/steer-state` export, and `apps/web/src/j5/composer/` are deleted; `ComposerPrimaryActions.tsx` and mobile `ThreadQueueControl.tsx` equal upstream; `ChatComposer.tsx` and `QueuedRunsControl.tsx` keep only their other recorded seams (saved-agent/persona rows, case 24). Remaining steer UX gaps are tracked in the upstream give-back backlog, [Jacksondr5/j5code#276](https://github.com/Jacksondr5/j5code/issues/276). The number stays reserved. 28. Retired 2026-10-08 (Jackson's decision 15; register D7): J5's Codex CLI version floor is removed. `apps/server/src/j5/codex/` is deleted with its tests, `Adapters/CodexAdapterV2.ts` no longer reads the `initialize` response's `userAgent` for a gate, and `ProviderTurnStartService.ts` has no handling for a version error. J5 follows upstream's provider compatibility table, which advises and does not block; case 59 records the one edit that table needs. The number stays reserved. diff --git a/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts b/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts index dd030aec19817..b4c8727e8b486 100644 --- a/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts +++ b/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts @@ -146,7 +146,7 @@ import { formatPeerEnvelope, } from "./EnvelopeFormatter.ts"; import { A2ALedger, layer as ledgerLayer } from "./LedgerService.ts"; -import { readReceiverDelivery, withDeliveryOutcome } from "./receiverBacklog.ts"; +import { readReceiverBacklog, withDeliveryNotice } from "./receiverBacklog.ts"; import { noneLayer as peerDirectoryNoneLayer } from "./PeerDirectory.ts"; import { A2ALifecycleService, manualLayer as lifecycleServiceLayer } from "./LifecycleService.ts"; import { @@ -1177,23 +1177,20 @@ it.effect("measures the backlog a send waits behind on a busy receiver", () => message: `Update ${name}`, acceptedAt: `2026-09-24T00:00:0${sequence++}.000Z`, }); - const deliveryFor = (sent: { readonly messageId: LedgerMessageId }) => - readReceiverDelivery({ + const backlogFor = (sent: { readonly messageId: LedgerMessageId }) => + readReceiverBacklog({ receiverId: target.receiverId, callerThreadId: caller.threadId, sentMessageId: sent.messageId, }); - const backlogFor = (sent: { readonly messageId: LedgerMessageId }) => - deliveryFor(sent).pipe(Effect.map((delivery) => delivery?.backlog)); - // An idle receiver, or a seat that has not started, takes the message at once: nothing to - // warn about. + // An idle receiver takes the message at once: nothing to warn about. const firstInput = sendInput(caller, "first"); const first = yield* send.send(firstInput); - assert.deepStrictEqual(yield* deliveryFor(first), { outcome: "starting" }); + assert.isUndefined(yield* backlogFor(first)); // Nor once the message has started its own run. yield* worker.drain; - assert.deepStrictEqual(yield* deliveryFor(first), { outcome: "starting" }); + assert.isUndefined(yield* backlogFor(first)); yield* startPendingTestTurn(target.threadId); yield* finishTestTurn(harness, target.threadId); @@ -1201,13 +1198,14 @@ it.effect("measures the backlog a send waits behind on a busy receiver", () => // A replayed send of a message that has already run reports the current state. const replay = yield* send.send(firstInput); assert.equal(replay.messageId, first.messageId); - assert.isUndefined(yield* deliveryFor(replay)); + assert.isUndefined(yield* backlogFor(replay)); // Committed sends the worker has not handed over yet are waiting too. yield* send.send(sendInput(caller, "second")); const third = yield* send.send(sendInput(caller, "third")); - assert.deepStrictEqual(yield* deliveryFor(third), { - outcome: "queued", - backlog: { type: "behind_turn", waiting: 2, fromCaller: 2 }, + assert.deepStrictEqual(yield* backlogFor(third), { + type: "behind_turn", + waiting: 2, + fromCaller: 2, }); // Queued runs and pending deliveries add up; another sender's count is not the caller's. yield* worker.drain; @@ -1220,7 +1218,7 @@ it.effect("measures the backlog a send waits behind on a busy receiver", () => // Only agents on this server are measured. assert.isUndefined( - yield* readReceiverDelivery({ + yield* readReceiverBacklog({ receiverId: ParticipantId.make("agent:j5-a2a-delivery-backlog-elsewhere"), callerThreadId: caller.threadId, sentMessageId: third.messageId, @@ -1268,98 +1266,34 @@ it.effect("counts a message queued before an Astra turn became steerable", () => "queued", ); assert.deepStrictEqual( - yield* readReceiverDelivery({ + yield* readReceiverBacklog({ receiverId: target.receiverId, callerThreadId: ThreadId.make("thread:j5-a2a-delivery-backlog-astra-queued-caller"), sentMessageId: target.messageId, }), - { outcome: "queued", backlog: { type: "behind_turn", waiting: 1, fromCaller: 0 } }, + { type: "behind_turn", waiting: 1, fromCaller: 0 }, ); }).pipe(Effect.provide(makeTestLayer(harness))); }), ); -it.effect("predicts how a message lands on a busy receiver, before and after the worker acts", () => - Effect.gen(function* () { - const harness = yield* makeHarness; - yield* Effect.gen(function* () { - const send = yield* A2ASendService; - const worker = yield* A2ADeliveryWorker; - const effects = yield* OrchestrationEffectWorkerV2; - const caller = yield* seedTarget("outcome-caller"); - let sequence = 0; - const sendTo = ( - target: { readonly receiverId: ParticipantId }, - name: string, - mode?: "steer" | "restart", - ) => - send.send({ - commandId: CommCommandId.make(`command:j5-a2a-delivery-outcome-${name}`), - senderThreadId: caller.threadId, - to: target.receiverId, - message: `Update ${name}`, - ...(mode === undefined - ? {} - : { mode, modeLimit: { runtimeMode: "full-access", interactionMode: "default" } }), - acceptedAt: `2026-09-24T00:00:0${sequence++}.000Z`, - }); - const outcomeOf = ( - target: { readonly receiverId: ParticipantId }, - sent: { readonly messageId: LedgerMessageId }, - mode?: "steer" | "restart", - ) => - readReceiverDelivery({ - receiverId: target.receiverId, - callerThreadId: caller.threadId, - sentMessageId: sent.messageId, - mode, - }).pipe(Effect.map((delivery) => delivery?.outcome)); - - // A running GPT 6 turn takes the update mid-turn. Once the worker has steered it, the - // message has no run of its own, and still reads as steered. - const astra = yield* seedTarget( - "outcome-astra", - "gpt-6-astra", - undefined, - caller.ledgerProjectId, - ); - yield* startBusyTurn(astra); - const steeredByDefault = yield* sendTo(astra, "astra"); - assert.equal(yield* outcomeOf(astra, steeredByDefault), "steered"); - const drained = yield* worker.drain.pipe(Effect.forkChild({ startImmediately: true })); - yield* runWorkerUntil(effects, drained); - assert.lengthOf(yield* Ref.get(harness.steerInputs), 1); - assert.equal(yield* outcomeOf(astra, steeredByDefault), "steered"); - - // Another model queues a plain update behind the turn, steers when asked, and starts a new - // turn for a restart. - const other = yield* seedTarget( - "outcome-other", - modelSelection.model, - undefined, - caller.ledgerProjectId, - ); - yield* startBusyTurn(other); - assert.equal(yield* outcomeOf(other, yield* sendTo(other, "plain")), "queued"); - assert.equal( - yield* outcomeOf(other, yield* sendTo(other, "steer", "steer"), "steer"), - "steered", - ); - assert.equal( - yield* outcomeOf(other, yield* sendTo(other, "restart", "restart"), "restart"), - "starting", - ); - - // Nobody is on a thread that has not started: the message starts its first turn. - const idle = yield* seedTarget( - "outcome-idle", - modelSelection.model, - undefined, - caller.ledgerProjectId, - ); - assert.equal(yield* outcomeOf(idle, yield* sendTo(idle, "idle")), "starting"); - }).pipe(Effect.provide(makeLifecycleTestLayer(harness))); - }), +it.effect( + "reports no backlog for a running Astra receiver, which takes peer messages mid-turn", + () => + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* Effect.gen(function* () { + const target = yield* seedTarget("backlog-astra", "gpt-6-astra"); + yield* startBusyTurn(target); + assert.isUndefined( + yield* readReceiverBacklog({ + receiverId: target.receiverId, + callerThreadId: ThreadId.make("thread:j5-a2a-delivery-backlog-astra-caller"), + sentMessageId: target.messageId, + }), + ); + }).pipe(Effect.provide(makeTestLayer(harness))); + }), ); it.effect( @@ -4015,7 +3949,7 @@ const sendNoticeTo = Effect.fn("A2AIntegration.sendNoticeTo")(function* ( message: "An update", acceptedAt: "2026-09-24T00:00:00.000Z", }); - return (yield* withDeliveryOutcome(sent, { + return (yield* withDeliveryNotice(sent, { receiverId: target.receiverId, callerThreadId: caller.threadId, })).deliveryNotice; diff --git a/apps/server/src/j5/a2a/EnvelopeFormatter.test.ts b/apps/server/src/j5/a2a/EnvelopeFormatter.test.ts index b46e1026a027d..f910a2a442748 100644 --- a/apps/server/src/j5/a2a/EnvelopeFormatter.test.ts +++ b/apps/server/src/j5/a2a/EnvelopeFormatter.test.ts @@ -175,7 +175,7 @@ it("renders the receiver backlog notice with its measured counts", () => { it("keeps the tool descriptions on their documented contracts", () => { assert.equal( A2A_SEND_TOOL_DESCRIPTION, - "Send one durable message. To another agent, three uses: a **plain send** when you don't need a reply; an **ask** — set expect_reply=true with a one-line intent, opening an exchange the receiver owes a reply to; a **reply** — include the exchange_id from the ask you are answering, which closes that exchange. To the human, only an ask: a plain send to a person is refused — if nobody needs to act, say it in your own thread instead. Set urgency only when asking the human. Use this tool only for participants already returned by j5_list_participants; when creating a Peer Agent, put any reply expectation in j5_spawn_agent's brief instead of sending a follow-up ask. Returns once the message is committed; delivery continues asynchronously — carry on with your work, and the reply arrives later as an incoming message. An agent that is busy may handle each message as its own turn after its current one ends, so put related updates in one message rather than sending them one by one. The result's deliveryOutcome says what will happen to your message: steered (it joins the turn the receiver is running now), queued (it waits for the receiver's current turn to end, or for a held queue or usage limit to lift; deliveryNotice says what it waits behind), starting (it begins a turn for an idle receiver, a Crew member that has not started, or a restart), or waiting_for_recipient (the receiver's server is offline and receives it when next available). The outcome is predicted as the message is sent, and you are told separately if it later fails to arrive. A refused message is an error with its reason, not an outcome. To interrupt an agent that is busy, set mode: mode=steer puts your message into the turn it is running now, and mode=restart stops that turn and starts it again on your message. Without mode the message is delivered the ordinary way, whatever its text or its intent says: Claude and Codex GPT 6 agents take it into the turn they are running, and other agents take it after their current turn ends. intent only labels an ask. Leave mode out for updates and replies. A Claude agent takes a steer once its running tool calls finish, and on other agents a steer can cancel the tool calls in flight, so keep it for a correction the receiver must see now, not for an update. An idle receiver starts a turn on your message whichever mode you set. Attach files for an agent on this server with attachments: pending uploads from t3_attachment_prepare_upload, or files its thread already holds. A provider Subagent is not a participant and is refused. Reuse client_request_id to retry the same send safely.", + "Send one durable message. To another agent, three uses: a **plain send** when you don't need a reply; an **ask** — set expect_reply=true with a one-line intent, opening an exchange the receiver owes a reply to; a **reply** — include the exchange_id from the ask you are answering, which closes that exchange. To the human, only an ask: a plain send to a person is refused — if nobody needs to act, say it in your own thread instead. Set urgency only when asking the human. Use this tool only for participants already returned by j5_list_participants; when creating a Peer Agent, put any reply expectation in j5_spawn_agent's brief instead of sending a follow-up ask. Returns once the message is committed; delivery continues asynchronously — carry on with your work, and the reply arrives later as an incoming message. An agent that is busy may handle each message as its own turn after its current one ends, so put related updates in one message rather than sending them one by one; the result's deliveryNotice says when your message will wait behind the receiver's current turn. To interrupt an agent that is busy, set mode: mode=steer puts your message into the turn it is running now, and mode=restart stops that turn and starts it again on your message. Without mode the message is delivered the ordinary way, whatever its text or its intent says: Claude and Codex GPT 6 agents take it into the turn they are running, and other agents take it after their current turn ends. intent only labels an ask. Leave mode out for updates and replies. A Claude agent takes a steer once its running tool calls finish, and on other agents a steer can cancel the tool calls in flight, so keep it for a correction the receiver must see now, not for an update. An idle receiver starts a turn on your message whichever mode you set. Attach files for an agent on this server with attachments: pending uploads from t3_attachment_prepare_upload, or files its thread already holds. A provider Subagent is not a participant and is refused. Reuse client_request_id to retry the same send safely.", ); assert.include( A2A_SEND_TOOL_DESCRIPTION, diff --git a/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts b/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts index 0c655e39c76c4..f926c00c4db4a 100644 --- a/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts +++ b/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts @@ -952,7 +952,7 @@ it.effect( }; const waiting = yield* vmServer.send.send(note); assert.equal(waiting.receiverServer, laptop.label); - assert.equal(waiting.deliveryOutcome, "waiting_for_recipient"); + assert.equal(waiting.delivery, "waiting_for_recipient"); assert.isString(waiting.recipientLastAvailableAt); assert.equal( waiting.note, @@ -983,7 +983,7 @@ it.effect( for (const retry of [note, ended]) { const retried = yield* vmServer.send.send(retry); assert.equal(retried.receiverServer, laptop.label, retry.commandId); - assert.isUndefined(retried.deliveryOutcome, retry.commandId); + assert.isUndefined(retried.delivery, retry.commandId); assert.isUndefined(retried.note, retry.commandId); } }), diff --git a/apps/server/src/j5/a2a/SendService.ts b/apps/server/src/j5/a2a/SendService.ts index f81721d475752..f4696a3af2757 100644 --- a/apps/server/src/j5/a2a/SendService.ts +++ b/apps/server/src/j5/a2a/SendService.ts @@ -1264,7 +1264,7 @@ const rawLayer: Layer.Layer< return { ...result, receiverServer: server.name, - deliveryOutcome: "waiting_for_recipient", + delivery: "waiting_for_recipient", ...(server.lastAvailableAt === null ? {} : { recipientLastAvailableAt: server.lastAvailableAt }), diff --git a/apps/server/src/j5/a2a/contracts.ts b/apps/server/src/j5/a2a/contracts.ts index 4eacc22b9fe26..fd0ac2579d9f2 100644 --- a/apps/server/src/j5/a2a/contracts.ts +++ b/apps/server/src/j5/a2a/contracts.ts @@ -447,22 +447,6 @@ export const SendAsOutsideAgentInput = Schema.Struct({ }); export type SendAsOutsideAgentInput = typeof SendAsOutsideAgentInput.Type; -/** - * What a sent message will do, predicted when it is sent by the rule the delivery worker applies: - * `steered` lands in the turn the recipient is running now (directly, or by interrupting and - * restarting that turn when the sender asked for a `steer`); `queued` waits for a turn boundary or - * for a held queue or usage limit to lift; `starting` begins a turn for an idle recipient, a Crew - * seat that has not started, or a `restart`; `waiting_for_recipient` is an offline peer server. - * A refusal is not an outcome: it is the tool's error, with its reason. - */ -export const SendDeliveryOutcome = Schema.Literals([ - "steered", - "queued", - "starting", - "waiting_for_recipient", -]); -export type SendDeliveryOutcome = typeof SendDeliveryOutcome.Type; - export const SendMessageResult = Schema.Struct({ messageId: LedgerMessageId, exchangeId: Schema.NullOr(ExchangeId), @@ -473,11 +457,8 @@ export const SendMessageResult = Schema.Struct({ deliveryNotice: Schema.optional(Schema.String), /** The name of the peer server the receiver lives on; absent for a receiver on this server. */ receiverServer: Schema.optionalKey(Schema.String), - /** - * Absent when nothing can be said: the receiver is a person or an agent on a peer server that is - * available (its server decides on arrival), or the message already ran or was cancelled. - */ - deliveryOutcome: Schema.optionalKey(SendDeliveryOutcome), + /** Present when the receiver's server polls this one and is offline: the message waits for it. */ + delivery: Schema.optionalKey(Schema.Literal("waiting_for_recipient")), /** When that server was last available: its last poll. */ recipientLastAvailableAt: Schema.optionalKey(Schema.String), /** The same facts in one sentence an agent reads at a glance. */ diff --git a/apps/server/src/j5/a2a/envelopes.v1.json b/apps/server/src/j5/a2a/envelopes.v1.json index 67e7b8fae42ef..7989976256dd6 100644 --- a/apps/server/src/j5/a2a/envelopes.v1.json +++ b/apps/server/src/j5/a2a/envelopes.v1.json @@ -13,7 +13,7 @@ "replyInstruction": "Reply once with j5_send_message(to=\"{{senderId}}\", exchange_id=\"{{exchangeId}}\", message=\"...\") to close the exchange. Follow-ups from the asker carrying this id join the same exchange.", "oneShotInstruction": "The sender did not request a reply to this message. Use j5_send_message without exchange_id only if a new message is needed.", "closedExchangeInstruction": "The platform closed this exchange when this reply was sent. No further reply is required.", - "sendToolDescription": "Send one durable message. To another agent, three uses: a **plain send** when you don't need a reply; an **ask** — set expect_reply=true with a one-line intent, opening an exchange the receiver owes a reply to; a **reply** — include the exchange_id from the ask you are answering, which closes that exchange. To the human, only an ask: a plain send to a person is refused — if nobody needs to act, say it in your own thread instead. Set urgency only when asking the human. Use this tool only for participants already returned by j5_list_participants; when creating a Peer Agent, put any reply expectation in j5_spawn_agent's brief instead of sending a follow-up ask. Returns once the message is committed; delivery continues asynchronously — carry on with your work, and the reply arrives later as an incoming message. An agent that is busy may handle each message as its own turn after its current one ends, so put related updates in one message rather than sending them one by one. The result's deliveryOutcome says what will happen to your message: steered (it joins the turn the receiver is running now), queued (it waits for the receiver's current turn to end, or for a held queue or usage limit to lift; deliveryNotice says what it waits behind), starting (it begins a turn for an idle receiver, a Crew member that has not started, or a restart), or waiting_for_recipient (the receiver's server is offline and receives it when next available). The outcome is predicted as the message is sent, and you are told separately if it later fails to arrive. A refused message is an error with its reason, not an outcome. To interrupt an agent that is busy, set mode: mode=steer puts your message into the turn it is running now, and mode=restart stops that turn and starts it again on your message. Without mode the message is delivered the ordinary way, whatever its text or its intent says: Claude and Codex GPT 6 agents take it into the turn they are running, and other agents take it after their current turn ends. intent only labels an ask. Leave mode out for updates and replies. A Claude agent takes a steer once its running tool calls finish, and on other agents a steer can cancel the tool calls in flight, so keep it for a correction the receiver must see now, not for an update. An idle receiver starts a turn on your message whichever mode you set. Attach files for an agent on this server with attachments: pending uploads from t3_attachment_prepare_upload, or files its thread already holds. A provider Subagent is not a participant and is refused. Reuse client_request_id to retry the same send safely.", + "sendToolDescription": "Send one durable message. To another agent, three uses: a **plain send** when you don't need a reply; an **ask** — set expect_reply=true with a one-line intent, opening an exchange the receiver owes a reply to; a **reply** — include the exchange_id from the ask you are answering, which closes that exchange. To the human, only an ask: a plain send to a person is refused — if nobody needs to act, say it in your own thread instead. Set urgency only when asking the human. Use this tool only for participants already returned by j5_list_participants; when creating a Peer Agent, put any reply expectation in j5_spawn_agent's brief instead of sending a follow-up ask. Returns once the message is committed; delivery continues asynchronously — carry on with your work, and the reply arrives later as an incoming message. An agent that is busy may handle each message as its own turn after its current one ends, so put related updates in one message rather than sending them one by one; the result's deliveryNotice says when your message will wait behind the receiver's current turn. To interrupt an agent that is busy, set mode: mode=steer puts your message into the turn it is running now, and mode=restart stops that turn and starts it again on your message. Without mode the message is delivered the ordinary way, whatever its text or its intent says: Claude and Codex GPT 6 agents take it into the turn they are running, and other agents take it after their current turn ends. intent only labels an ask. Leave mode out for updates and replies. A Claude agent takes a steer once its running tool calls finish, and on other agents a steer can cancel the tool calls in flight, so keep it for a correction the receiver must see now, not for an update. An idle receiver starts a turn on your message whichever mode you set. Attach files for an agent on this server with attachments: pending uploads from t3_attachment_prepare_upload, or files its thread already holds. A provider Subagent is not a participant and is refused. Reuse client_request_id to retry the same send safely.", "listToolDescription": "Your address book, one project at a time: the project's agents, and the human, with the display name to recognize them by, the participant_id to address them with, the project_id and project_title that place them, and what each accepts (messages, exchanges, urgency). Leave project_id out to list your own project; pass another project's id, from t3_project_list, to list that one. People appear in every listing. Results come a page at a time: your own row first, then the people, then agents with the most recently active first. Narrow a listing with name_contains, or with settled=true or settled=false for settled or active agents. If this server is peered with others, each row also carries `server`: the name of the server the participant lives on, and whether it is this one (`local`), and the result names every server in `servers`; pass a peer server's name as server to list that server's agents instead of this one's. When you're told to message someone by name or role, resolve them here first. Your own row is marked self=true and its project_title is the project you work in; it cannot receive messages or open exchanges from you — use schedule_task if you need a future trigger for yourself. Provider Subagents are not participants: they do not appear here and cannot be messaged. Archived agents are hidden by default; set include_archived=true to see them with archived=true. They cannot receive messages or open Exchanges. The roster changes — after you spawn, archive, unarchive, or delete an agent, call this again instead of reusing a stale listing.", "receiverBacklogNotice": "{{receiverId}} is in the middle of a turn, with {{waiting}} message(s) waiting for it ({{fromYou}} from you). It will handle each one as a separate turn after its current turn ends, so put any further updates for it in one message.", "receiverLimitAutoResumeNotice": "{{receiverId}} hit its provider's usage limit and continues automatically at {{resetAt}}. Your message is saved and will run then, in the order it was sent. Don't send it again.", diff --git a/apps/server/src/j5/a2a/mcp/handlers.ts b/apps/server/src/j5/a2a/mcp/handlers.ts index 27ccfe0cfa895..6ad677a7289c4 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -55,7 +55,7 @@ import { A2ALedger } from "../LedgerService.ts"; import { PeerDirectory } from "../PeerDirectory.ts"; import { PeerRegistryService } from "../PeerRegistryService.ts"; import { ParticipantPlacementService } from "../PlacementService.ts"; -import { withDeliveryOutcome } from "../receiverBacklog.ts"; +import { withDeliveryNotice } from "../receiverBacklog.ts"; import { A2ASendService } from "../SendService.ts"; import { AGENT_STOP_REASON, stopThread } from "../stopThread.ts"; import { sendClaimingAttachments } from "./attachments.ts"; @@ -413,7 +413,7 @@ const handlers = { ? yield* send() : yield* sendClaimingAttachments(receiverThreadId, attachments, send); yield* worker.notify; - return yield* withDeliveryOutcome(result, { + return yield* withDeliveryNotice(result, { receiverId: input.to, callerThreadId: scope.thread.threadId, mode, diff --git a/apps/server/src/j5/a2a/mcp/outsideAgent.ts b/apps/server/src/j5/a2a/mcp/outsideAgent.ts index 1d2439ac0337d..2e249c56682ef 100644 --- a/apps/server/src/j5/a2a/mcp/outsideAgent.ts +++ b/apps/server/src/j5/a2a/mcp/outsideAgent.ts @@ -17,7 +17,6 @@ import { exceededDispatchModeLimit } from "../../../orchestration-v2/DispatchMod import { ThreadManagementService } from "../../../orchestration-v2/ThreadManagementService.ts"; import { type CommCommandId, outsideAgentParticipantId } from "../contracts.ts"; import { A2ADeliveryWorker } from "../DeliveryWorker.ts"; -import { withDeliveryOutcome } from "../receiverBacklog.ts"; import { A2ASendService } from "../SendService.ts"; import { sendClaimingAttachments } from "./attachments.ts"; import type { J5SendMessageInput } from "./tools.ts"; @@ -201,7 +200,7 @@ export const sendAsOutsideAgent = Effect.fn("j5.a2a.mcp.sendAsOutsideAgent")(fun ? yield* send() : yield* sendClaimingAttachments(receiver.threadId, attachments, send); yield* (yield* A2ADeliveryWorker).notify; - // The outcome only: the backlog notice counts the caller's own waiting messages by its thread, - // and an outside agent has none. - return yield* withDeliveryOutcome(result, { receiverId: input.to, mode }); + // No backlog notice: it counts the caller's own waiting messages by its thread, and an outside + // agent has none. + return result; }); diff --git a/apps/server/src/j5/a2a/receiverBacklog.ts b/apps/server/src/j5/a2a/receiverBacklog.ts index 5ce02279731be..6a7001cd6a79e 100644 --- a/apps/server/src/j5/a2a/receiverBacklog.ts +++ b/apps/server/src/j5/a2a/receiverBacklog.ts @@ -4,7 +4,7 @@ import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import { OrchestratorV2 } from "../../orchestration-v2/Orchestrator.ts"; -import { isActiveRun, latestActiveRun } from "../../orchestration-v2/ThreadManagementService.ts"; +import { latestActiveRun } from "../../orchestration-v2/ThreadManagementService.ts"; import { latestExecutedRun, latestRootProviderFailure, @@ -22,13 +22,7 @@ import { formatReceiverLimitNotice, formatReceiverQueueHeldNotice, } from "./EnvelopeFormatter.ts"; -import { - LedgerMessageId, - Participant, - type ParticipantId, - type SendDeliveryOutcome, - type SendMode, -} from "./contracts.ts"; +import { LedgerMessageId, Participant, type ParticipantId, type SendMode } from "./contracts.ts"; export type ReceiverBacklog = | { @@ -46,32 +40,18 @@ export type ReceiverBacklog = /** Its queue is held, so the message runs only once a person resumes it. */ | { readonly type: "queue_held" }; -/** What the sender is told about a message to an agent on this server. */ -export type ReceiverDelivery = { - readonly outcome: Exclude; - /** Why a queued message waits, when there is something to tell the sender. */ - readonly backlog?: ReceiverBacklog; -}; - const decodeParticipant = Schema.decodeUnknownEffect(Schema.fromJsonString(Participant)); /** - * What will become of a just-sent message to an agent on this server, by the rule the delivery - * worker applies, so the sender need not wait for the worker: `steered` into the running turn a - * Claude or GPT 6 receiver takes updates in, or one a sender-asked `steer` lands on; `starting` - * for an idle receiver, a Crew seat that has not started, or a `restart`; `queued` behind a turn - * or held queue, with a `backlog` saying why when it is something the sender can act on. A message - * the worker already handed over reads from what it did: its own run, or a delivery with no run, - * which is a steer. Undefined when nothing can be said: the receiver is not an agent on this - * server, or the message has already run or will never run. Measured when called and never - * stored, so it is advice to the sender, not a delivery fact. A failed read is logged and reads - * as undefined: the message is already committed, and the send must not fail over advice. + * What a just-sent message waits behind: the receiver's running turn and the A2A messages queued or + * not yet handed over after it, or a held queue or usage limit (D4). Undefined when it will not + * wait (idle receiver, mid-turn delivery, not a local agent, already run or never will). Advice + * measured on call, never stored, so a failed read logs and reads as undefined. */ -export const readReceiverDelivery = Effect.fn("j5.a2a.readReceiverDelivery")( +export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( function* (input: { readonly receiverId: ParticipantId; - /** The sending thread; an outside agent has none, and counts no waiting messages of its own. */ - readonly callerThreadId?: ThreadId | undefined; + readonly callerThreadId: ThreadId; readonly sentMessageId: LedgerMessageId; /** How the sender asked for the message to land; absent means `queue`. */ readonly mode?: SendMode | undefined; @@ -106,29 +86,16 @@ export const readReceiverDelivery = Effect.fn("j5.a2a.readReceiverDelivery")( ]); if (target.thread.archivedAt !== null) return undefined; - const mode = input.mode ?? "queue"; const runByMessage = new Map(target.runs.map((run) => [run.userMessageId, run])); const sentRun = runByMessage.get(deliveryMessageId(input.sentMessageId)); + // Already started or finished (a replay reports the current state, not the first one). + if (sentRun !== undefined && sentRun.status !== "queued") return undefined; const pending = pendingRows.filter( (row) => !runByMessage.has(deliveryMessageId(LedgerMessageId.make(row.message_id))), ); - if (sentRun !== undefined && sentRun.status !== "queued") { - // The worker got there first: a turn already runs on it (a replay reports the current - // state, not the first one). A steer by interrupt-restart shows the same way. - return isActiveRun(sentRun) - ? ({ outcome: mode === "steer" ? "steered" : "starting" } satisfies ReceiverDelivery) - : undefined; - } - if (sentRun === undefined && !pending.some((row) => row.message_id === input.sentMessageId)) { - // Not queued and not pending: a steer the worker has delivered into a running turn leaves - // no run of its own; a cancelled or alarmed message is not going anywhere. - const status = (yield* sql<{ readonly status: string }>` - SELECT status FROM j5_a2a_delivery WHERE message_id = ${input.sentMessageId} LIMIT 1 - `)[0]?.status; - return status === "delivered" - ? ({ outcome: mode === "restart" ? "starting" : "steered" } satisfies ReceiverDelivery) - : undefined; - } + // Neither queued nor pending: cancelled or alarmed, so it is not waiting. + if (sentRun === undefined && !pending.some((row) => row.message_id === input.sentMessageId)) + return undefined; if (latestActiveRun(target) === undefined) { // An idle receiver takes the message now, resuming a held queue first, unless it @@ -143,45 +110,36 @@ export const readReceiverDelivery = Effect.fn("j5.a2a.readReceiverDelivery")( turnItemTypes: ["error"], }); const hold = idleQueueHold({ ...target, turnItems }); - if (hold?.type === "worktree_setup_failed") - return { outcome: "queued", backlog: { type: "queue_held" } } satisfies ReceiverDelivery; - if (hold?.type === "usage_limit") { - // Upstream continues it at the reset only when its recovery is armed for this limit, - // as the thread's usage-limit banner shows. - const recovery = target.thread.limitRecovery; - const resetAt = latestRootProviderFailure(hold.run, turnItems)?.resetAt; - return { - outcome: "queued", - backlog: { - type: "usage_limit", - resetAt: - recovery?.autoResume === true && - recovery.runId === hold.run.id && - recovery.resetAt === resetAt - ? recovery.resetAt - : null, - }, - } satisfies ReceiverDelivery; - } - // Resuming a held queue starts its messages first and this one joins the back; the sender - // needs no notice, it runs without a person. - return target.runs.some((run) => run.status === "queued" && run.id !== sentRun?.id) - ? ({ outcome: "queued" } satisfies ReceiverDelivery) - : ({ outcome: "starting" } satisfies ReceiverDelivery); + if (hold?.type === "worktree_setup_failed") return { type: "queue_held" } as const; + if (hold?.type !== "usage_limit") return undefined; + // Upstream continues it at the reset only when its recovery is armed for this limit, + // as the thread's usage-limit banner shows. + const recovery = target.thread.limitRecovery; + const resetAt = latestRootProviderFailure(hold.run, turnItems)?.resetAt; + return { + type: "usage_limit", + resetAt: + recovery?.autoResume === true && + recovery.runId === hold.run.id && + recovery.resetAt === resetAt + ? recovery.resetAt + : null, + } satisfies ReceiverBacklog; } // Not yet handed over, so a running Claude or GPT 6 turn, or the turn a steer or restart lands on, // will take it mid-turn. Once queued, it stays queued even if the receiver's turn later // becomes steerable. + const mode = input.mode ?? "queue"; if ( sentRun === undefined && (mode === "queue" ? peerSteeringRun(target, "peer") : requestedSteeringRun(target, "peer", mode)) !== undefined ) - return { outcome: mode === "restart" ? "starting" : "steered" } satisfies ReceiverDelivery; + return undefined; // A held queue drains only when someone resumes the thread, not when its turn ends. if (target.runs.some((run) => run.status === "queued" && run.queueHeld === true)) - return { outcome: "queued", backlog: { type: "queue_held" } } satisfies ReceiverDelivery; + return { type: "queue_held" } as const; const callerId = (yield* sql<{ readonly sender_id: string }>` SELECT sender_id FROM j5_a2a_delivery WHERE message_id = ${input.sentMessageId} LIMIT 1 `)[0]?.sender_id; @@ -196,22 +154,17 @@ export const readReceiverDelivery = Effect.fn("j5.a2a.readReceiverDelivery")( messageIds: queued.map((run) => run.userMessageId), })).messages; return { - outcome: "queued", - backlog: { - type: "behind_turn", - waiting: queued.length + pending.length, - fromCaller: - input.callerThreadId === undefined - ? 0 - : queuedMessages.filter((message) => message.senderThreadId === input.callerThreadId) - .length + pending.filter((row) => row.sender_id === callerId).length, - }, - } satisfies ReceiverDelivery; + type: "behind_turn", + waiting: queued.length + pending.length, + fromCaller: + queuedMessages.filter((message) => message.senderThreadId === input.callerThreadId).length + + pending.filter((row) => row.sender_id === callerId).length, + } satisfies ReceiverBacklog; }, (effect, input) => effect.pipe( Effect.catch((cause) => - Effect.logWarning("J5 A2A receiver delivery read failed", { + Effect.logWarning("J5 A2A receiver backlog read failed", { receiverId: input.receiverId, cause, }).pipe(Effect.as(undefined)), @@ -219,39 +172,28 @@ export const readReceiverDelivery = Effect.fn("j5.a2a.readReceiverDelivery")( ), ); -/** - * Adds what the sender should know to a send result: the predicted `deliveryOutcome`, and a - * `deliveryNotice` when the message waits on something the sender can act on. An outside agent has - * no thread to count waiting messages by, so it gets the outcome alone. - */ -export const withDeliveryOutcome = Effect.fn("j5.a2a.withDeliveryOutcome")(function* < +/** Adds a notice to a send result when the message will wait: behind the receiver's turn, or on its hold. */ +export const withDeliveryNotice = Effect.fn("j5.a2a.withDeliveryNotice")(function* < R extends { readonly messageId: LedgerMessageId }, >( result: R, input: { readonly receiverId: ParticipantId; - readonly callerThreadId?: ThreadId | undefined; + readonly callerThreadId: ThreadId; readonly mode?: SendMode | undefined; }, ) { - const delivery = yield* readReceiverDelivery({ ...input, sentMessageId: result.messageId }); - if (delivery === undefined) return result; - const { backlog } = delivery; + const backlog = yield* readReceiverBacklog({ ...input, sentMessageId: result.messageId }); + if (backlog === undefined) return result; const deliveryNotice = - input.callerThreadId === undefined || backlog === undefined - ? undefined - : backlog.type === "behind_turn" - ? formatReceiverBacklogNotice({ - receiverId: input.receiverId, - waiting: backlog.waiting, - fromYou: backlog.fromCaller, - }) - : backlog.type === "usage_limit" - ? formatReceiverLimitNotice({ receiverId: input.receiverId, resetAt: backlog.resetAt }) - : formatReceiverQueueHeldNotice({ receiverId: input.receiverId }); - return { - ...result, - deliveryOutcome: delivery.outcome, - ...(deliveryNotice === undefined ? {} : { deliveryNotice }), - }; + backlog.type === "behind_turn" + ? formatReceiverBacklogNotice({ + receiverId: input.receiverId, + waiting: backlog.waiting, + fromYou: backlog.fromCaller, + }) + : backlog.type === "usage_limit" + ? formatReceiverLimitNotice({ receiverId: input.receiverId, resetAt: backlog.resetAt }) + : formatReceiverQueueHeldNotice({ receiverId: input.receiverId }); + return { ...result, deliveryNotice }; }); diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index 5b94d9430a87b..9ce10251d443c 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -21,7 +21,7 @@ An agent learns what it can do from its tools, and it reads a tool's description ### `j5_send_message` -**Description:** "Send one durable message. To another agent, three uses: a **plain send** when you don't need a reply; an **ask** — set expect_reply=true with a one-line intent, opening an exchange the receiver owes a reply to; a **reply** — include the exchange_id from the ask you are answering, which closes that exchange. To the human, only an ask: a plain send to a person is refused — if nobody needs to act, say it in your own thread instead. Set urgency only when asking the human. Use this tool only for participants already returned by j5_list_participants; when creating a Peer Agent, put any reply expectation in j5_spawn_agent's brief instead of sending a follow-up ask. Returns once the message is committed; delivery continues asynchronously — carry on with your work, and the reply arrives later as an incoming message. An agent that is busy may handle each message as its own turn after its current one ends, so put related updates in one message rather than sending them one by one. The result's deliveryOutcome says what will happen to your message: steered (it joins the turn the receiver is running now), queued (it waits for the receiver's current turn to end, or for a held queue or usage limit to lift; deliveryNotice says what it waits behind), starting (it begins a turn for an idle receiver, a Crew member that has not started, or a restart), or waiting_for_recipient (the receiver's server is offline and receives it when next available). The outcome is predicted as the message is sent, and you are told separately if it later fails to arrive. A refused message is an error with its reason, not an outcome. To interrupt an agent that is busy, set mode: mode=steer puts your message into the turn it is running now, and mode=restart stops that turn and starts it again on your message. Without mode the message is delivered the ordinary way, whatever its text or its intent says: Claude and Codex GPT 6 agents take it into the turn they are running, and other agents take it after their current turn ends. intent only labels an ask. Leave mode out for updates and replies. A Claude agent takes a steer once its running tool calls finish, and on other agents a steer can cancel the tool calls in flight, so keep it for a correction the receiver must see now, not for an update. An idle receiver starts a turn on your message whichever mode you set. Attach files for an agent on this server with attachments: pending uploads from t3_attachment_prepare_upload, or files its thread already holds. A provider Subagent is not a participant and is refused. Reuse client_request_id to retry the same send safely." +**Description:** "Send one durable message. To another agent, three uses: a **plain send** when you don't need a reply; an **ask** — set expect_reply=true with a one-line intent, opening an exchange the receiver owes a reply to; a **reply** — include the exchange_id from the ask you are answering, which closes that exchange. To the human, only an ask: a plain send to a person is refused — if nobody needs to act, say it in your own thread instead. Set urgency only when asking the human. Use this tool only for participants already returned by j5_list_participants; when creating a Peer Agent, put any reply expectation in j5_spawn_agent's brief instead of sending a follow-up ask. Returns once the message is committed; delivery continues asynchronously — carry on with your work, and the reply arrives later as an incoming message. An agent that is busy may handle each message as its own turn after its current one ends, so put related updates in one message rather than sending them one by one; the result's deliveryNotice says when your message will wait behind the receiver's current turn. To interrupt an agent that is busy, set mode: mode=steer puts your message into the turn it is running now, and mode=restart stops that turn and starts it again on your message. Without mode the message is delivered the ordinary way, whatever its text or its intent says: Claude and Codex GPT 6 agents take it into the turn they are running, and other agents take it after their current turn ends. intent only labels an ask. Leave mode out for updates and replies. A Claude agent takes a steer once its running tool calls finish, and on other agents a steer can cancel the tool calls in flight, so keep it for a correction the receiver must see now, not for an update. An idle receiver starts a turn on your message whichever mode you set. Attach files for an agent on this server with attachments: pending uploads from t3_attachment_prepare_upload, or files its thread already holds. A provider Subagent is not a participant and is refused. Reuse client_request_id to retry the same send safely." | Input | Type | Required | Meaning | | ------------------- | ----------------- | ------------------------------------ | ------------------------------------------------------------------------------- | @@ -42,9 +42,9 @@ An agent learns what it can do from its tools, and it reads a tool's description **Attachments.** Each is a pending upload from `t3_attachment_prepare_upload`, or an attachment the receiver's thread already holds. They are claimed into the receiver's thread before the message is committed, and released if the send is refused before anything is committed (an unacceptable sender, receiver or request). A storage failure leaves the claims in place, because nobody knows then whether the message was committed. A person and an agent on a peer server take no attachments. This replaces J5's own version of `t3_thread_send_attachments`, which sent a thinner message through the same ledger: no ask or reply, no retry key, no landing choice. -**Result:** the message id, the Exchange's state, and a `deliveryOutcome`, one per call because the tool takes one recipient: `steered`, the message joins the turn the receiver is running now (directly on Claude and Codex GPT 6, or by interrupting and restarting that turn when the sender set `mode=steer` on a provider that does it that way, as Cursor does); `queued`, it waits for the receiver's current turn to end or for a held queue or usage limit to lift; `starting`, it begins a turn now, for an idle receiver, a Crew member that has not started (its first assignment), or a `restart`; `waiting_for_recipient`, the receiver's server is offline. The outcome is predicted as the message is sent, by the same rule the delivery worker applies (`peerSteeringRun` and `requestedSteeringRun` in `DeliveryTransport.ts`), and never waits on the worker. It is a prediction: a turn that ends before delivery turns a `steered` into a start, and the existing late-failure alarm is how a sender learns a message did not arrive. It is absent when nothing can be said: the receiver is a person or an agent on an available peer server, which decides on arrival, or the message has already run or was cancelled. A refusal is not an outcome. It stays a tool error with its reason (see Errors). When the message will wait, the result also carries a `deliveryNotice`, advice about what it waits behind. Behind a turn the receiver will not take it into, the notice states how many messages are waiting for it, how many of them are the caller's, and that each will run as its own turn. A message to an agent stopped on a usage limit always waits until the agent continues. When the message waits on that limit, or on the receiver's held queue or failed worktree setup, the notice says it runs, in the order it was sent, once a person resumes or continues the receiver, or at the reset time when upstream continues it automatically, and that it should not be sent again. The notice is measured as the message is sent; a sender is not told when a receiver's queue is held later. When the recipient lives on a peer server, the result also names that server. When that server is offline, the outcome is `waiting_for_recipient`, and the result gives when the server was last available, and its wording names the server: "Recorded. is on Laptop, which is offline, last available 3 h ago; it receives this when Laptop is next available." A recipient on this server adds no server name; one on an online peer server adds only that server's name. +**Result:** the message id and the Exchange's state. When the receiver is an agent on this server and the message will wait, the result also carries a `deliveryNotice`. Behind a turn the receiver will not take it into, the notice states how many messages are waiting for it, how many of them are the caller's, and that each will run as its own turn. A message to an agent stopped on a usage limit always waits until the agent continues. When the message waits on that limit, or on the receiver's held queue or failed worktree setup, the notice says it runs, in the order it was sent, once a person resumes or continues the receiver, or at the reset time when upstream continues it automatically, and that it should not be sent again. The notice is measured as the message is sent; a sender is not told when a receiver's queue is held later. When the recipient lives on a peer server, the result also names that server. When that server is offline, the result says the message is waiting for the recipient and when the server was last available, and its wording names the server: "Recorded. is on Laptop, which is offline, last available 3 h ago; it receives this when Laptop is next available." A recipient on this server adds nothing; one on an online peer server adds only that server's name. -**Rules.** A message to the caller itself is refused. A message addressed to an [outside agent](index.md#participants) is refused for every sender, because nothing can be delivered to one. A send to a person that is not an ask is refused; a person never opens an Exchange, so there is nothing for an agent to reply to. Between agents, a further ask to a peer that already holds an open Exchange from the caller joins it as a follow-up. To a person, a further ask opens a new Exchange and a new inbox item unless it names an open one in `regarding`, in which case it joins that Exchange and is shown beneath the original ask. An ask to a person without an urgency is refused. An outside agent sends a plain message only, so `expect_reply`, `exchange_id`, `intent` and `urgency` are refused from it, and so is a person, who takes only asks. It reaches agents on this server only: an agent on a peer server and an id the server does not know are refused. A thread caller's receiver is held to the caller's permission modes only for `steer` and `restart`. An outside agent's receiver is held to the level the sign-in was approved at on every send, one that asks for no steer or restart included. The level is checked when the message is sent, not when it lands. An outside agent's message is recorded in the receiver's project, and its result carries the `deliveryOutcome` but no `deliveryNotice`. Attachments work the same for every sender. +**Rules.** A message to the caller itself is refused. A message addressed to an [outside agent](index.md#participants) is refused for every sender, because nothing can be delivered to one. A send to a person that is not an ask is refused; a person never opens an Exchange, so there is nothing for an agent to reply to. Between agents, a further ask to a peer that already holds an open Exchange from the caller joins it as a follow-up. To a person, a further ask opens a new Exchange and a new inbox item unless it names an open one in `regarding`, in which case it joins that Exchange and is shown beneath the original ask. An ask to a person without an urgency is refused. An outside agent sends a plain message only, so `expect_reply`, `exchange_id`, `intent` and `urgency` are refused from it, and so is a person, who takes only asks. It reaches agents on this server only: an agent on a peer server and an id the server does not know are refused. A thread caller's receiver is held to the caller's permission modes only for `steer` and `restart`. An outside agent's receiver is held to the level the sign-in was approved at on every send, one that asks for no steer or restart included. The level is checked when the message is sent, not when it lands. An outside agent's message is recorded in the receiver's project, and its result carries no `deliveryNotice`. Attachments work the same for every sender. **Errors**, each naming the actual state and the next command: the caller is not a participant (a provider Subagent or a deleted thread); the recipient is not addressable (pointing at `j5_list_participants`); the recipient is the caller (naming the caller's own id, and `schedule_task` for a future trigger to oneself); an ask without an intent; a send to a person that is not an ask (naming the legal move and the own-thread alternative); an ask to a person without urgency; an `exchange_id` or `regarding` that is unknown, already closed, or not the caller's (naming the Exchange's actual state); a first message to a participant on a peer server whose address book cannot be read, or that has not polled yet (naming that reason). For an outside agent: anything but a plain message (naming a retry without those fields); a person, a peer server's agent or an unknown id (naming the legal move); a receiver that runs above the approved level (naming the level). For every sender: a message addressed to an outside agent (saying nothing can be delivered to it). @@ -74,7 +74,7 @@ Read-only; no events. ### `j5_spawn_agent` -Agents have two ways to get help: a subagent (their provider's own, or `delegate_task`) or members on a Crew (`j5_propose_crew`, `j5_request_crew_member`). `j5_spawn_agent` serves neither. Its description limits it to a user's explicit request for a standalone agent they will talk to, and to callers that name it, such as an outside agent or a skill. Nothing a caller depends on was removed. +Agents have two ways to get help: a subagent (their provider's own, or `delegate_task`) or members on a Crew (`j5_propose_crew`, `j5_request_crew_member`). `j5_spawn_agent` serves neither. Its description keeps it for a Peer Agent or standalone agent the person explicitly asks for, and for callers that name it, such as an outside agent or a skill; when nobody asked for one it says to use a subagent or a Crew. Nothing a caller depends on was removed. **Description (contract):** "Use this when the user explicitly asks for a Peer Agent or a standalone agent they will talk to, or when an outside agent or a skill you are following names it. When nobody asked for one, it is not a diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index aab4043df5b2b..16bb673f40b51 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 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. An agent chooses a Crew when the work needs workers who must respond to each other, and the person can ask for one in an ordinary conversation (web and desktop); the word "crew" in a message does not decide it, because the agent weighs the work (AC1). Once it chooses a Crew, 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, where the project's models for custom members allow that model, 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. +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 can ask for a Crew in an ordinary conversation (web and desktop), and an agent also chooses one when the work needs workers who must respond to each other (AC1). Once it chooses a Crew, 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, where the project's models for custom members allow that model, 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. @@ -65,7 +65,7 @@ A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26). ### Launch and the gate -1. An agent chooses between working directly, subagents for independent assignments, and a Crew for work whose workers must respond to each other, from the work and not from the user's wording: "crew" in a message does not decide it. It may reassess mid-work and carry finished findings forward without restarting completed work. Once it chooses a Crew it proposes a roster before doing the delegated work. The thread retains its persona, model, and policy; saved personas are optional and there is no Crew slash command. +1. An explicit request for a Crew, a Peer Agent or a subagent gets that mechanism (Jackson, 2026-10-31); a word mentioned in passing, or in quoted text, is not a request. When the person asked for none, an agent chooses between working directly, subagents for independent assignments, and a Crew for work whose workers must respond to each other, from the work. It may reassess mid-work and carry finished findings forward without restarting completed work. Once it chooses a Crew it proposes a roster before doing the delegated work. The thread retains its persona, model, and policy; saved personas are optional and there is no Crew slash command. 2. Initial roster proposals start collapsed in a compact strip above the Captain’s composer, alongside Tasks and Playbooks. Expanding or collapsing the strip is remembered for that thread and environment; the roster draft survives collapsing and the strip leaving while the composer shows an approval or a question, until the person decides. The person reviews the outcome and members, adds or removes members, edits a member in a modal, and approves or declines the final roster. Add and Edit share the same modal: Cancel discards that modal’s changes, while Save validates the member and returns to the roster. Invalid or duplicate names and missing custom-member instructions prevent saving. The last member cannot be removed. Approval is unavailable while a modal is open or a matching full-roster preview is missing. With Auto-approve new Crews enabled for the Captain’s project, it launches as proposed with no card. 3. Each proposal member shows its provider, name, model, reasoning, access, and the Captain’s reason. Non-shared workspaces and access that stops for approvals remain visible. The Persona picker offers Custom member and the available saved personas. Selecting a saved persona populates its name and instructions and resolves its runtime defaults; the saved definition is unchanged. The instructions box holds the persona’s whole text, and an edit replaces the persona’s instructions for this member only; the original is not also sent, and Reset to persona text returns the box to the saved text. The instructions an agent attaches to a persona seat stay additional, and an unedited box keeps them. Runtime and workspace choices remain editable. A new custom member starts in the Captain’s checkout. Existing and new worktrees use the Captain’s repository options. Editing the roster refreshes the server preview, which binds the exact runtime settings, Captain’s project and checkout, each seat’s workspace, and the current playbook plan. Missing, unavailable, incomplete, or stale previews cannot approve a launch. Playbook proposals retain each member’s steps, persona-swap explanations, and unowned steps for the Captain. The card cannot reassign steps; removing a member leaves its steps unowned. 4. A seat naming an agent missing from or disabled in the library, a duplicate seat name, or a roster past twelve seats is refused to the Captain with the next step, before anything spawns; prose is never parsed. So are an unknown or invalid playbook, a step the playbook lacks, a step claimed by two seats (or already owned by a live member), and steps on a Crew without a playbook. A seat that claims no steps needs no readable playbook, so a Crew whose playbook file is gone can still grow. Each step has one owner, enforced again where member rows are written, so of two additions racing for one step the first reservation wins and the second is refused. @@ -120,10 +120,6 @@ A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26). 29. Reasoning levels follow the same rules as models, per provider instance: until a list is saved every level is eligible, a saved list holds only the checked levels so a level new to the catalog starts unchecked, and a saved empty list makes none eligible. A provider's levels are the choices of its models' reasoning options; a thinking switch is not a level. 30. A custom seat, a plain `j5_spawn_agent` and a plain `delegate_task` are refused when the level they would run at, the explicit one or else the model's default, is unchecked: the refusal names the level, the model, the provider, the project and the setting, lists the levels that model may use, and creates nothing. A model with no reasoning option has no level to check. The roster card offers a custom member only eligible levels and starts a changed model on its first eligible level; a persona seat's pickers stay whole. A retry of a call or proposal already accepted is not checked again. -### Messages - -31. `j5_send_message` returns a typed `deliveryOutcome` for its one recipient: `steered` into a running turn, `queued` for the next turn, `starting` the recipient's turn (an idle recipient, a member that has not started, or a restart), or `waiting_for_recipient` for an offline peer server. It is predicted at send time by the rule the delivery worker applies and never waits on the worker; the alarm for a message that later fails to arrive is unchanged, and `deliveryNotice` still advises when the message waits on a held queue, a usage limit, or a failed worktree setup. A refusal is not an outcome: it stays a tool error with its reason. - ## Scenarios - **A review loop.** The Builder pushes a commit and tells the Critic. The Critic sends its findings to the Builder, not to the Captain; the Builder fixes them and replies to the Critic. After the second round the Critic has no findings left and sends the Captain one review pass naming the commit it reviewed. The Captain never relayed a message. (AC9, AC24) @@ -175,4 +171,4 @@ A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26). - 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-27 — models for custom members: a project's lists of checked models and checked reasoning levels decide what custom seats, plain spawned agents and plain delegated tasks run on; personas keep their own; native subagents are outside the lists on every provider (AC24–AC30; Bryant; [#744](https://github.com/Jacksondr5/j5code/issues/744)). -- 2026-10-27 — an agent chooses between working directly, subagents, and a Crew from the work, not from the word "crew"; members run their own review loops and reach the Captain only for a review pass, a blocker, or a disagreement; `j5_send_message` reports a delivery outcome (AC1, AC9, AC31; Bryant; [#746](https://github.com/Jacksondr5/j5code/issues/746)). +- 2026-10-27 — when the person asked for none, an agent chooses between working directly, subagents, and a Crew from the work; an explicit request for a Crew, a Peer Agent or a subagent still gets that mechanism; members run their own review loops and reach the Captain only for a review pass, a blocker, or a disagreement, or their final result (AC1, AC9; Bryant and Jackson; [#746](https://github.com/Jacksondr5/j5code/issues/746)). diff --git a/docs/j5/product/upstream.md b/docs/j5/product/upstream.md index 893883065ed4d..24e6870f56a2c 100644 --- a/docs/j5/product/upstream.md +++ b/docs/j5/product/upstream.md @@ -46,13 +46,13 @@ Letter codes in the Decided lines (SC2, QS1, AR3, and so on) are rulings recorde ### Agents and orchestration -#### D1. Help is a Subagent or a Crew member, chosen from the work +#### D1. Help is a Subagent or a Crew member, chosen from the work unless the person names one **Upstream:** the instructions every agent receives point it to `delegate_task` for help from another provider, or from a model its own subagent tool can't run, and to `t3_thread_launch` or `create_threads` to start new threads. -**J5:** agents are told to choose among working directly, subagents for independent assignments, and a Crew for work whose workers must respond to each other, from the work and not from the words in the user's message, and may reassess mid-work without restarting completed work. There are two ways to get help: create a subagent (their provider's own, or `delegate_task` across providers), or put members on a Crew (`j5_propose_crew` to start one, `j5_request_crew_member` to grow one). `j5_spawn_agent` stays for a user's explicit request for a standalone agent they will talk to, and for callers that already use it (outside agents, skills); it is not described as a way to get help. `delegate_task` is kept for narrow cases: running a saved persona as a subagent, work on another provider that the person doesn't need to talk to directly, and, as upstream says, a model the provider's own subagent tool can't run or a child that needs a checkout of its own (a worktree started from the parent's local commit). A review that takes several rounds gets a new `delegate_task` call for each round. +**J5:** an explicit request for a Crew, a Peer Agent or a subagent gets that mechanism, and a word mentioned in passing or in quoted text is not a request. When the person asked for none, agents are told to choose among working directly, subagents for independent assignments, and a Crew for work whose workers must respond to each other, from the work, and may reassess mid-work without restarting completed work. There are two ways to get help: create a subagent (their provider's own, or `delegate_task` across providers), or put members on a Crew (`j5_propose_crew` to start one, `j5_request_crew_member` to grow one). `j5_spawn_agent` stays for a user's explicit request for a Peer Agent or a standalone agent they will talk to, and for callers that already use it (outside agents, skills); when nobody asked for one it is not described as a way to get help. `delegate_task` is kept for narrow cases: running a saved persona as a subagent, work on another provider that the person doesn't need to talk to directly, and, as upstream says, a model the provider's own subagent tool can't run or a child that needs a checkout of its own (a worktree started from the parent's local commit). A review that takes several rounds gets a new `delegate_task` call for each round. -**Why:** upstream's delegated child is "a Peer Agent in a Subagent costume": the person can't talk to it, yet it outlives the agent that started it. That is the awkward middle J5's vocabulary exists to remove. The Crew shape was added after an agent asked to "spawn a crew" made subagents instead, because nothing it had been told mentioned a Crew. The rule that the word "crew" decides was reversed on 2026-10-27: it sent agents to a Crew because the user said "crew", and to a standalone Peer Agent when a subagent would do. Personas later gave `delegate_task` a purpose again: a persona needs a way to run as a subagent. +**Why:** upstream's delegated child is "a Peer Agent in a Subagent costume": the person can't talk to it, yet it outlives the agent that started it. That is the awkward middle J5's vocabulary exists to remove. The Crew shape was added after an agent asked to "spawn a crew" made subagents instead, because nothing it had been told mentioned a Crew. The rule that the word "crew" decides was narrowed on 2026-10-27: it sent agents to a Crew because the user said "crew", and to a standalone Peer Agent when a subagent would do. An explicit request for a Crew, a Peer Agent or a subagent gets that mechanism again (Jackson, 2026-10-31); the choice from the work applies only when the person asked for none. Personas later gave `delegate_task` a purpose again: a persona needs a way to run as a subagent. **Consequences:** upstream's launch and workspace guidance never reaches J5 agents. `j5_spawn_agent` and Crew seats require their own workspace choice instead, with upstream's `existing_worktree` name and shape beside `shared` and `worktree`, and reuse upstream's ThreadLaunch to prepare a new worktree (#274). A spawn may also name upstream's `root`, the project's main checkout, and may join another project or upstream's "No project" project (#519); a Crew seat stays in its Captain's project with the first three choices. J5's text lives in a J5 folder inside upstream's shared provider package, and the constant upstream exports for its own text points at it. So J5's text reaches every harness that reads that constant: Codex, Claude, Cursor, OpenCode, the ACP agents and Pi, and any provider upstream later moves into a package of its own. Every upstream advance ports upstream's prompt changes into it by hand, and a test pins J5's wording. J5 takes upstream's own sections as upstream writes them: secrets, thread links, showing visuals, the browser, and the `delegate_task` rules above. Since v0.1.3 they are upstream's shorter text, with its rule on settings: a native subagent is right when the child needs no settings beyond the parent's, and only settings the user asked for send a child through `delegate_task`. J5's own description of `delegate_task` is its persona rules followed by upstream's short text; upstream's mechanics (the worktree option, a wait that ends at the child's question, runtime modes, options) are on the input fields J5 reuses. @@ -643,4 +643,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-27 — D1: agents choose between working directly, subagents and a Crew from the work, not from the word "crew", and get help in two ways, a subagent or a Crew member; `j5_spawn_agent` is described only for a standalone agent the user asks for (Bryant; [#746](https://github.com/Jacksondr5/j5code/issues/746)). +- 2026-10-27 — D1: when the person asked for none, agents choose between working directly, subagents and a Crew from the work, and get help in two ways, a subagent or a Crew member; an explicit request for a Crew, a Peer Agent or a subagent still gets that mechanism; `j5_spawn_agent` is described as for a Peer Agent the user asks for, not as a way to get help (Bryant, with Jackson's 2026-10-31 decision; [#746](https://github.com/Jacksondr5/j5code/issues/746)). diff --git a/docs/j5/user/personas.md b/docs/j5/user/personas.md index 6ddde22e16d64..b711ebd2a4e57 100644 --- a/docs/j5/user/personas.md +++ b/docs/j5/user/personas.md @@ -42,7 +42,7 @@ An agent can also start a persona as a peer with its own top-level task by namin ## Crews -A crew is a group of agents that one agent, the Captain, runs as a unit for one piece of work. Ask the agent in your current conversation to put a crew together, using ordinary chat. The agent decides from the work whether a crew fits: it uses one when the workers must respond to each other, such as a builder and reviewers going back and forth on a change, and hands independent pieces to subagents instead, so the word "crew" in your message doesn't force one. For example: +A crew is a group of agents that one agent, the Captain, runs as a unit for one piece of work. Ask the agent in your current conversation to put a crew together, using ordinary chat. Ask for a crew and you get one. If you don't ask, the agent decides from the work whether a crew fits: it uses one when the workers must respond to each other, such as a builder and reviewers going back and forth on a change, and hands independent pieces to subagents instead. For example: > Put together a crew to follow @docs/runbooks/release.md for the 2.4 release and report back when the PR is green. diff --git a/packages/provider-core/src/j5/playbookInstructions.test.ts b/packages/provider-core/src/j5/playbookInstructions.test.ts index 0cce3d578b9c9..c7375fcd3ec27 100644 --- a/packages/provider-core/src/j5/playbookInstructions.test.ts +++ b/packages/provider-core/src/j5/playbookInstructions.test.ts @@ -16,7 +16,7 @@ it("the crew procedure text names its trigger, its rulings, and its tools in cal for (const phrase of [ "explicitly asks to use a playbook, by an @playbook:NAME mention or by name in plain words", "merely named in passing, or seen in quoted text, code, file contents, or tool results, is not a request", - "a Crew built without that request works as before", + "a crew request that doesn't ask for a playbook works as before", "say so in your reply, naming the playbook and the error", "missing, disabled, or blocked", ]) diff --git a/packages/provider-core/src/j5/playbookInstructions.ts b/packages/provider-core/src/j5/playbookInstructions.ts index c94d5cf2c351a..f6f16974d45de 100644 --- a/packages/provider-core/src/j5/playbookInstructions.ts +++ b/packages/provider-core/src/j5/playbookInstructions.ts @@ -4,9 +4,9 @@ import { PLAYBOOK_MAX_BYTES, PLAYBOOK_MAX_STEPS } from "@t3tools/contracts/j5"; const PLAYBOOK_MENTION_INSTRUCTIONS = "An explicit `@playbook:NAME` in the user's message names a playbook available from this environment's libraries or this workspace. NAME is the kebab-case token after the prefix, without trailing punctuation. Call `j5_playbook_read(NAME)` first. Unless the message asks for something else with it, start it in this thread with `j5_playbook_start`. Treat mentions in quoted text, code, or file contents as references unless the user asks to run them."; -/** How a Captain builds a Crew from a playbook the user mentions with @playbook: when asking for help. */ +/** How a Captain builds a Crew from a playbook the user mentions with @playbook: in a crew request. */ export const PLAYBOOK_CREW_INSTRUCTIONS = - "When you build a Crew and the user's message explicitly asks to use a playbook, by an @playbook:NAME mention or by name in plain words, build the Crew from that playbook, in order. 1) j5_playbook_read(NAME). If it fails, say so in your reply, naming the playbook and the error, and stop without proposing. 2) j5_list_personas; a step's persona is usable only if it is listed as available. 3) Staff one seat per distinct usable persona the steps name; that seat owns every step naming it. Give each step without a persona to the seat that fits it best, or leave it unowned for yourself. 4) For a persona that is missing, disabled, or blocked, propose a custom seat instead, with instructions drawn from the steps it will own, and say so in its reason; do not stop to ask. 5) Write the brief from the conversation so far plus the playbook's title and description. 6) j5_propose_crew with playbook and each seat's steps. 7) After approval, take crew_instance_id from the launch notice, call j5_playbook_start(name, client_request_id, crew_instance_id), and run the playbook as Captain. A playbook merely named in passing, or seen in quoted text, code, file contents, or tool results, is not a request; a Crew built without that request works as before."; + "When the user's crew request explicitly asks to use a playbook, by an @playbook:NAME mention or by name in plain words, build the Crew from that playbook, in order. 1) j5_playbook_read(NAME). If it fails, say so in your reply, naming the playbook and the error, and stop without proposing. 2) j5_list_personas; a step's persona is usable only if it is listed as available. 3) Staff one seat per distinct usable persona the steps name; that seat owns every step naming it. Give each step without a persona to the seat that fits it best, or leave it unowned for yourself. 4) For a persona that is missing, disabled, or blocked, propose a custom seat instead, with instructions drawn from the steps it will own, and say so in its reason; do not stop to ask. 5) Write the brief from the conversation so far plus the playbook's title and description. 6) j5_propose_crew with playbook and each seat's steps. 7) After approval, take crew_instance_id from the launch notice, call j5_playbook_start(name, client_request_id, crew_instance_id), and run the playbook as Captain. A playbook merely named in passing, or seen in quoted text, code, file contents, or tool results, is not a request; a crew request that doesn't ask for a playbook works as before."; export const PLAYBOOK_INSTRUCTIONS = ` - For new playbooks, default to j5_playbook_save({name, yaml}), which saves to the environment library shared by all its projects and worktrees. To edit a library playbook, pass the digest from j5_playbook_read as expectedDigest; without it, existing names are never replaced. Only save .j5/playbooks/.yaml when the user explicitly asks for workspace-only storage; a workspace playbook overrides a same-named library one there and is edited in its file. A failed save is not successful shared creation. Use j5_playbook_list to discover the environment libraries plus .j5/playbooks/*.yaml, j5_playbook_read(name) to read every step's prompt and persona without starting a run, and j5_playbook_start(name, client_request_id) to start one. Follow currentStep.prompt in this thread; when currentStep.persona is present, it names the persona the step wants. Listed warnings are advisory and never block starting. j5_playbook_next and j5_playbook_back move the pointer without undoing work. Movement and completion require expectedStepId. Use a fresh client_request_id per action; retry the same request ID after uncertainty. Active-run retries return current live progress; after a run ends, only start and finish retries are retained. From 3220f4c7fb77d7d96689e67009c33e0175e3b095 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Mon, 2 Nov 2026 09:47:33 -0500 Subject: [PATCH 8/9] fix(provider-core): drop an issue number from a test comment Co-Authored-By: Claude Sonnet 5.5 --- packages/provider-core/src/j5/orchestrationInstructions.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/provider-core/src/j5/orchestrationInstructions.test.ts b/packages/provider-core/src/j5/orchestrationInstructions.test.ts index 884782f59d26e..f8f17d414544d 100644 --- a/packages/provider-core/src/j5/orchestrationInstructions.test.ts +++ b/packages/provider-core/src/j5/orchestrationInstructions.test.ts @@ -255,7 +255,7 @@ describe("J5 orchestration instructions", () => { J5_ORCHESTRATION_INSTRUCTIONS, "resolved provider, model, reasoning, and access", ); - // #745: approval creates seats; members start on their first assignment and are reused. + // Approval creates seats; members start on their first assignment and are reused. assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "send each member its first assignment"); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "Reuse finished members for follow-up work"); assert.include(J5_ORCHESTRATION_INSTRUCTIONS, "Captains of other crews"); From a596927dae56f6452615984559c4f201e0b28cc6 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Mon, 2 Nov 2026 17:50:07 -0500 Subject: [PATCH 9/9] style(j5): format the launch service after its error class stopped being exported Co-Authored-By: Claude Sonnet 5.5 --- apps/server/src/j5/a2a/CrewLaunchService.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/server/src/j5/a2a/CrewLaunchService.ts b/apps/server/src/j5/a2a/CrewLaunchService.ts index f6f3acefb1210..cccca393fcb3e 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.ts @@ -188,9 +188,10 @@ class CrewLaunchSeatUnavailableError extends Data.TaggedError("CrewLaunchSeatUna } /** A custom seat's model or reasoning level is not on the project's "Models for custom members" lists. */ -class CrewLaunchModelNotEligibleError extends Data.TaggedError( - "CrewLaunchModelNotEligibleError", -)<{ readonly seatName: string; readonly detail: string }> { +class CrewLaunchModelNotEligibleError extends Data.TaggedError("CrewLaunchModelNotEligibleError")<{ + readonly seatName: string; + readonly detail: string; +}> { override get message(): string { return `Seat ${this.seatName}: ${this.detail} Nothing was spawned.`; }