diff --git a/FORK.md b/FORK.md index 1e7c0837a2fc..1d145163026b 100644 --- a/FORK.md +++ b/FORK.md @@ -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 peer delivery and durable steer outcomes: `apps/server/src/j5/a2a/DeliveryTransport.ts` 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) as run-pinned native steers. 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 idle agent with a held queue otherwise resumes the queue and joins the back (register D4), with two exceptions where it waits unsent with `A2ADeliveryHeldError` instead: the thread stopped on a usage limit, or its latest executed run failed or was interrupted preparing a worktree (`workspacePreparation.type === "worktree"`) and the thread has no `worktreePath`. 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 peer delivery and durable steer outcomes: `apps/server/src/j5/a2a/DeliveryTransport.ts` 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) as run-pinned native steers. 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. 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 5678785286d4..aced9ec6a553 100644 --- a/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts +++ b/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts @@ -94,6 +94,7 @@ import { latestSteerableRun, ThreadManagementService, type ThreadManagementSendMode, + isActiveRun, } from "../../orchestration-v2/ThreadManagementService.ts"; import { ThreadLifecycleService, @@ -128,6 +129,7 @@ import { import { deliveryCommandId } from "./DeliveryTransport.ts"; import { EffectOutboxV2 } from "../../orchestration-v2/EffectOutbox.ts"; import { ProviderRuntimeRecoveryService } from "../../orchestration-v2/ProviderRuntimeRecoveryService.ts"; +import { limitRecoveryCommand } from "../../orchestration-v2/UsageLimitRecoveryWorker.ts"; import { ProviderSessionManagerV2 } from "../../orchestration-v2/ProviderSessionManager.ts"; import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; import * as ThreadSettlement from "../../orchestration-v2/ThreadSettlementService.ts"; @@ -3470,6 +3472,311 @@ it.effect("resumes an idle receiver's held queue so a delivery runs after the he }), ); +/** Leaves a target idle after its turn stopped on a usage limit, with one unheld message queued if asked. */ +const idleOnUsageLimit = Effect.fn("A2AIntegration.idleOnUsageLimit")(function* ( + harness: DeliveryHarness, + target: { readonly projectId: ProjectId; readonly threadId: ThreadId }, + queued: boolean, +) { + const threads = yield* ThreadManagementService; + yield* startBusyTurn(target); + const earlier = queued + ? yield* threads.sendToThread({ + projectId: target.projectId, + threadId: target.threadId, + commandId: CommandId.make(`command:limited:earlier:${target.threadId}`), + messageId: MessageId.make(`message:limited:earlier:${target.threadId}`), + text: "Earlier work", + attachments: [], + mode: "queue", + createdBy: "user", + creationSource: "web", + }) + : undefined; + const resetAt = DateTime.formatIso(DateTime.add(yield* DateTime.now, { minutes: 1 })); + yield* finishTestTurn(harness, target.threadId, { + class: "usage_limit", + message: "Usage limit reached.", + code: null, + retryable: null, + resetAt, + }); + return { earlierRunId: earlier?.run.id, resetAt }; +}); + +it.effect( + "holds a delivery to a usage-limited agent with nothing queued, and tells its sender", + () => + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* Effect.gen(function* () { + const target = yield* seedTarget("limited-empty"); + const threads = yield* ThreadManagementService; + const transport = yield* A2ADeliveryTransport; + yield* idleOnUsageLimit(harness, target, false); + + const error = yield* transport.deliverAgent(target.delivery).pipe(Effect.flip); + + assert.instanceOf(error, A2ADeliveryHeldError); + const after = yield* threads.getThreadProjection(target.threadId); + assert.isFalse( + after.messages.some((row) => row.id === deliveryMessageId(target.messageId)), + ); + assert.isFalse(after.runs.some((run) => run.status === "queued" || isActiveRun(run))); + assert.equal( + yield* sendNoticeTo("limited-empty", target), + `${target.receiverId} hit its provider's usage limit and is paused until a person continues it. Your message is saved and will run then, in the order it was sent. Don't send it again.`, + ); + }).pipe(Effect.provide(makeLifecycleTestLayer(harness))); + }), +); + +it.effect.each(["upstream", "a person"] as const)( + "holds a delivery behind messages queued before a usage limit and runs it after them once %s continues the agent", + (continuedBy) => + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* Effect.gen(function* () { + const target = yield* seedTarget(`limited-queued-${continuedBy.replace(" ", "-")}`); + const threads = yield* ThreadManagementService; + const orchestrator = yield* OrchestratorV2; + const transport = yield* A2ADeliveryTransport; + const { earlierRunId, resetAt } = yield* idleOnUsageLimit(harness, target, true); + const limited = yield* threads.getThreadProjection(target.threadId); + const earlier = limited.runs.find((run) => run.id === earlierRunId); + assert.equal(earlier?.status, "queued"); + assert.isNotTrue(earlier?.queueHeld); + + assert.instanceOf( + yield* transport.deliverAgent(target.delivery).pipe(Effect.flip), + A2ADeliveryHeldError, + ); + assert.isFalse( + (yield* threads.getThreadProjection(target.threadId)).messages.some( + (row) => row.id === deliveryMessageId(target.messageId), + ), + ); + + if (continuedBy === "upstream") { + // What the usage-limit sweep does: arm the recovery, then continue past the reset. + const shell = () => + orchestrator + .getShellSnapshot() + .pipe( + Effect.map((snapshot) => + snapshot.threads.find((thread) => thread.id === target.threadId)!, + ), + ); + yield* threads.dispatch( + limitRecoveryCommand( + yield* shell(), + true, + DateTime.toEpochMillis(yield* DateTime.now), + )!, + ); + yield* TestClock.adjust("2 minutes"); + yield* threads.dispatch( + limitRecoveryCommand(yield* shell(), true, Date.parse(resetAt) + 1)!, + ); + } else { + yield* threads.sendToThread({ + projectId: target.projectId, + threadId: target.threadId, + commandId: CommandId.make("command:limited-queued:person-continue"), + messageId: MessageId.make("message:limited-queued:person-continue"), + text: "Carry on.", + attachments: [], + mode: "auto", + createdBy: "user", + creationSource: "web", + }); + } + yield* startPendingTestTurn(target.threadId); + + yield* transport.deliverAgent(target.delivery); + + const continued = yield* threads.getThreadProjection(target.threadId); + const delivered = continued.runs.find( + (run) => run.userMessageId === deliveryMessageId(target.messageId), + ); + assert.equal(delivered?.status, "queued"); + assert.isAbove( + delivered!.queuePosition!, + continued.runs.find((run) => run.id === earlierRunId)!.queuePosition!, + ); + yield* finishTestTurn(harness, target.threadId); + yield* (yield* OrchestrationEffectWorkerV2).drain(); + const after = yield* threads.getThreadProjection(target.threadId); + assert.notEqual(after.runs.find((run) => run.id === earlierRunId)?.status, "queued"); + assert.equal( + after.runs.find((run) => run.userMessageId === deliveryMessageId(target.messageId)) + ?.status, + "queued", + ); + }).pipe(Effect.provide(makeTestLayer(harness))); + }), +); + +/** The delivery seam with the silence detector, which wakes held deliveries when a run starts. */ +const makeWakeTestLayer = (harness: DeliveryHarness) => + silenceDetectorManualLayer.pipe( + Layer.provideMerge(crewInstanceLayer), + Layer.provideMerge(makeLifecycleTestLayer(harness)), + Layer.provideMerge(serverConfigLayer), + Layer.provideMerge(NodeServices.layer), + ); + +/** A person continues a usage-limited target; returns the stored event of the run it started. */ +const continueByPerson = Effect.fn("A2AIntegration.continueByPerson")(function* (target: { + readonly projectId: ProjectId; + readonly threadId: ThreadId; +}) { + const started = yield* (yield* EventSinkV2).stream({ threadId: target.threadId }).pipe( + Stream.filter( + (stored) => + (stored.event.type === "run.created" || stored.event.type === "run.updated") && + stored.event.payload.status === "starting", + ), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + yield* (yield* ThreadManagementService).sendToThread({ + projectId: target.projectId, + threadId: target.threadId, + commandId: CommandId.make(`command:continue:${target.threadId}`), + messageId: MessageId.make(`message:continue:${target.threadId}`), + text: "Carry on.", + attachments: [], + mode: "auto", + createdBy: "user", + creationSource: "web", + }); + return Option.getOrThrow(yield* Fiber.join(started)); +}); + +const queuePositionOf = Effect.fn("A2AIntegration.queuePositionOf")(function* ( + threadId: ThreadId, + messageId: LedgerMessageId, +) { + const run = (yield* (yield* ThreadManagementService).getThreadProjection(threadId)).runs.find( + (candidate) => candidate.userMessageId === deliveryMessageId(messageId), + ); + return run?.status === "queued" ? run.queuePosition : undefined; +}); + +/** A target stopped on a usage limit and a caller in its project that sends it updates. */ +const limitedTargetWithCaller = Effect.fn("A2AIntegration.limitedTargetWithCaller")(function* ( + harness: DeliveryHarness, + suffix: string, +) { + const send = yield* A2ASendService; + const target = yield* seedTarget(suffix); + const caller = yield* seedTarget( + `${suffix}-caller`, + modelSelection.model, + undefined, + target.ledgerProjectId, + ); + yield* idleOnUsageLimit(harness, target, false); + const sendUpdate = (name: string) => + send.send({ + commandId: CommCommandId.make(`command:j5-a2a-delivery-${suffix}-${name}`), + senderThreadId: caller.threadId, + to: target.receiverId, + message: `Update ${name}`, + acceptedAt: "2026-09-24T00:00:00.000Z", + }); + return { target, sendUpdate }; +}); + +it.effect("hands held messages over in send order, together, as soon as the agent continues", () => + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* Effect.gen(function* () { + const worker = yield* A2ADeliveryWorker; + const { target, sendUpdate } = yield* limitedTargetWithCaller(harness, "wake-order"); + + // A is held and rechecked until its next recheck is eight minutes out. + const a = yield* sendUpdate("a"); + yield* worker.drain; + for (let attempt = 1; attempt <= 3; attempt++) { + yield* TestClock.adjust(heldQueueRecheckMs(attempt)); + yield* worker.drain; + } + // B, sent later, is held with its first recheck a minute out: before A's. + const b = yield* sendUpdate("b"); + yield* worker.drain; + assert.isUndefined(yield* queuePositionOf(target.threadId, a.messageId)); + assert.isUndefined(yield* queuePositionOf(target.threadId, b.messageId)); + + const started = yield* continueByPerson(target); + yield* (yield* A2ASilenceDetector).handleStoredEvent(started); + // No time passes: the wake hands both over now, A first. + yield* worker.drain; + const positionA = yield* queuePositionOf(target.threadId, a.messageId); + const positionB = yield* queuePositionOf(target.threadId, b.messageId); + assert.isDefined(positionA); + assert.isDefined(positionB); + assert.isBelow(positionA!, positionB!); + }).pipe(Effect.provide(makeWakeTestLayer(harness))); + }), +); + +it.effect("keeps a message sent just after the agent continues behind the ones held for it", () => + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* Effect.gen(function* () { + const worker = yield* A2ADeliveryWorker; + const { target, sendUpdate } = yield* limitedTargetWithCaller(harness, "wake-after-lift"); + const a = yield* sendUpdate("a"); + yield* worker.drain; + + const started = yield* continueByPerson(target); + // Sent between the lift and the wake: it waits behind A instead of overtaking it. + const c = yield* sendUpdate("c"); + yield* worker.drain; + assert.isUndefined(yield* queuePositionOf(target.threadId, a.messageId)); + assert.isUndefined(yield* queuePositionOf(target.threadId, c.messageId)); + + yield* (yield* A2ASilenceDetector).handleStoredEvent(started); + yield* worker.drain; + const positionA = yield* queuePositionOf(target.threadId, a.messageId); + const positionC = yield* queuePositionOf(target.threadId, c.messageId); + assert.isDefined(positionA); + assert.isDefined(positionC); + assert.isBelow(positionA!, positionC!); + }).pipe(Effect.provide(makeWakeTestLayer(harness))); + }), +); + +it.effect( + "starts a delivery at once on an idle agent whose last turn failed for another reason", + () => + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* Effect.gen(function* () { + const target = yield* seedTarget("failed-other"); + const threads = yield* ThreadManagementService; + const transport = yield* A2ADeliveryTransport; + yield* startBusyTurn(target); + yield* finishTestTurn(harness, target.threadId, { + class: "provider_error", + message: "The provider failed.", + code: null, + retryable: null, + }); + + yield* transport.deliverAgent(target.delivery); + + const delivered = (yield* threads.getThreadProjection(target.threadId)).runs.find( + (run) => run.userMessageId === deliveryMessageId(target.messageId), + ); + assert.isDefined(delivered); + assert.isTrue(isActiveRun(delivered!)); + }).pipe(Effect.provide(makeTestLayer(harness))); + }), +); + it.effect("keeps a delivery unsent while a usage limit blocks the receiver's held queue", () => Effect.gen(function* () { const harness = yield* makeHarness; diff --git a/apps/server/src/j5/a2a/DeliveryTransport.ts b/apps/server/src/j5/a2a/DeliveryTransport.ts index 43b495b7c2c8..ff07dd65d397 100644 --- a/apps/server/src/j5/a2a/DeliveryTransport.ts +++ b/apps/server/src/j5/a2a/DeliveryTransport.ts @@ -85,11 +85,12 @@ export class A2ADeliveryHeldError extends Schema.TaggedError run?.status === "queued" && run.queueHeld === true ? Effect.fail( - new A2ADeliveryHeldError({ participantId: input.receiverId, runId: run.id }), + new A2ADeliveryHeldError({ + participantId: input.receiverId, + waitingOn: `run ${run.id}`, + }), ) : Effect.void; // Upstream starts a message sent to an idle thread at once, even past a held queue, and // leaves the held messages waiting. A delivery keeps its place instead: it resumes the // queue, so the held messages run first and it joins the back (#580). A retry of an - // accepted delivery never resumes again. Upstream refuses to resume a thread stopped by - // a usage limit, so that delivery waits unsent, as a held one, until the thread continues. - // So does one whose worktree setup failed (`idleQueueHold`). + // accepted delivery never resumes again. A delivery to a thread stopped by a usage limit + // waits unsent until the thread continues, held queue or not: upstream would start it + // into the same limit, or leave it behind messages that wait for the continue (#718). + // Delivered then, it joins the back of the queue. One whose worktree setup failed waits + // when messages are held there (`idleQueueHold`); upstream holds any other itself. const heldQueueRun = target.runs.find( (run) => run.status === "queued" && run.queueHeld === true, ); + const idle = !alreadyAccepted && !target.runs.some(isActiveRun); + const hold = idle ? idleQueueHold(target) : undefined; const queueBehindHeld = - alreadyAccepted || heldQueueRun === undefined || target.runs.some(isActiveRun) + !idle || (heldQueueRun === undefined && hold?.type !== "usage_limit") ? Effect.void - : idleQueueHold(target) !== undefined + : hold !== undefined ? Effect.fail( new A2ADeliveryHeldError({ participantId: input.receiverId, - runId: heldQueueRun.id, + waitingOn: `run ${heldQueueRun?.id ?? hold.run.id}`, }), ) : orchestrator.dispatch({ diff --git a/apps/server/src/j5/a2a/DeliveryWorker.test.ts b/apps/server/src/j5/a2a/DeliveryWorker.test.ts index 933f5259b3f3..4cb0ba0b4834 100644 --- a/apps/server/src/j5/a2a/DeliveryWorker.test.ts +++ b/apps/server/src/j5/a2a/DeliveryWorker.test.ts @@ -29,6 +29,7 @@ import { layerWithHooks as deliveryWorkerLayerWithHooks, } from "./DeliveryWorker.ts"; import { + A2ADeliveryHeldError, A2ADeliveryTransport, A2ADeliveryTransportError, deliveryCommandId, @@ -687,6 +688,332 @@ it.effect("keeps a message queued behind a held receiver queue undelivered until }), ); +type ScriptedStep = "held" | "fail"; + +/** + * A local transport that answers each message from its script, one step per attempt, and lands + * it once the steps run out. It records what landed, in order. + */ +const scriptedTransport = ( + script: Ref.Ref>>, + delivered: Ref.Ref>, +): A2ADeliveryTransportShape => ({ + deliverAgent: (input) => + Effect.gen(function* () { + const steps = yield* Ref.get(script); + const [step, ...rest] = steps.get(input.message) ?? []; + yield* Ref.set(script, new Map(steps).set(input.message, rest)); + if (step === "held") { + return yield* new A2ADeliveryHeldError({ + participantId: input.receiverId, + waitingOn: "run test", + }); + } + if (step === "fail") { + return yield* new A2ADeliveryTransportError({ + operation: "test delivery", + cause: "offline", + }); + } + yield* Ref.update(delivered, (all) => [...all, input.message]); + }), + cancelAgent: () => Effect.succeed("cancelled" as const), + deliverPeer: () => Effect.die("peer delivery is not under test"), + deliverHuman: () => Effect.void, +}); + +const otherSender: AgentParticipant = { + kind: "agent", + id: ParticipantId.make("agent:delivery-other-sender"), + threadId: ThreadId.make("thread:delivery-other-sender"), +}; + +/** Two senders in their own projects, and the receiver in the first, which has more history. */ +const seedTwoProjects = Effect.fn("test.j5.a2a.delivery.seedTwoProjects")(function* () { + yield* runMigrations(); + yield* runJ5A2AMigrations(); + const ledgerService = yield* A2ALedger; + const busy = LedgerProjectId.make("project:delivery:busy"); + const fresh = LedgerProjectId.make("project:delivery:fresh"); + yield* ledgerService.ensureProject({ projectId: busy, createdAt: timestamp }); + yield* ledgerService.ensureProject({ projectId: fresh, createdAt: timestamp }); + yield* join(busy, receiver, "two-projects-receiver"); + yield* join(busy, sender, "two-projects-sender"); + // History that puts the busy ledger's sequence far ahead of the fresh one's. + for (let index = 0; index < 8; index++) { + yield* join( + busy, + { + kind: "machine", + id: ParticipantId.make(`machine:filler-${index}`), + name: `filler ${index}`, + }, + `two-projects-filler-${index}`, + ); + } + yield* join(fresh, otherSender, "two-projects-other-sender"); +}); + +const sendAt = (from: AgentParticipant, name: string, acceptedAt: string) => + Effect.gen(function* () { + return yield* (yield* A2ASendService).send({ + commandId: CommCommandId.make(`command:delivery:order:${name}`), + senderThreadId: from.threadId, + to: receiver.id, + message: name, + acceptedAt, + }); + }); + +it.effect.each([ + ["a millisecond apart", "2026-08-16T12:00:02.000Z"], + ["in the same millisecond", "2026-08-16T12:00:01.000Z"], +] as const)("keeps send order to one agent across projects, sent %s", ([, bAcceptedAt]) => + Effect.gen(function* () { + const script = yield* Ref.make>>( + new Map([["A", ["held"]]]), + ); + const delivered = yield* Ref.make>([]); + yield* Effect.gen(function* () { + yield* seedTwoProjects(); + const worker = yield* A2ADeliveryWorker; + const sql = yield* SqlClient.SqlClient; + // A is accepted first, from the project with the longer ledger, and held. + const a = yield* sendAt(sender, "A", "2026-08-16T12:00:01.000Z"); + yield* worker.drain; + // The hold lifts; B is sent from the fresh project before anything wakes A. + const b = yield* sendAt(otherSender, "B", bAcceptedAt); + const seqs = yield* sql<{ readonly message_id: string; readonly sent_seq: number }>` + SELECT message_id, sent_seq FROM j5_a2a_delivery ORDER BY sent_seq + `; + assert.deepStrictEqual( + seqs.map((row) => row.message_id), + [b.messageId, a.messageId], + "B's own ledger numbers it before A", + ); + yield* worker.drain; + assert.deepStrictEqual(yield* Ref.get(delivered), []); + + yield* worker.wake(receiver.id); + yield* worker.drain; + assert.deepStrictEqual(yield* Ref.get(delivered), ["A", "B"]); + }).pipe(Effect.provide(makeTestLayer(scriptedTransport(script, delivered)))); + }), +); + +it.effect("does not count waiting behind another message toward a delivery's alarm", () => + Effect.gen(function* () { + const script = yield* Ref.make>>( + new Map([ + ["A", ["held", "held"]], + ["B", ["fail"]], + ]), + ); + const delivered = yield* Ref.make>([]); + yield* Effect.gen(function* () { + yield* seedTwoProjects(); + const worker = yield* A2ADeliveryWorker; + yield* sendAt(sender, "A", "2026-08-16T12:00:01.000Z"); + yield* sendAt(sender, "B", "2026-08-16T12:00:02.000Z"); + // A is held twice, and B waits behind it twice without reaching the transport. + yield* worker.drain; + yield* TestClock.adjust(heldQueueRecheckMs(1)); + yield* worker.drain; + // A lands on its next recheck, and B's first transport attempt fails. + yield* TestClock.adjust(heldQueueRecheckMs(2)); + yield* worker.drain; + assert.deepStrictEqual(yield* Ref.get(delivered), ["A"]); + assert.lengthOf(yield* worker.listAlarms, 0); + // One transport failure is retried, not alarmed. + yield* TestClock.adjust("250 millis"); + yield* worker.drain; + assert.deepStrictEqual(yield* Ref.get(delivered), ["A", "B"]); + assert.lengthOf(yield* worker.listAlarms, 0); + }).pipe(Effect.provide(makeTestLayer(scriptedTransport(script, delivered)))); + }), +); + +it.effect("tells the sender how many times the transport failed, not how often it waited", () => + Effect.gen(function* () { + const script = yield* Ref.make>>( + new Map([ + ["A", ["held", "held"]], + ["B", ["fail", "fail", "fail"]], + ]), + ); + const delivered = yield* Ref.make>([]); + yield* Effect.gen(function* () { + yield* seedTwoProjects(); + const worker = yield* A2ADeliveryWorker; + yield* sendAt(sender, "A", "2026-08-16T12:00:01.000Z"); + yield* sendAt(sender, "B", "2026-08-16T12:00:02.000Z"); + // B waits twice behind A, then fails three times in transport once A lands. + yield* worker.drain; + yield* TestClock.adjust(heldQueueRecheckMs(1)); + yield* worker.drain; + yield* TestClock.adjust(heldQueueRecheckMs(2)); + yield* worker.drain; + yield* TestClock.adjust("250 millis"); + yield* worker.drain; + yield* TestClock.adjust("500 millis"); + yield* worker.drain; + assert.lengthOf(yield* worker.listAlarms, 1); + const notice = (yield* Ref.get(delivered)).find((text) => text.includes("delivery failed")); + assert.include(notice, "delivery failed 3 times"); + }).pipe(Effect.provide(makeTestLayer(scriptedTransport(script, delivered)))); + }), +); + +const secondReceiver: AgentParticipant = { + kind: "agent", + id: ParticipantId.make("agent:delivery-second-receiver"), + threadId: ThreadId.make("thread:delivery-second-receiver"), +}; + +it.effect("wakes a held delivery early but leaves one backing off after a transport failure", () => + Effect.gen(function* () { + const script = yield* Ref.make>>( + new Map([ + ["Backing off", ["fail"]], + ["Held", ["held"]], + ]), + ); + const delivered = yield* Ref.make>([]); + yield* Effect.gen(function* () { + yield* seedTwoProjects(); + yield* join(LedgerProjectId.make("project:delivery:busy"), secondReceiver, "second-receiver"); + const worker = yield* A2ADeliveryWorker; + const sql = yield* SqlClient.SqlClient; + const backingOff = yield* sendAt(sender, "Backing off", "2026-08-16T12:00:01.000Z"); + yield* (yield* A2ASendService).send({ + commandId: CommCommandId.make("command:delivery:order:held-second"), + senderThreadId: sender.threadId, + to: secondReceiver.id, + message: "Held", + acceptedAt: "2026-08-16T12:00:01.000Z", + }); + yield* worker.drain; + assert.deepStrictEqual(yield* Ref.get(delivered), []); + + // Both receivers wake before the failed delivery's retry is due. + yield* worker.wake(receiver.id); + yield* worker.wake(secondReceiver.id); + yield* worker.drain; + assert.deepStrictEqual(yield* Ref.get(delivered), ["Held"]); + const attempts = yield* sql<{ readonly attempts: number }>` + SELECT attempts FROM j5_a2a_delivery WHERE message_id = ${backingOff.messageId} + `; + assert.equal(attempts[0]?.attempts, 1, "a wake does not spend a transport retry"); + + yield* TestClock.adjust("250 millis"); + yield* worker.drain; + assert.deepStrictEqual(yield* Ref.get(delivered), ["Held", "Backing off"]); + }).pipe(Effect.provide(makeTestLayer(scriptedTransport(script, delivered)))); + }), +); + +it.effect("hands the next message over as soon as the one it waited behind alarms", () => + Effect.gen(function* () { + const script = yield* Ref.make>>( + new Map([["A", ["fail", "fail", "fail"]]]), + ); + const delivered = yield* Ref.make>([]); + yield* Effect.gen(function* () { + yield* seedTwoProjects(); + const worker = yield* A2ADeliveryWorker; + yield* sendAt(sender, "A", "2026-08-16T12:00:01.000Z"); + yield* sendAt(sender, "B", "2026-08-16T12:00:02.000Z"); + yield* worker.drain; + yield* TestClock.adjust("250 millis"); + yield* worker.drain; + // A's third failure alarms it, and B follows at once instead of on its recheck. + yield* TestClock.adjust("500 millis"); + yield* worker.drain; + assert.lengthOf(yield* worker.listAlarms, 1); + // A's sender is told of the alarm too, after B lands. + assert.equal((yield* Ref.get(delivered))[0], "B"); + }).pipe(Effect.provide(makeTestLayer(scriptedTransport(script, delivered)))); + }), +); + +it.effect("hands the next message over as soon as the one it waited behind is cancelled", () => + Effect.gen(function* () { + const script = yield* Ref.make>>( + new Map([["A", ["held"]]]), + ); + const delivered = yield* Ref.make>([]); + yield* Effect.gen(function* () { + yield* seedTwoProjects(); + const worker = yield* A2ADeliveryWorker; + yield* sendAt(sender, "A", "2026-08-16T12:00:01.000Z"); + yield* sendAt(otherSender, "B", "2026-08-16T12:00:02.000Z"); + yield* worker.drain; + assert.deepStrictEqual(yield* Ref.get(delivered), []); + // A's sender leaves, which cancels A; B no longer waits behind it. + yield* worker.cancelParticipantDeliveries(sender.id); + yield* worker.drain; + assert.deepStrictEqual(yield* Ref.get(delivered), ["B"]); + }).pipe(Effect.provide(makeTestLayer(scriptedTransport(script, delivered)))); + }), +); + +it.effect("hands the next message over as soon as the one it waited behind lands", () => + Effect.gen(function* () { + const delivered = yield* Ref.make>([]); + const failNext = yield* Ref.make(true); + const transport: A2ADeliveryTransportShape = { + // The first attempt fails in transport; every later one lands. + deliverAgent: (input) => + Ref.getAndSet(failNext, false).pipe( + Effect.flatMap((fail) => + fail + ? Effect.fail( + new A2ADeliveryTransportError({ operation: "test delivery", cause: "offline" }), + ) + : Ref.update(delivered, (all) => [...all, input.message]), + ), + ), + cancelAgent: () => Effect.succeed("cancelled" as const), + deliverPeer: () => Effect.die("peer delivery is not under test"), + deliverHuman: () => Effect.void, + }; + yield* Effect.gen(function* () { + yield* runMigrations(); + yield* runJ5A2AMigrations(); + const worker = yield* A2ADeliveryWorker; + const sql = yield* SqlClient.SqlClient; + const sendService = yield* A2ASendService; + const projectId = LedgerProjectId.make("project:delivery:in-order"); + yield* (yield* A2ALedger).ensureProject({ projectId, createdAt: timestamp }); + yield* join(projectId, sender, "in-order-sender"); + yield* join(projectId, receiver, "in-order-receiver"); + const sendUpdate = (name: string) => + sendService.send({ + commandId: CommCommandId.make(`command:delivery:in-order:${name}`), + senderThreadId: sender.threadId, + to: receiver.id, + message: `Update ${name}`, + acceptedAt: timestamp, + }); + yield* sendUpdate("a"); + const b = yield* sendUpdate("b"); + + // A fails in transport and retries soon; B waits behind it on the slower held recheck. + yield* worker.drain; + assert.deepStrictEqual(yield* Ref.get(delivered), []); + + // Only A's retry is due, yet B follows it at once. + yield* TestClock.adjust("250 millis"); + yield* worker.drain; + assert.deepStrictEqual(yield* Ref.get(delivered), ["Update a", "Update b"]); + const row = yield* sql<{ readonly status: string }>` + SELECT status FROM j5_a2a_delivery WHERE message_id = ${b.messageId} + `; + assert.equal(row[0]?.status, "delivered"); + }).pipe(Effect.provide(makeTestLayer(transport))); + }), +); + it.effect("delivers a machine's send to its agent receiver instead of withdrawing it", () => Effect.gen(function* () { const delivered = yield* Ref.make>([]); diff --git a/apps/server/src/j5/a2a/DeliveryWorker.ts b/apps/server/src/j5/a2a/DeliveryWorker.ts index 9c9398c211fb..18df6333ee2d 100644 --- a/apps/server/src/j5/a2a/DeliveryWorker.ts +++ b/apps/server/src/j5/a2a/DeliveryWorker.ts @@ -21,7 +21,7 @@ import type * as Scope from "effect/Scope"; import { reportedLabel } from "./peerLabel.ts"; import config from "./delivery-config.v1.json" with { type: "json" }; import { - type A2ADeliveryHeldError, + A2ADeliveryHeldError, type A2ADeliveryRefusedError, A2ADeliveryTransport, A2ADeliveryTransportError, @@ -82,6 +82,10 @@ interface DeliveryRow { readonly message_text: string; readonly status: "pending" | "retry_scheduled" | "delivered" | "alarmed"; readonly attempts: number; + /** Of those attempts, the rechecks while the receiver held it. */ + readonly held_attempts: number; + /** The order it was accepted on this server, across projects. */ + readonly accept_order: number; readonly created_at: string; /** Set when the row came in from a peer server; NULL means the origin is `project_id` here. */ readonly origin_project_id: string | null; @@ -127,6 +131,8 @@ export const noopHooks = Layer.succeed( export interface A2ADeliveryWorkerShape { readonly notify: Effect.Effect; + /** The agent may take messages again: attempt its waiting deliveries now, in send order. */ + readonly wake: (participantId: ParticipantId) => Effect.Effect; readonly cancelParticipantDeliveries: ( participantId: ParticipantId, ) => Effect.Effect; @@ -173,7 +179,8 @@ const workerError = (operation: string) => (cause: unknown) => new A2ADeliveryWorkerError({ operation, cause }); /** - * A held receiver queue waits for a person; recheck it slowly and never alarm on it. + * A held delivery waits for its receiver to be resumed or continued, which wakes it (`wake`); + * this slow recheck is the fallback, and it never alarms. * Each recheck appends a ledger event, so the interval doubles from one minute to a * fifteen-minute cap: a long hold costs about four events an hour, not sixty. */ @@ -244,6 +251,12 @@ const makeLayer = (daemon: boolean) => SELECT environment_id FROM j5_a2a_peer WHERE link_mode = 'store' ) )`; + const deliveryColumns = sql` + project_id, message_id, sent_seq, sender_id, receiver_id, receiver_project_id, + exchange_id, exchange_role, envelope_channel, correlation_id, message_text, status, + attempts, held_attempts, accept_order, created_at, origin_project_id, + origin_environment_id, receiver_environment_id + `; const storedForPollingPeer = sql`( receiver_environment_id IN (SELECT environment_id FROM j5_a2a_peer WHERE link_mode = 'store') )`; @@ -324,6 +337,28 @@ const makeLayer = (daemon: boolean) => createdAt: row.created_at, }); } else { + // Messages reach an agent in the order they were accepted, from any project: this one + // waits while an earlier one to the same agent is still waiting, held or in retry. A + // wake hands them over together, so it costs nothing once the hold lifts. + const earlier = yield* sql<{ readonly message_id: string }>` + SELECT message_id FROM j5_a2a_delivery + WHERE receiver_id = ${row.receiver_id} + AND receiver_environment_id IS NULL + AND status IN ('pending', 'retry_scheduled') + AND accept_order < ${row.accept_order} + LIMIT 1 + `.pipe( + Effect.mapError( + (cause) => + new A2ADeliveryTransportError({ operation: "read earlier deliveries", cause }), + ), + ); + if (earlier[0] !== undefined) { + return yield* new A2ADeliveryHeldError({ + participantId: row.receiver_id, + waitingOn: `earlier message ${earlier[0].message_id}`, + }); + } yield* appendReceiverEntry(row); // Canonical references live in the immutable sent fact. Reading that // indexed row avoids a second projection and a schema migration. @@ -448,13 +483,17 @@ const makeLayer = (daemon: boolean) => const failedAt = DateTime.formatIso(failedAtDate); // A held queue is not a failed delivery: it stays retry_scheduled, never delivered or alarmed. const held = heldError(cause); + // Rechecks while held never reached the transport, so only the others count. + const transportAttempt = attempt - row.held_attempts; const alarmed = - refusal !== undefined || (held === undefined && attempt >= config.alarmAfterAttempts); + refusal !== undefined || + (held === undefined && transportAttempt >= config.alarmAfterAttempts); const nextAttemptAt = alarmed ? null : DateTime.formatIso( DateTime.add(failedAtDate, { - milliseconds: held !== undefined ? heldQueueRecheckMs(attempt) : backoffMs(attempt), + milliseconds: + held !== undefined ? heldQueueRecheckMs(attempt) : backoffMs(transportAttempt), }), ); const messageId = LedgerMessageId.make(row.message_id); @@ -468,7 +507,7 @@ const makeLayer = (daemon: boolean) => refusal !== undefined ? yield* refusalNotices(row, refusal, failedAt) : alarmed - ? yield* alarmNotices(row, attempt, cause, failedAt) + ? yield* alarmNotices(row, transportAttempt, cause, failedAt) : []; return yield* writer.appendEventsInTransaction({ commandId: commandId("failed", messageId, attempt), @@ -490,6 +529,7 @@ const makeLayer = (daemon: boolean) => : `${refusal.code}: ${refusal.message}`, nextAttemptAt, alarmed, + ...(held === undefined ? {} : { held: true }), }, createdAt: failedAt, }, @@ -712,24 +752,7 @@ const makeLayer = (daemon: boolean) => const runOnceRaw = Effect.gen(function* () { const now = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso)); const rows = yield* sql` - SELECT - project_id, - message_id, - sent_seq, - sender_id, - receiver_id, - receiver_project_id, - exchange_id, - exchange_role, - envelope_channel, - correlation_id, - message_text, - status, - attempts, - created_at, - origin_project_id, - origin_environment_id, - receiver_environment_id + SELECT ${deliveryColumns} FROM j5_a2a_delivery WHERE status IN ('pending', 'retry_scheduled') AND (next_attempt_at IS NULL OR next_attempt_at <= ${now}) @@ -739,6 +762,48 @@ const makeLayer = (daemon: boolean) => `; const row = rows[0]; if (row === undefined) return null; + return yield* attemptRow(row); + }); + const runOnceEffect = runOnceRaw.pipe(Effect.mapError(workerError("run one delivery"))); + const runOnce: A2ADeliveryWorkerShape["runOnce"] = drainPermit.withPermit(runOnceEffect); + + // Receivers that stopped being held. Their held deliveries are attempted at once, in send + // order, instead of on each one's own recheck. One backing off after a transport failure + // keeps its schedule, so a busy receiver's wakes don't spend its retries; the guard holds + // the deliveries behind it meanwhile. + const wokenReceivers = new Set(); + const wake = (participantId: string) => + Effect.sync(() => wokenReceivers.add(participantId)).pipe( + Effect.andThen(Queue.offer(wakeups, undefined)), + Effect.asVoid, + ); + /** A row left the waiting set: the next message to its agent may be waiting behind it. */ + const wakeBehind = (row: DeliveryRow) => + row.receiver_environment_id === null && + !isHumanParticipantId(ParticipantId.make(row.receiver_id)) + ? wake(row.receiver_id) + : Effect.void; + const runWokenEffect = Effect.gen(function* () { + const now = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso)); + const receivers = [...wokenReceivers]; + wokenReceivers.clear(); + const completed: Array = []; + for (const receiverId of receivers) { + const rows = yield* sql` + SELECT ${deliveryColumns} + FROM j5_a2a_delivery + WHERE receiver_id = ${receiverId} + AND receiver_environment_id IS NULL + AND status IN ('pending', 'retry_scheduled') + AND (last_held = 1 OR next_attempt_at IS NULL OR next_attempt_at <= ${now}) + ORDER BY accept_order + `; + for (const row of rows) completed.push(yield* attemptRow(row)); + } + return completed; + }).pipe(Effect.mapError(workerError("run woken deliveries"))); + + const attemptRow = Effect.fn("j5.a2a.delivery.attemptRow")(function* (row: DeliveryRow) { const attempt = row.attempts + 1; if (yield* deliveryUnavailable(row)) { const milestone = yield* cancelDelivery(row, attempt); @@ -780,15 +845,15 @@ const makeLayer = (daemon: boolean) => ? exit.value : yield* recordFailure(row, attempt, exit.cause, refusalOf(exit.cause)); }).pipe(Effect.ensuring(Effect.sync(() => peerAttemptsInFlight.delete(inFlight)))); + if (milestone.state !== "retry_scheduled") yield* wakeBehind(row); yield* PubSub.publish(milestones, milestone); return milestone; }); - const runOnceEffect = runOnceRaw.pipe(Effect.mapError(workerError("run one delivery"))); - const runOnce: A2ADeliveryWorkerShape["runOnce"] = drainPermit.withPermit(runOnceEffect); const drainEffect = Effect.fn("j5.a2a.delivery.drain")(function* () { const completed: Array = []; while (true) { + completed.push(...(yield* runWokenEffect)); const milestone = yield* runOnceEffect; if (milestone === null) return completed; completed.push(milestone); @@ -846,6 +911,7 @@ const makeLayer = (daemon: boolean) => ) { for (const row of rows) { const milestone = yield* cancelDelivery(row, row.attempts + 1); + yield* wakeBehind(row); yield* PubSub.publish(milestones, milestone); } }); @@ -989,6 +1055,7 @@ const makeLayer = (daemon: boolean) => { concurrency: "unbounded", discard: true }, ).pipe(Effect.mapError(workerError("cancel participant deliveries"))), notify: Queue.offer(wakeups, undefined).pipe(Effect.asVoid), + wake, handOutToPeer: (environmentId) => storePermit .withPermit(handOutToPeer(environmentId)) diff --git a/apps/server/src/j5/a2a/LedgerService.ts b/apps/server/src/j5/a2a/LedgerService.ts index efda9d1a6377..9effb3fc261d 100644 --- a/apps/server/src/j5/a2a/LedgerService.ts +++ b/apps/server/src/j5/a2a/LedgerService.ts @@ -223,6 +223,11 @@ const encodeEventPayload = (event: CommEvent) => : encodeJson(event.payload); /** The pending delivery both a local send and a peer-received row project; origin columns are NULL for local sends. */ +/** + * `accept_order` is the order the row was accepted on this server, across every project's ledger, + * which the delivery worker keeps per receiver. The insert takes the next value in one statement, + * and a unique index holds it to one row. + */ const insertPendingDelivery = ( sql: SqlClient.SqlClient, row: { @@ -249,12 +254,13 @@ const insertPendingDelivery = ( project_id, message_id, command_id, sent_seq, sender_id, receiver_id, receiver_project_id, exchange_id, exchange_role, envelope_channel, correlation_id, message_text, status, attempts, last_error, next_attempt_at, delivered_seq, created_at, updated_at, - origin_project_id, origin_environment_id, receiver_environment_id + origin_project_id, origin_environment_id, receiver_environment_id, accept_order ) VALUES ( ${row.projectId}, ${row.messageId}, ${row.commandId}, ${row.sentSeq}, ${row.senderId}, ${row.receiverId}, ${row.receiverProjectId}, ${row.exchangeId}, ${row.exchangeRole}, ${row.envelopeChannel}, ${row.correlationId}, ${row.messageText}, 'pending', 0, NULL, NULL, NULL, ${row.createdAt}, ${row.createdAt}, - ${row.originProjectId}, ${row.originEnvironmentId}, ${row.receiverEnvironmentId} + ${row.originProjectId}, ${row.originEnvironmentId}, ${row.receiverEnvironmentId}, + (SELECT COALESCE(MAX(accept_order), 0) + 1 FROM j5_a2a_delivery) ) `; @@ -588,6 +594,8 @@ export const layer: Layer.Layer< SET status = ${payload.alarmed ? "alarmed" : "retry_scheduled"}, attempts = ${payload.attempt}, + held_attempts = held_attempts + ${payload.held === true ? 1 : 0}, + last_held = ${payload.held === true ? 1 : 0}, last_error = ${payload.error}, next_attempt_at = ${payload.nextAttemptAt}, updated_at = ${event.createdAt} diff --git a/apps/server/src/j5/a2a/Migrations.test.ts b/apps/server/src/j5/a2a/Migrations.test.ts index 9fa19c4be06f..52ee3beaaf91 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -99,6 +99,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () { migration_id: 43, name: "TaskSchedulers" }, { migration_id: 44, name: "QueuedMessageEdits" }, { migration_id: 45, name: "McpClientApprovers" }, + { migration_id: 46, name: "LocalDeliveryOrder" }, ]); assert.deepStrictEqual( migrationEntries.map(([id, name]) => [id, name]), @@ -148,6 +149,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () [43, "TaskSchedulers"], [44, "QueuedMessageEdits"], [45, "McpClientApprovers"], + [46, "LocalDeliveryOrder"], ], ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), @@ -1396,7 +1398,7 @@ it.effect("recreates earlier-shaped crews tables when 14 runs over them", () => applied.map((row) => row.migration_id), [ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, ], ); const memberColumns = yield* sql<{ readonly name: string }>` diff --git a/apps/server/src/j5/a2a/Migrations.ts b/apps/server/src/j5/a2a/Migrations.ts index 491775fcd83e..5565f7c56117 100644 --- a/apps/server/src/j5/a2a/Migrations.ts +++ b/apps/server/src/j5/a2a/Migrations.ts @@ -46,6 +46,7 @@ import Migration0042 from "./migrations/042_EveryoneHereAsks.ts"; import Migration0043 from "./migrations/043_TaskSchedulers.ts"; import Migration0044 from "./migrations/044_QueuedMessageEdits.ts"; import Migration0045 from "./migrations/045_McpClientApprovers.ts"; +import Migration0046 from "./migrations/046_LocalDeliveryOrder.ts"; export const J5_A2A_MIGRATIONS_TABLE = "j5_a2a_migrations"; @@ -102,6 +103,7 @@ export const migrationEntries = [ [43, "TaskSchedulers", Migration0043], [44, "QueuedMessageEdits", Migration0044], [45, "McpClientApprovers", Migration0045], + [46, "LocalDeliveryOrder", Migration0046], ] as const; const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/j5/a2a/SilenceDetector.ts b/apps/server/src/j5/a2a/SilenceDetector.ts index fb692324a279..f05a86bf07e1 100644 --- a/apps/server/src/j5/a2a/SilenceDetector.ts +++ b/apps/server/src/j5/a2a/SilenceDetector.ts @@ -173,6 +173,11 @@ const terminalRun = (stored: OrchestrationV2StoredEvent): OrchestrationV2Run | u : undefined; }; +/** A run starting on a thread: whatever held its agent's messages has lifted. */ +const runStarted = ({ event }: OrchestrationV2StoredEvent) => + (event.type === "run.created" || event.type === "run.updated") && + event.payload.status === "starting"; + const stablePart = (value: string) => encodeURIComponent(value); const noticeIdentity = (projectId: string, exchangeId: string, deliveryMessageId: string) => @@ -699,6 +704,18 @@ const makeLayer = (daemon: boolean) => Effect.provideService(A2ALedgerTransactionWriter, ledgerWriter), ); } + if (runStarted(stored)) { + // Deliveries held while the agent was stopped on a usage limit, its queue was held, + // or its worktree setup had failed go now, together and in send order. + const started = yield* sql<{ readonly participant_id: string }>` + SELECT participant_id FROM j5_a2a_membership + WHERE thread_id = ${stored.event.threadId} AND archived_at IS NULL + `; + for (const membership of started) { + yield* deliveryWorker.wake(ParticipantId.make(membership.participant_id)); + } + return []; + } const run = terminalRun(stored); if (run === undefined || run.completedAt === null) return []; const memberships = yield* sql` diff --git a/apps/server/src/j5/a2a/contracts.ts b/apps/server/src/j5/a2a/contracts.ts index d9f0393d8a94..919daedb8578 100644 --- a/apps/server/src/j5/a2a/contracts.ts +++ b/apps/server/src/j5/a2a/contracts.ts @@ -348,6 +348,8 @@ export const MessageDeliveryFailedPayload = Schema.Struct({ error: Schema.String.check(Schema.isNonEmpty()), nextAttemptAt: Schema.NullOr(Schema.String), alarmed: Schema.Boolean, + /** The receiver held it unsent: a recheck, which never counts toward the alarm. */ + held: Schema.optional(Schema.Boolean), }); export type MessageDeliveryFailedPayload = typeof MessageDeliveryFailedPayload.Type; diff --git a/apps/server/src/j5/a2a/migrations/046_LocalDeliveryOrder.test.ts b/apps/server/src/j5/a2a/migrations/046_LocalDeliveryOrder.test.ts new file mode 100644 index 000000000000..83ad2a55de16 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/046_LocalDeliveryOrder.test.ts @@ -0,0 +1,81 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runJ5A2AMigrations } from "../Migrations.ts"; + +it.effect( + "orders existing deliveries by acceptance and gives waiting ones a fresh retry budget", + () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runJ5A2AMigrations({ toMigrationInclusive: 45 }); + for (const project of ["project:busy", "project:fresh"]) { + yield* sql` + INSERT INTO j5_a2a_project_ledger (project_id, created_at) + VALUES (${project}, '2026-10-24T00:00:00.000Z') + `; + } + const delivery = (row: { + readonly project: string; + readonly message: string; + readonly seq: number; + readonly status: string; + readonly attempts: number; + readonly createdAt: string; + }) => sql` + INSERT INTO j5_a2a_delivery ( + project_id, message_id, command_id, sent_seq, sender_id, receiver_id, receiver_project_id, + exchange_role, correlation_id, message_text, status, attempts, created_at, updated_at, + envelope_channel + ) VALUES ( + ${row.project}, ${row.message}, 'command:upgrade', ${row.seq}, 'agent:sender', + 'agent:receiver', 'project:busy', 'none', 'correlation:upgrade', 'An update', + ${row.status}, ${row.attempts}, ${row.createdAt}, ${row.createdAt}, 'peer' + ) + `; + // Held twice before the upgrade, which counted toward its alarm then. + yield* delivery({ + project: "project:busy", + message: "message:held", + seq: 11, + status: "retry_scheduled", + attempts: 2, + createdAt: "2026-10-24T00:00:01.000Z", + }); + yield* delivery({ + project: "project:fresh", + message: "message:delivered", + seq: 1, + status: "delivered", + attempts: 1, + createdAt: "2026-10-24T00:00:00.000Z", + }); + yield* delivery({ + project: "project:fresh", + message: "message:later", + seq: 2, + status: "pending", + attempts: 0, + createdAt: "2026-10-24T00:00:02.000Z", + }); + + yield* runJ5A2AMigrations(); + + assert.deepStrictEqual( + yield* sql<{ + readonly message_id: string; + readonly accept_order: number; + readonly held_attempts: number; + }>` + SELECT message_id, accept_order, held_attempts FROM j5_a2a_delivery ORDER BY accept_order + `, + [ + { message_id: "message:delivered", accept_order: 1, held_attempts: 0 }, + { message_id: "message:held", accept_order: 2, held_attempts: 2 }, + { message_id: "message:later", accept_order: 3, held_attempts: 0 }, + ], + ); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); diff --git a/apps/server/src/j5/a2a/migrations/046_LocalDeliveryOrder.ts b/apps/server/src/j5/a2a/migrations/046_LocalDeliveryOrder.ts new file mode 100644 index 000000000000..adaa29353cba --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/046_LocalDeliveryOrder.ts @@ -0,0 +1,41 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +// Messages reach an agent on this server in the order they were accepted, from whichever project: +// a delivery waits behind an earlier one to the same agent, and a wake hands an agent's waiting +// deliveries over together. `sent_seq` counts within one project's ledger and `created_at` ties +// within a millisecond, so each row takes the next `accept_order` as it is written. A recheck +// while held is not a transport failure, so it is counted apart from the attempts that alarm. +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`ALTER TABLE j5_a2a_delivery ADD COLUMN accept_order INTEGER`; + yield* sql` + WITH ordered AS ( + SELECT project_id, message_id, + ROW_NUMBER() OVER (ORDER BY created_at, sent_seq, project_id, message_id) AS ordinal + FROM j5_a2a_delivery + ) + UPDATE j5_a2a_delivery SET accept_order = ordered.ordinal + FROM ordered + WHERE ordered.project_id = j5_a2a_delivery.project_id + AND ordered.message_id = j5_a2a_delivery.message_id + `; + yield* sql` + CREATE UNIQUE INDEX j5_a2a_delivery_accept_order_idx ON j5_a2a_delivery (accept_order) + `; + yield* sql` + CREATE INDEX j5_a2a_delivery_local_waiting_idx + ON j5_a2a_delivery (receiver_id, accept_order) + WHERE receiver_environment_id IS NULL AND status IN ('pending', 'retry_scheduled') + `; + yield* sql`ALTER TABLE j5_a2a_delivery ADD COLUMN held_attempts INTEGER NOT NULL DEFAULT 0`; + // Whether the latest attempt was held, so a wake retries it early and leaves a row backing off + // after a transport failure to its schedule. Rows from before this wait for their recheck. + yield* sql`ALTER TABLE j5_a2a_delivery ADD COLUMN last_held INTEGER NOT NULL DEFAULT 0`; + // A row already waiting may have spent attempts on rechecks while held, which earlier counted + // toward its alarm. It starts with a fresh transport budget instead. + yield* sql` + UPDATE j5_a2a_delivery SET held_attempts = attempts + WHERE status IN ('pending', 'retry_scheduled') + `; +}); diff --git a/apps/server/src/j5/a2a/receiverBacklog.ts b/apps/server/src/j5/a2a/receiverBacklog.ts index 82c00c3a4da7..658fe0c39c44 100644 --- a/apps/server/src/j5/a2a/receiverBacklog.ts +++ b/apps/server/src/j5/a2a/receiverBacklog.ts @@ -101,12 +101,10 @@ export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( // 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; - const heldQueue = target.runs.some((run) => run.status === "queued" && run.queueHeld === true); if (latestActiveRun(target) === undefined) { - // An idle receiver takes the message now, resuming a held queue first, unless that - // queue may not be resumed. Upstream holds a message sent after a failed worktree - // setup even without a held queue. + // An idle receiver takes the message now, resuming a held queue first, unless it + // stopped on a usage limit or its worktree setup failed (`idleQueueHold`). const latestRun = latestExecutedRun(target.runs); // Only a failed run's errors can name a usage limit. const { turnItems } = @@ -118,9 +116,7 @@ export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( }); const hold = idleQueueHold({ ...target, turnItems }); if (hold?.type === "worktree_setup_failed") return { type: "queue_held" } as const; - // Without a held queue a delivery starts a turn at once, as upstream starts any message - // to an idle thread, but one already queued waits for the continue. - if (hold?.type !== "usage_limit" || (!heldQueue && sentRun === undefined)) return undefined; + 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; @@ -147,7 +143,8 @@ export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( ) return undefined; // A held queue drains only when someone resumes the thread, not when its turn ends. - if (heldQueue) return { type: "queue_held" } as const; + if (target.runs.some((run) => run.status === "queued" && run.queueHeld === true)) + 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; diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index 3f62879defb6..298153416c57 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -42,7 +42,7 @@ 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. When the message waits on the receiver's held queue or failed worktree setup, or on the usage limit it stopped on, 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 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 no `deliveryNotice`. Attachments work the same for every sender. diff --git a/docs/j5/product/upstream.md b/docs/j5/product/upstream.md index 5c73976e3c55..f5ea953cb778 100644 --- a/docs/j5/product/upstream.md +++ b/docs/j5/product/upstream.md @@ -90,9 +90,9 @@ Letter codes in the Decided lines (SC2, QS1, AR3, and so on) are rulings recorde **Why:** a peer owns nothing about another agent's turn, and upstream's steering was actively harmful. On Claude, a steer aborts the turn and makes the agent report that "the user doesn't want to take this action", a refusal the human never gave. On Cursor, it destroys the turn. The ruling expected this to fold back into upstream: J5 only changed the default value of upstream's own delivery setting, so that it would collapse if upstream shipped a queue option. The GPT 6 models are built to take messages during work. Without the exception, a 36-minute Astra run worked from stale guidance because its peers' updates waited for the end. -**Consequences:** this changes when a message is admitted, not whether the model reads it. Queueing also removed an accidental way of freeing a stuck start, so a queued run's age became something the Fleet page shows. Each advance checks the outbox and follow-up behavior this depends on. Checked on 2026-10-17 against upstream's nightly `v0.1.1-nightly.20261017.3238`, it is still needed: upstream still steers whenever it can (Claude with `priority: "now"`, which cancels sibling tool calls, though it now moves the parent's foreground subagents to the background first; Cursor by interrupting and restarting the turn), and has no GPT 6-specific or asynchronous delivery. **J5 wants to drop this divergence** and follow upstream's delivery once upstream can deliver a message to a running turn without aborting it (Claude) or restarting it (Cursor), and supports the GPT 6 models' in-work messaging. Since 2026-10-11 the divergence is only the default: a sender can ask for a steer or a restart, with upstream's rule that the receiver may not run with broader permissions than the sender, and what is left is that J5 queues where upstream's `auto` would steer. The default is revisited on or after 2027-01-11, because agents are getting better at being steered and that has to reach the cheaper models first. Upstream's Stop holds a thread's queue. A stopped agent's queued messages wait until a person resumes its queue. Upstream starts a message sent to an idle thread at once, past a held queue, and leaves the held messages waiting; a person sees them above the composer and chooses between Resume and a new message. A sender on J5's delivery path sees none of that, so a J5 delivery to an idle agent with a held queue resumes the queue and joins the back: messages run in the order they were sent, whatever held the queue (a Stop, a restart, a provider failure). Upstream refuses to resume a thread that stopped on a usage limit, so a delivery to one waits unsent and joins the back once the thread continues. A delivery to an agent whose last run failed or was interrupted while setting up its worktree, and that has no worktree, is held too, because resuming would run it in the project's own checkout. If messages are already held there, the delivery waits unsent. If none are, upstream accepts it and holds it in the thread's queue, as it holds any message sent then. A person's own message keeps upstream's behavior (Jackson, 2026-10-12). J5 doesn't guard a steer that races a Stop (D5, retired): a peer steer already in flight when the person presses Stop can occasionally wake a GPT 6 agent, and the person stops it again. +**Consequences:** this changes when a message is admitted, not whether the model reads it. Queueing also removed an accidental way of freeing a stuck start, so a queued run's age became something the Fleet page shows. Each advance checks the outbox and follow-up behavior this depends on. Checked on 2026-10-17 against upstream's nightly `v0.1.1-nightly.20261017.3238`, it is still needed: upstream still steers whenever it can (Claude with `priority: "now"`, which cancels sibling tool calls, though it now moves the parent's foreground subagents to the background first; Cursor by interrupting and restarting the turn), and has no GPT 6-specific or asynchronous delivery. **J5 wants to drop this divergence** and follow upstream's delivery once upstream can deliver a message to a running turn without aborting it (Claude) or restarting it (Cursor), and supports the GPT 6 models' in-work messaging. Since 2026-10-11 the divergence is only the default: a sender can ask for a steer or a restart, with upstream's rule that the receiver may not run with broader permissions than the sender, and what is left is that J5 queues where upstream's `auto` would steer. The default is revisited on or after 2027-01-11, because agents are getting better at being steered and that has to reach the cheaper models first. Upstream's Stop holds a thread's queue. A stopped agent's queued messages wait until a person resumes its queue. Upstream starts a message sent to an idle thread at once, past a held queue, and leaves the held messages waiting; a person sees them above the composer and chooses between Resume and a new message. A sender on J5's delivery path sees none of that, so a J5 delivery to an idle agent with a held queue resumes the queue and joins the back: messages run in the order they were sent, whatever held the queue (a Stop, a restart, a provider failure). A delivery to an agent that stopped on a usage limit waits unsent, whether or not its queue is held, until the agent continues, by upstream's automatic continue at the reset or by a person, and then joins the back of the queue. Upstream refuses to resume such a thread's queue, starts a message sent to it at once into the same limit, and leaves one sent behind already queued messages waiting with no word to its sender; the sender's `deliveryNotice` says the message is saved and when it will run. A delivery to an agent whose last run failed or was interrupted while setting up its worktree, and that has no worktree, is held too, because resuming would run it in the project's own checkout. If messages are already held there, the delivery waits unsent. If none are, upstream accepts it and holds it in the thread's queue, as it holds any message sent then. Deliveries waiting unsent for one agent go together, in send order, as soon as a run starts on it, and a delivery waits while an earlier one to the same agent is still waiting, so none overtakes another. A person's own message keeps upstream's behavior (Jackson, 2026-10-12). J5 doesn't guard a steer that races a Stop (D5, retired): a peer steer already in flight when the person presses Stop can occasionally wake a GPT 6 agent, and the person stops it again. -**Decided:** Jackson with Product, 2026-09-03 (QS1); the Astra exception by Jackson, 2026-09-04, widened by him to every Codex GPT 6 model on 2026-10-12; the sender's choice of `steer` or `restart` by Jackson, 2026-10-11 ([#519](https://github.com/Jacksondr5/j5code/issues/519)); holding a delivery after a failed worktree setup by Jackson, 2026-10-17. Recorded in FORK.md case 26. +**Decided:** Jackson with Product, 2026-09-03 (QS1); the Astra exception by Jackson, 2026-09-04, widened by him to every Codex GPT 6 model on 2026-10-12; the sender's choice of `steer` or `restart` by Jackson, 2026-10-11 ([#519](https://github.com/Jacksondr5/j5code/issues/519)); holding a delivery after a failed worktree setup by Jackson, 2026-10-17; holding every delivery to a usage-limited agent by Jackson, 2026-10-24. Recorded in FORK.md case 26. #### D6. Native resume starts fresh only when the conversation is gone @@ -606,3 +606,4 @@ J5 kept a run from resuming after a usage-limit reset when the person had presse - 2026-10-24 — D2: agents get upstream's queue tools, with edit held to an agent's own messages and the ledger following every edit; D4: the platform delivers in send order and a person or an agent may reorder by hand (Jackson, [#136](https://github.com/Jacksondr5/j5code/issues/136)). - 2026-10-24 — D33: lowering or removing an Owner ends the MCP clients that Owner approved, and only those (Jackson; [#639](https://github.com/Jacksondr5/j5code/issues/639)). - 2026-10-25 — D19: a copied prompt link points at j5.codes/new, which opens it in J5's apps or on the person's own server (Jackson's 2026-10-24 decision; [#633](https://github.com/Jacksondr5/j5code/issues/633)). +- 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)).