Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(minions): our own implementation of the #6063 fix (#6063)
time-attack0c57e3fd207e
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex 681fa88544..17a28d44cd 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -14,7 +14,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, retries ordinary crashes with exponential backoff and runs periodic health checks. The default launcher prefers the current source/compiled CLI over PATH; internal `cliArgsPrefix` carries source-entrypoint arguments while explicit `--cli-path` remains authoritative. Private-queue recovery belongs to the ready worker, not the parent spawn hook. A typed local configuration fault leaves the owner alive but blocks respawns, recovery and progress-watchdog actions; repair plus explicit owner restart is required. `OwnerProcessingState` supplies additive live readiness and redacted runtime identities. `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets. Worker exit classifier emits `likely_cause` on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`. Consumes `detectTini()` + `buildSpawnInvocation()` from `src/core/minions/spawn-helpers.ts` to wrap the worker subtree in `tini -s` subreaper mode when tini is on `PATH` (without assuming PID 1) (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposes `isTiniDetected` read-only accessor. The spawn-and-respawn loop is the shared `ChildWorkerSupervisor` core: MinionSupervisor composes it via `runSuperviseLoop()` → `new ChildWorkerSupervisor({...})` and maps `ChildSupervisorEvent` back through `emit()` SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, and `process.exit` on the HARD crash ceiling stay in MinionSupervisor. Crossing the SOFT budget (`maxCrashes`) does not permanently give up: the core drops into degraded retry (capped backoff + a `crash_budget_degraded` health_warn) and self-heals when a respawn runs stably; permanent `process.exit(MAX_CRASHES)` fires only at the hard ceiling `resolveHardStopMaxCrashes(maxCrashes)` (default `maxCrashes × 10`, env `GBRAIN_SUPERVISOR_HARD_STOP_CRASHES`, `0` = never). Separately, `gbrain jobs supervisor status` + `gbrain doctor` detect a live supervisor through this queue lock (`inspectLock` + `isLockHolderLive`, freshness-keyed so PID reuse can't false-positive) when the `$HOME`-derived pidfile is absent, so a split-`$HOME` deployment does not read a healthy supervisor as "not running". `code=0` leaves `crashCount` untouched (so a worker alternating real crashes + watchdog drains still trips `max_crashes`); `cleanRestartBudget` (default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop via `health_warn { reason: 'clean_restart_budget_exceeded' }` + backoff. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Progress watchdog: `healthCheck()` restarts an alive-but-wedged child via `childSupervisor.restartCurrentChild(35_000)` when a queue has claimable work, 0 live-lock active jobs, and stale completions across `wedgeRestartChecks` (default 3) consecutive checks past `wedgeRestartMinutes` (default 15, 0 disables) + a `startupGraceMs` window; bounded by `wedgeRestartLoopBudget` (default 3 / `wedgeRestartLoopWindowMs`) which switches to a one-shot `wedge_restart_loop` alert. The wedge query is the exported `queryWedgeSignals(engine, queue, handlerNames)` — name+queue-scoped, `active_healthy` = live-lock only (an expired-lock active row does NOT mask the wedge), due-delayed counted. Claimable names are derived at start via a throwaway `registerBuiltinHandlers` worker (its new `quiet` opt). Flags `--wedge-restart-minutes` / `--wedge-restart-checks` + env `GBRAIN_WEDGE_RESTART_MINUTES` / `GBRAIN_WEDGE_RESTART_CHECKS`. The worker argv is built by the exported pure `buildWorkerArgs(opts)` (appends `--nice N` when `opts.nice_requested` is set, alongside `--concurrency`/`--queue`/`--max-rss`); the niceness apply RESULT (`nice_requested`/`nice_effective`/`nice_error`, computed by the CLI in jobs.ts — the supervisor doesn't call setPriority) rides on the `started`/`worker_spawned` audit emissions. Queue-scoped singleton: the real authority is a DB lock (`tryAcquireDbLock` from `src/core/db-lock.ts`) keyed on `supervisorLockId(queue)` = `gbrain-supervisor:<queue>` — keyed on the QUEUE ALONE because the lock row lives inside the target database, so the (database) half of the mutex is physical, not part of the key (mixing in a config-derived DB identity would let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire). Two supervisors with different `$HOME`/`--pid-file` against the same `(database, queue)` cannot both run with conflicting `--max-rss`: the second exits `LOCK_HELD`. The pidfile-cleanup `process.on('exit')` listener is installed BEFORE the DB-lock acquisition so the `LOCK_HELD` early-exit can't strand the pidfile this process just created. The default pidfile is brain-scoped (`supervisor-<brainId>.pid`) so different brains under one HOME don't false-block. The lock refreshes on its own `setInterval` (TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that THROWS past the threshold exits `LOCK_LOST` (code 4) rather than risk a split-brain, while a fenced refresh returning `false` (0 rows matched — the lock was stolen or force-cleared) is treated as CERTAIN loss, not a blip: the supervisor emits `health_error { reason: 'supervisor_lock_lost' }` and exits `LOCK_LOST` immediately (counting it toward the failure threshold would let two supervisors drain the same queue for up to two more refresh windows). `shutdown()` releases the lock so a clean restart re-acquires immediately. The `started` audit records `max_rss_mb` so `gbrain doctor`'s `supervisor_singleton` check can surface the effective cap. Exports `supervisorLockId()` and the pure `classifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch'` (host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned by `test/supervisor.test.ts` (16 cases), `test/supervisor-tini.test.ts`, `test/supervisor-wedge.test.ts`, `test/supervisor-build-worker-args.test.ts`, and `test/supervisor-db-lock.test.ts`. `SupervisorOpts.jobIsolation` passes `--job-isolation process` to the spawned worker via a CONDITIONAL `buildWorkerArgs` push (inline argv stays byte-identical). `queryWedgeSignals`/`probeQueueState` thread a per-probe AbortSignal; the probe timeout cancels the losing query (pool-slot release under exhaustion). `buildWorkerArgs` also appends `--allow-shell-jobs` when `opts.allowShellJobs` (conditional push like `--job-isolation`, so existing argv stays byte-identical; pinned by `test/supervisor-build-worker-args.test.ts`). Rationale: the worker's startup cwd-.env quarantine drops `GBRAIN_ALLOW_SHELL_JOBS` whenever a .env in the worker's cwd assigns it, so the env copy in `runSuperviseLoop` alone could silently disable shell jobs; `jobs work` parses the flag and re-sets `process.env.GBRAIN_ALLOW_SHELL_JOBS='1'` after preflight (read sites in jobs.ts / handlers/shell.ts unchanged). `allowShellJobs` sets the env var on the child AND pushes `--allow-shell-jobs`. #5062: registers as the CLI signal owner; `shutdown()` is one shared promise (repeated signals join it) that keeps refreshing the queue lock while the worker drains (SIGTERM, 35s, SIGKILL by liveness, 5s confirmation), then releases the lock and emits `stopped` with `drained` / `worker_forced` / `worker_exit_code` / `lock_released`. `gbrain jobs supervisor stop` (`src/commands/jobs/supervisor.ts`) reports `drained` only when the pid is gone, the supervisor's own `stopped` row follows its `shutting_down` with `drained: true`, every worker it spawned is gone and its lock row is released; otherwise it names the failing check (`no_stopped_event`, `worker_still_running`, `lock_unverified`, `lock_still_held`, `forced`) and exits 1.-- `src/core/minions/tool-write-identity.ts` — Binds a journal mutation to the persisted subagent execution coordinates with a deterministic UUIDv8 before dispatch. Legacy, gateway and oneshot replay preserve the same logical request across process restart; explicit caller IDs remain authoritative. `runToolWrite` (all six dispatch sites: legacy loop and resume, gateway execute and resume reconciliation, oneshot write loop and recovery) replays a pending receipt in-process under the same request ID, with no model call, until the write is terminal, the job is cancelled, or the job deadline less `TOOL_WRITE_DEADLINE_RESERVE_MS` (45 s: the longest `wait_ms` plus admission headroom) arrives; a job without a deadline waits `maintenanceWriteWaitMs()` (30 s). Only then does it leave the handler as `write_pending`, so a write that never commits holds the job (and a serial dream drain behind it) until that point. A terminal `failed` receipt is never replayed. Pending receipts leave tool ledgers pending for retry and never count as written pages. Pinned by `test/subagent-pending-tool-write.test.ts`.+- `src/core/minions/tool-write-identity.ts` — Binds a journal mutation to the persisted subagent execution coordinates with a deterministic UUIDv8 before dispatch. Legacy, gateway and oneshot replay preserve the same logical request across process restart; explicit caller IDs remain authoritative. `awaitCommittedToolWrite(job, toolName, dispatch)` wraps every subagent tool dispatch (legacy loop and resume, gateway execute and resume reconciliation, oneshot write loop and recovery): while the write is admitted but still pending it replays the same request ID through `replayWhilePending` (no model call, nothing new admitted) until the write is terminal, the job's signal aborts (the pause ends and the last pending error, receipt included, is rethrown), or the job deadline is closer than `WIRE_WRITE_WAIT_MAX_MS` plus `WRITE_ADMISSION_HEADROOM_MS` (45 s); a job without a deadline replays for the `MaintenanceWriteWait` base (30 s). Only then does the write leave the handler as `write_pending`, so a write that never commits holds the job (and a serial dream drain behind it) until that point. A terminal `failed` receipt and non-mutation tools are never replayed. Pending receipts leave tool ledgers pending for retry and never count as written pages. Pinned by `test/subagent-handler.test.ts`, `test/minions/subagent-pending-write-runners.test.ts`, `test/minions/subagent-oneshot.test.ts` and `test/e2e/subagent-gateway-resume-reconciliation.test.ts`.- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (13-name allow-list, size pinned by `test/brain-allowlist.test.ts`). Attachment tools `file_list` and `file_url` are excluded. Registry construction and execution reject every `localOnly` operation; `selectAllowedTools` rejects malformed bindings and preserves explicit empty lists as no tools. Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trusted local jobs receive these from the submitter; remote-owned jobs receive the grant intersection plus `delegatedAuth`. Their per-call operation contexts carry the verified OAuth owner principal and current operation/source grant intersection into durable requests, and retain remote visibility policy, without requiring direct read/write scopes for independently bound delegated tools. `BuildBrainToolsOpts.deferEmbeds` (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads `OperationContext.deferEmbeds` so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param). `execute()` runs the same `validateParams` the MCP dispatchers use before the op handler, so a call that omits a required parameter (or sends the wrong type / an unknown enum value) fails with `<tool>: Missing required parameter: <name>` the model can act on, instead of a handler crash. `putPageRejection` classifies legacy rejected import envelopes for subagent accounting; actual persistence errors keep the typed receipt contract. Scoped model-authored type normalization is performed by `persistence/page-input.ts` only after durable existing-request lookup, so registry execution never rewrites a replay using a newer schema pack.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 535caa395d..3406ca9df3 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -17,7 +17,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/onboarding.ts` + `legacy-locks.ts` + `physical-root-recovery.ts` — read-only source onboarding states; exact same-host dead-lock cleanup under explicit activation opt-in; and state-bound same-owner root repair using a durable manifest and token-verified temporary stamp. `physical-root.ts` `restampPhysicalRoot` handles a filesystem device id that changed while the owner token, brain, worktree, root, inode and a non-zero birth time still match (macOS can renumber `st_dev` across reboots): under the caller's outside-root native lock, one transaction verifies owner host, brain and host binding and rewrites the recorded self-transfer copies and retained topology staging identities (each only while it still names the old device); after commit the stamp and the reservation's initial device are rewritten and the event is logged, so an interruption between the two leaves a device-only change the next locked acquisition finishes. Ownership markers inside a retained topology clone stage are not re-stamped; an interrupted clone recovery that spans a device renumbering still needs source recovery. `assertPhysicalRoot` stays read-only; zero birth time or any other difference keeps the refusal. `--self-transfer` prepare/accept requires separate fresh reviewed state, preserves original reservation owner evidence and refuses uncertain records. Tests: `test/persistence-onboarding.test.ts`, `test/persistence-admin-recovery.test.ts`, `test/persistence-container-preflight.test.ts`.- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests.-- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. `maintenanceWriteWaitMs` is that base for a job without a deadline, which is also a subagent tool write's wait when its job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.+- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.Atom completion admits replacement and revision-pinned stale-atom deletion children together.Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.Derived atom pages may regenerate or retire when their canonical file is already absent, while ordinary page writes retain missing-file refusal.@@ -41,7 +41,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/page-input.ts` — freezes scoped subagent type normalization at durable admission, after existing-request replay. An explicit undeclared model-authored type becomes `note` with `legacy_type` retained using the then-active schema pack; a replay keeps its original normalized payload when the pack changes. Caller intent remains unchanged for idempotency checks. Raw input size is checked before normalization and malformed Markdown is left to the importer’s sanitized error contract. `test/brain-allowlist.test.ts` pins changed-pack replay, raw-size refusal, and private parse-error redaction. `undeclaredPageTypeWarning` covers every other `put_page` (not managed file imports): a type the write source's pack neither declares nor aliases is stored as written and the committed result carries `type_warning` (`code: page_type_undeclared`, cause, fix, docs), also logged; pinned by `test/put-page-type-warning.test.ts`.- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.-- `src/core/persistence/write-wait.ts` — the CLI write-wait and exit contract (#5232). `resolveCliWriteWaitMs` (`--wait` seconds > `GBRAIN_WRITE_WAIT_MS` > file-plane `persistence.write_wait_ms` > 30 s; agents keep `AGENT_WRITE_WAIT_MS`); `writeExchangeBudget` (transport deadline = wait + 15 s admission headroom; an explicit `--timeout` shortens the requested owner wait instead); `replayWhilePending` (replays the identical request ID while an older owner, a remote server or a subagent tool's own bounded wait reports pending; an aborted `signal` ends the pause and stops the replays); `writeErrorExitCode` keys on an admitted non-terminal receipt (`admittedPendingReceipt` in `types.ts`): pending → `PENDING_WRITE_EXIT_CODE` (0 with `--accept-pending`/`GBRAIN_ACCEPT_PENDING=1`), anything else → 1. Pinned by `test/pending-write-exit.serial.test.ts` and `test/pending-write-exit-owner.test.ts`.+- `src/core/persistence/write-wait.ts` — the CLI write-wait and exit contract (#5232). `resolveCliWriteWaitMs` (`--wait` seconds > `GBRAIN_WRITE_WAIT_MS` > file-plane `persistence.write_wait_ms` > 30 s; agents keep `AGENT_WRITE_WAIT_MS`); `writeExchangeBudget` (transport deadline = wait + 15 s admission headroom; an explicit `--timeout` shortens the requested owner wait instead); `replayWhilePending` (replays the identical request ID while an older owner, a remote server or a subagent tool's own bounded wait reports pending; the caller-supplied `sleep` decides how each pause ends, which is how subagent tool writes stop on abort); `writeErrorExitCode` keys on an admitted non-terminal receipt (`admittedPendingReceipt` in `types.ts`): pending → `PENDING_WRITE_EXIT_CODE` (0 with `--accept-pending`/`GBRAIN_ACCEPT_PENDING=1`), anything else → 1. Pinned by `test/pending-write-exit.serial.test.ts` and `test/pending-write-exit-owner.test.ts`.- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB. Called at submission (`page-mutations.ts`, before admission) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`.- `src/core/persistence/suffixed-slug.ts` — `.md`/`.mdx`-suffixed slugs (#4807). `preparePageAdmission` refuses a new put_page/put_pages slug ending in `.md`/`.mdx` before any journal row (`invalid_params`, why, suggestion naming the bare slug, read-only `get_page` fix and verify); a live page with that exact (source_id, slug) still updates and the put_page response carries `slug_advisory` (put under the bare slug, then delete_page). `suffixedSlugDryRun` serves put_page dry runs; `suffixedFrontmatterSlugHold` holds a file import whose frontmatter `slug:` identity ends in `.md` as `frontmatter_slug_conflict`. `validateSlug` and path-derived import slugs are unchanged. Test: `test/ingestion/put-page-write-through.test.ts`.diff --git a/src/core/minions/handlers/subagent-oneshot.ts b/src/core/minions/handlers/subagent-oneshot.tsindex 7a20729831..901698d0f1 100644--- a/src/core/minions/handlers/subagent-oneshot.ts+++ b/src/core/minions/handlers/subagent-oneshot.ts@@ -31,7 +31,7 @@* a completed result.*/-import { retainToolWriteRequestId, runToolWrite, isPendingToolWrite } from '../tool-write-identity.ts';+import { retainToolWriteRequestId, awaitCommittedToolWrite, isPendingToolWrite } from '../tool-write-identity.ts';import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../../engine.ts';import type { MinionJobContext, SubagentHandlerData, SubagentResult, ToolDef, ContentBlock, OneshotFallbackReason } from '../types.ts';@@ -257,7 +257,7 @@ async function loadOneshotLedger(engine: BrainEngine, jobId: number): Promise<Le}export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutcome> {- const { engine, ctx, data, model } = args;+ const { engine, ctx, data, model, putPageTool } = args;const chat = args._chat ?? gatewayChat;const submitted = snapshotFromJob(ctx.data);const checkCurrentWrite = async (slug?: string): Promise<void> => {@@ -289,15 +289,15 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutcif (row.status !== 'pending') continue;const input = { slug: row.slug ?? '', content: row.content ?? '', ...(row.request_id ? { request_id: row.request_id } : {}) };retainToolWriteRequestId(input, ctx.id, 1, row.ordinal ?? 0, row.tool_use_id, 'brain_put_page');- if (!args.putPageTool || !input.slug || !input.content) {+ if (!putPageTool || !input.slug || !input.content) {await persistToolExecFailed(engine, ctx.id, 1, row.ordinal ?? 0, row.tool_use_id, 'brain_put_page', input,'oneshot recovery: pending write could not be re-executed (missing tool or ledger input)');row.status = 'failed';continue;}try {- const putPageTool = args.putPageTool;- const output = await runToolWrite(() => putPageTool.execute(input, { engine, jobId: ctx.id, remote: true, signal: ctx.signal }), 'brain_put_page', ctx);+ const output = await awaitCommittedToolWrite(ctx, 'brain_put_page',+ () => putPageTool.execute(input, { engine, jobId: ctx.id, remote: true, signal: ctx.signal }));await persistToolExecComplete(engine, ctx.id, 1, row.ordinal ?? 0, row.tool_use_id, output);row.status = 'complete';} catch (e) {@@ -343,7 +343,7 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutc};}- if (!args.putPageTool) {+ if (!putPageTool) {// No put_page in the registry (misconfigured allow-list) — a config// error, not a model failure; distinct reason so telemetry separates it.return { kind: 'fallback', reason: 'no_put_page_tool' };@@ -575,13 +575,8 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutcif (ctx.signal?.aborted) throw new DOMException('oneshot write loop aborted by job signal', 'AbortError');let output: unknown;try {- const putPageTool = args.putPageTool;- output = await runToolWrite(() => putPageTool.execute(input, {- engine,- jobId: ctx.id,- remote: true,- signal: ctx.signal,- }), 'brain_put_page', ctx);+ output = await awaitCommittedToolWrite(ctx, 'brain_put_page',+ () => putPageTool.execute(input, { engine, jobId: ctx.id, remote: true, signal: ctx.signal }));} catch (e) {// Abort/transient-conn errors are not write verdicts (same rule as// recovery): rethrow, row stays pending, retry re-executes.diff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.tsindex 9d0dfce4db..de274b1cf7 100644--- a/src/core/minions/handlers/subagent.ts+++ b/src/core/minions/handlers/subagent.ts@@ -24,7 +24,7 @@* as P2 items in the plan file.*/-import { retainToolWriteRequestId, runToolWrite, isPendingToolWrite } from '../tool-write-identity.ts';+import { retainToolWriteRequestId, awaitCommittedToolWrite, isPendingToolWrite } from '../tool-write-identity.ts';import Anthropic from '@anthropic-ai/sdk';import type { MinionJobContext, MinionJob } from '../types.ts';import { UnrecoverableError } from '../types.ts';@@ -706,9 +706,9 @@ export function makeSubagentHandler(deps: SubagentDeps) {retainToolWriteRequestId(use.input, ctx.id, last.message_idx, useOrdinal, use.id, use.name);await persistToolExecPending(engine, ctx.id, last.message_idx, useOrdinal, use.id, use.name, use.input);try {- const output = await runToolWrite(() => toolDef.execute(use.input, {+ const output = await awaitCommittedToolWrite(ctx, use.name, () => toolDef.execute(use.input, {engine, jobId: ctx.id, remote: true, signal: ctx.signal,- }), use.name, ctx);+ }));await persistToolExecComplete(engine, ctx.id, last.message_idx, useOrdinal, use.id, output);synthesizedResults.push({type: 'tool_result', tool_use_id: use.id,@@ -1053,12 +1053,12 @@ export function makeSubagentHandler(deps: SubagentDeps) {const toolStart = Date.now();try {- const output = await runToolWrite(() => toolDef.execute(use.input, {+ const output = await awaitCommittedToolWrite(ctx, toolName, () => toolDef.execute(use.input, {engine,jobId: ctx.id,remote: true,signal: ctx.signal,- }), toolName, ctx);+ }));await persistToolExecComplete(engine, ctx.id, assistantIdx, useOrdinal, use.id, output);logSubagentHeartbeat({job_id: ctx.id,@@ -1201,8 +1201,8 @@ async function runSubagentViaGateway(args: GatewayRunArgs): Promise<SubagentResuidempotent: t.idempotent === true,async execute(input: unknown, signal: AbortSignal): Promise<unknown> {try {- return await runToolWrite(() => t.execute(input, { engine, jobId: ctx.id, remote: true, signal }), t.name,- { deadlineAtMs: ctx.deadlineAtMs, signal });+ return await awaitCommittedToolWrite({ deadlineAtMs: ctx.deadlineAtMs, signal }, t.name,+ () => t.execute(input, { engine, jobId: ctx.id, remote: true, signal }));} catch (error) {if (isPendingToolWrite(error)) pendingToolWrite = error;throw error;@@ -1250,7 +1250,7 @@ async function runSubagentViaGateway(args: GatewayRunArgs): Promise<SubagentResupriorTools: priorToolsV1,toolDefs,signal: ctx.signal,- deadlineAtMs: ctx.deadlineAtMs,+ jobDeadlineAtMs: ctx.deadlineAtMs,});// Terminal early-return (#1151 parity): the prior run already reached@@ -1516,8 +1516,8 @@ interface ReconcileArgs {priorTools: PersistedToolExec[];toolDefs: ToolDef[];signal: AbortSignal;- /** The job deadline that bounds a re-dispatched tool write's wait (#5474). */- deadlineAtMs: number | null;+ /** Bounds how long a re-dispatched pending tool write keeps replaying (#5474). */+ jobDeadlineAtMs: number | null;}interface ReconcileResult {@@ -1551,7 +1551,7 @@ interface ReconcileResult {* resume stays balanced.*/async function reconcileGatewayReplay(args: ReconcileArgs): Promise<ReconcileResult> {- const { engine, jobId, priorMessages, priorTools, toolDefs, signal, deadlineAtMs } = args;+ const { engine, jobId, priorMessages, priorTools, toolDefs, signal } = args;const work = priorMessages.map(m => {const adapted = adaptContentBlocksToChatBlocks(m.content_blocks);@@ -1654,8 +1654,8 @@ async function reconcileGatewayReplay(args: ReconcileArgs): Promise<ReconcileResretainToolWriteRequestId(call.input, jobId, msg.message_idx, callIdx, call.toolCallId, call.toolName);await persistToolExecPending(engine, jobId, msg.message_idx, callIdx, call.toolCallId, call.toolName, call.input);try {- const output = await runToolWrite(() => toolDef.execute(call.input, { engine, jobId, remote: true, signal }), call.toolName,- { deadlineAtMs, signal });+ const output = await awaitCommittedToolWrite({ deadlineAtMs: args.jobDeadlineAtMs, signal }, call.toolName,+ () => toolDef.execute(call.input, { engine, jobId, remote: true, signal }));await persistToolExecComplete(engine, jobId, msg.message_idx, callIdx, call.toolCallId, output);results.push({ type: 'tool-result', toolCallId: call.toolCallId, toolName: call.toolName, output });} catch (e) {diff --git a/src/core/minions/tool-write-identity.ts b/src/core/minions/tool-write-identity.tsindex fe7069aaa3..9e83a50bfd 100644--- a/src/core/minions/tool-write-identity.ts+++ b/src/core/minions/tool-write-identity.ts@@ -3,9 +3,10 @@ import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import { isWriteReceipt } from '../persistence/types.ts';import { isPersistenceIpcMutation } from '../persistence/ipc.ts';-import { WRITE_ADMISSION_HEADROOM_MS, replayWhilePending } from '../persistence/write-wait.ts';+import { replayWhilePending, WRITE_ADMISSION_HEADROOM_MS } from '../persistence/write-wait.ts';import { WIRE_WRITE_WAIT_MAX_MS } from '../persistence/params.ts';-import { maintenanceWriteWaitMs } from '../persistence/maintenance-wait.ts';+import { MaintenanceWriteWait } from '../persistence/maintenance-wait.ts';+import { abortableSleep, RetryAbortError } from '../retry.ts';/** Bind a durable write to its persisted tool execution, including crash replay. */export function retainToolWriteRequestId(input: unknown, jobId: number, messageIdx: number, ordinal: number, toolUseId: string, toolName: string): void {@@ -29,38 +30,33 @@ export function assertToolWriteCommitted(output: unknown, toolName: string): voierror.writeRequest = output; error.writeError = code; throw error;}-/**- * A pending tool write stops waiting this long before the job deadline: one- * more tool wait at its longest (each replay resends the model's `wait_ms`)- * plus admission headroom, so the handler returns `write_pending` (a retry- * under a fresh deadline) before the runner's timeout marks the job dead.- */-const TOOL_WRITE_DEADLINE_RESERVE_MS = WIRE_WRITE_WAIT_MAX_MS + WRITE_ADMISSION_HEADROOM_MS;+/** What a subagent tool dispatch needs from its job to bound a pending write. */+export interface ToolWriteJob { deadlineAtMs: number | null; signal?: AbortSignal }/**- * #5474: run a tool and wait for its accepted write. The tool's own bounded- * wait can end while the write is still queued; replaying the same request_id- * admits nothing new and calls no model, so the job replays until the write- * is terminal, the job is cancelled, or the job deadline less the reserve- * arrives (a job without a deadline waits the #5854 maintenance wait). The- * job cannot take its next turn without the result. Only then does the write- * leave the handler as `write_pending`, its tool row still pending for the- * retry: runners count that as a failed attempt, and the dream inline drain- * retries at once. Tradeoff: a write that never commits holds the job, and a- * serial dream drain behind it, until that deadline. The receipt's- * `inspect_owner` advice is no exit signal: it also marks writer-pool- * contention and any write older than 2 min, the slow commits this wait is for.+ * #5474: dispatch a subagent tool and, while its accepted write is still+ * pending, replay the same request id (nothing new is admitted, no model turn)+ * instead of failing the attempt. The replays stop when the write is terminal,+ * when the job is aborted, or once the job's deadline is closer than one more+ * longest tool wait plus admission headroom, so a retry still fits before the+ * runner times the job out. A job with no deadline gets the maintenance write+ * wait. Whatever is still pending then leaves as `write_pending` with its tool+ * row pending, exactly as before.*/-export async function runToolWrite(run: () => Promise<unknown>, toolName: string,- job: { deadlineAtMs: number | null; signal?: AbortSignal }): Promise<unknown> {- const waitMs = job.deadlineAtMs == null ? maintenanceWriteWaitMs()- : Math.max(0, job.deadlineAtMs - Date.now() - TOOL_WRITE_DEADLINE_RESERVE_MS);- return replayWhilePending(async () => {- const output = await run();- assertToolWriteCommitted(output, toolName);- return output;- }, waitMs, { signal: job.signal });+export async function awaitCommittedToolWrite(job: ToolWriteJob, toolName: string, dispatch: () => Promise<unknown>): Promise<unknown> {+ const windowMs = job.deadlineAtMs == null ? new MaintenanceWriteWait().ms()+ : Math.max(0, job.deadlineAtMs - Date.now() - WIRE_WRITE_WAIT_MAX_MS - WRITE_ADMISSION_HEADROOM_MS);+ let lastFailure: unknown;+ const attempt = () => dispatch()+ .then(output => { assertToolWriteCommitted(output, toolName); return output; })+ .catch((failure: unknown) => { lastFailure = failure; throw failure; });+ try {+ return await replayWhilePending(attempt, windowMs, ms => abortableSleep(ms, job.signal));+ } catch (error) {+ throw error instanceof RetryAbortError && lastFailure !== undefined ? lastFailure : error;+ }}+export function isPendingToolWrite(error: unknown): error is OperationError {return error instanceof OperationError && error.code === 'write_pending' && error.writeRequest !== undefined;}diff --git a/src/core/persistence/maintenance-wait.ts b/src/core/persistence/maintenance-wait.tsindex 10aaeadc67..b7a94d65c9 100644--- a/src/core/persistence/maintenance-wait.ts+++ b/src/core/persistence/maintenance-wait.ts@@ -31,9 +31,6 @@ export function __setMaintenanceWriteWaitForTests(ms: number | null): () => void/** The wait for a maintenance publish outside a job budget. */export function maintenancePublishWaitMs(): number { return testWaitMs ?? MAINTENANCE_PUBLISH_WAIT_MS; }-/** A job's write wait when it has no deadline; also a subagent tool write's (#5474). */-export function maintenanceWriteWaitMs(): number { return testWaitMs ?? MAINTENANCE_WRITE_WAIT_MS; }-export class MaintenanceWriteWait {private pending = false;constructor(private readonly deadlineAtMs: number | null = null, private readonly now: () => number = Date.now) {}diff --git a/src/core/persistence/write-wait.ts b/src/core/persistence/write-wait.tsindex 3e6967500e..ea7d602583 100644--- a/src/core/persistence/write-wait.ts+++ b/src/core/persistence/write-wait.ts@@ -8,7 +8,6 @@ import { loadConfig, type GBrainConfig } from '../config.ts';import { getCliOptions } from '../cli-options.ts';import { PENDING_WRITE_EXIT_CODE } from '../exit-codes.ts';import { OperationError } from '../ops/contract.ts';-import { abortableSleep } from '../retry.ts';import { admittedPendingReceipt, type WriteReceipt } from './types.ts';import { WIRE_WRITE_WAIT_MAX_MS } from './params.ts';@@ -130,22 +129,18 @@ export function pollCommand(requestId: string): string {* Keep the caller's wait across transports that wait less than it (an older* owner, or a remote server's own bounded wait): replay the identical request* (same request_id, so nothing new is admitted) until it settles or the wait- * is spent. Only an admitted pending receipt is replayed. An aborted `signal`- * ends the pause and stops the replays; the pending error propagates with its- * receipt.+ * is spent. Only an admitted pending receipt is replayed.*/export async function replayWhilePending<T>(send: () => Promise<T>, waitMs: number,- { sleep = abortableSleep, signal }: { sleep?: (ms: number, signal?: AbortSignal) => Promise<void>; signal?: AbortSignal } = {}): Promise<T> {+ sleep: (ms: number) => Promise<void> = ms => new Promise(resolve => setTimeout(resolve, ms))): Promise<T> {const deadline = Date.now() + waitMs;for (;;) {try { return await send(); }catch (error) {const receipt = pendingReceiptOf(error);const remaining = deadline - Date.now();- if (!receipt || remaining <= 0 || signal?.aborted) throw error;- await sleep(Math.min(Math.max(receipt.retry_after_ms ?? 1000, 50), remaining), signal)- .catch(sleepError => { if (!signal?.aborted) throw sleepError; });- if (signal?.aborted) throw error;+ if (!receipt || remaining <= 0) throw error;+ await sleep(Math.min(Math.max(receipt.retry_after_ms ?? 1000, 50), remaining));}}}diff --git a/test/e2e/subagent-gateway-resume-reconciliation.test.ts b/test/e2e/subagent-gateway-resume-reconciliation.test.tsindex 03267699f0..09251d2b18 100644--- a/test/e2e/subagent-gateway-resume-reconciliation.test.ts+++ b/test/e2e/subagent-gateway-resume-reconciliation.test.ts@@ -33,7 +33,6 @@ import {type ChatMessage,type ChatResult,} from '../../src/core/ai/gateway.ts';-import { __setMaintenanceWriteWaitForTests } from '../../src/core/persistence/maintenance-wait.ts';let engine: PGLiteEngine;@@ -131,7 +130,7 @@ function assertBalanced(messages: ChatMessage[]): void {describe('gateway resume reconciliation', () => {it('a pending journal write stays pending and replays its UUID before another model turn', async () => {- let turns = 0; let queued = Number.POSITIVE_INFINITY; const identities: unknown[] = [];+ let turns = 0; let pending = true; const identities: unknown[] = [];__setChatTransportForTests(async () => {turns++;return { text: turns === 1 ? '' : 'done', blocks: turns === 1@@ -148,21 +147,44 @@ describe('gateway resume reconciliation', () => {expect(id).toMatch(/^[0-9a-f-]{36}$/);const [row] = await engine.executeRaw<{ request_id: string }>("SELECT input->>'request_id' AS request_id FROM subagent_tool_executions WHERE job_id=$1", [jobId]);expect(row.request_id).toBe(id);- return { request_id: id, state: queued-- > 0 ? 'queued' : 'committed', retry_after_ms: 20 };+ return { request_id: id, state: pending ? 'queued' : 'committed', retry_after_ms: pending ? 100 : null };} }];- // No in-run wait (#5474): the job's write wait would otherwise replay the pending receipt for 30 s.- const restoreWait = __setMaintenanceWriteWaitForTests(0);- try {- await expect(buildHandler(registry)(ctx)).rejects.toMatchObject({ code: 'write_pending' });- } finally { restoreWait(); }+ // 40 s from its deadline the job is inside the replay reserve, so the pending write leaves at once (#5474).+ await expect(buildHandler(registry)({ ...ctx, deadlineAtMs: Date.now() + 40_000 })).rejects.toMatchObject({ code: 'write_pending' });expect((await engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id=$1', [jobId]))[0].status).toBe('pending');- // The resumed dispatch replays the still-pending write until it commits (#5474).- queued = 2;+ pending = false;await buildHandler(registry)(ctx);- expect(turns).toBe(2); expect(identities).toEqual(Array(4).fill(identities[0]));+ expect(turns).toBe(2); expect(identities).toHaveLength(2); expect(identities[1]).toBe(identities[0]);expect((await engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id=$1', [jobId]))[0].status).toBe('complete');});+ it('a resumed dispatch keeps replaying a still-pending write until it commits (#5474)', async () => {+ let turns = 0; let pendingReplies = 0; const seen: unknown[] = [];+ __setChatTransportForTests(async () => {+ turns++;+ return { text: '', blocks: turns === 1+ ? [{ type: 'tool-call', toolCallId: 'resume-call', toolName: 'brain_put_page', input: { slug: 'notes/resume-fixture', content: 'fixture' } }]+ : [{ type: 'text', text: 'finished' }], stopReason: turns === 1 ? 'tool_calls' : 'end',+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'openai:gpt-4o', providerId: 'openai' } satisfies ChatResult;+ });+ const { jobId, ctx } = await makeJob('persist after resume', 'openai:gpt-4o');+ const registry: ToolDef[] = [{ name: 'brain_put_page', description: 'p', input_schema: { type: 'object' }, idempotent: true,+ execute: async input => {+ const request_id = (input as Record<string, unknown>).request_id; seen.push(request_id);+ return pendingReplies-- > 0 ? { request_id, state: 'running', retry_after_ms: 15 } : { request_id, state: 'committed', retry_after_ms: null };+ } }];+ pendingReplies = Number.MAX_SAFE_INTEGER;+ await expect(buildHandler(registry)({ ...ctx, deadlineAtMs: Date.now() + 40_000 })).rejects.toMatchObject({ code: 'write_pending' });+ pendingReplies = 3;+ await buildHandler(registry)(ctx);+ expect(turns).toBe(2);+ expect(seen).toHaveLength(5);+ expect(new Set(seen).size).toBe(1);+ const statuses = await engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id=$1', [jobId]);+ expect(statuses.map(row => row.status)).toEqual(['complete']);+ });+it('forward-persists the tool-result user turn (idx 2) in a 2-turn flow', async () => {let turn = 0;__setChatTransportForTests(async () => {diff --git a/test/minions/subagent-oneshot.test.ts b/test/minions/subagent-oneshot.test.tsindex 483137343e..2872258400 100644--- a/test/minions/subagent-oneshot.test.ts+++ b/test/minions/subagent-oneshot.test.ts@@ -25,7 +25,6 @@ import {type OneshotArgs,} from '../../src/core/minions/handlers/subagent-oneshot.ts';import type { ChatResult } from '../../src/core/ai/gateway.ts';-import { __setMaintenanceWriteWaitForTests } from '../../src/core/persistence/maintenance-wait.ts';let engine: PGLiteEngine;let queue: MinionQueue;@@ -185,45 +184,64 @@ describe('extractWikilinkTargets', () => {});describe('runSubagentOneshot', () => {- /** The real put_page behind a stub that reports the next `queued.left` dispatches as still queued. */- function queuedThenCommitted(args: OneshotArgs) {+ test('pending write receipts retain the whole ledger and retry without another provider call', async () => {+ const ctx = await makeCtx(DATA); const args = makeArgs(ctx, DATA, VALID_RESPONSE);const realTool = args.putPageTool!; const realChat = args._chat!;- const state = { chatCalls: 0, queued: 0, ids: [] as unknown[] };- args._chat = (async (options: Parameters<typeof realChat>[0]) => { state.chatCalls++; return realChat(options); }) as typeof realChat;+ let chatCalls = 0; let pending = true; const ids: unknown[] = [];+ args._chat = (async (options: Parameters<typeof realChat>[0]) => { chatCalls++; return realChat(options); }) as typeof realChat;args.putPageTool = { ...realTool, execute: async (input, context) => {- const id = (input as Record<string, unknown>).request_id; state.ids.push(id);- if (state.queued-- > 0) return { request_id: id, state: 'queued', retry_after_ms: 20 };+ const id = (input as Record<string, unknown>).request_id; ids.push(id);+ if (pending) return { request_id: id, state: 'queued', retry_after_ms: 100 };return realTool.execute(input, context);} };- return state;- }- const toolRowStatuses = async (jobId: number) =>- (await engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id=$1 ORDER BY ordinal', [jobId])).map(row => row.status);-- test('pending write receipts retain the whole ledger and retry without another provider call', async () => {- const ctx = await makeCtx(DATA); const args = makeArgs(ctx, DATA, VALID_RESPONSE);- const run = queuedThenCommitted(args);- run.queued = Number.POSITIVE_INFINITY;- // No in-run wait (#5474): the job's write wait would otherwise replay the pending receipt for 30 s.- const restoreWait = __setMaintenanceWriteWaitForTests(0);- try {- await expect(runSubagentOneshot(args)).rejects.toMatchObject({ code: 'write_pending', writeRequest: { state: 'queued' } });- } finally { restoreWait(); }- expect(await toolRowStatuses(ctx.id)).toEqual(['pending', 'pending']);- // Recovery replays a still-pending row until its write commits (#5474).- run.queued = 2;+ // 40 s from its deadline the job is inside the replay reserve, so the pending write leaves at once (#5474).+ await expect(runSubagentOneshot({ ...args, ctx: { ...ctx, deadlineAtMs: Date.now() + 40_000 } }))+ .rejects.toMatchObject({ code: 'write_pending', writeRequest: { state: 'queued' } });+ const rows = await engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id=$1', [ctx.id]);+ expect(rows).toHaveLength(2); expect(rows.every(row => row.status === 'pending')).toBe(true);+ pending = false;expect((await runSubagentOneshot(args)).kind).toBe('done');- expect(run.chatCalls).toBe(1); expect(run.ids.slice(0, 4)).toEqual(Array(4).fill(run.ids[0]));- expect(await toolRowStatuses(ctx.id)).toEqual(['complete', 'complete']);- });+ expect(chatCalls).toBe(1); expect(ids[1]).toBe(ids[0]);+ });++ describe('a write still pending after its own wait (#5474)', () => {+ /** Wrap the real put_page so the next `stall` dispatches report the write still queued. */+ function stallingWrites(args: OneshotArgs) {+ const inner = args.putPageTool!; const innerChat = args._chat!;+ const tally = { stall: 0, providerCalls: 0, requestIds: [] as unknown[] };+ args._chat = (async (options: Parameters<typeof innerChat>[0]) => { tally.providerCalls++; return innerChat(options); }) as typeof innerChat;+ args.putPageTool = { ...inner, execute: async (input, context) => {+ const request_id = (input as Record<string, unknown>).request_id; tally.requestIds.push(request_id);+ return tally.stall-- > 0 ? { request_id, state: 'recovering', retry_after_ms: 10 } : inner.execute(input, context);+ } };+ return tally;+ }+ const ledger = async (jobId: number) => (await engine.executeRaw<{ status: string; ordinal: number }>(+ 'SELECT status, ordinal FROM subagent_tool_executions WHERE job_id=$1 ORDER BY ordinal', [jobId])).map(row => row.status);++ test('the write loop replays it and finishes the job in one run', async () => {+ const ctx = await makeCtx(DATA); const args = makeArgs(ctx, DATA, VALID_RESPONSE);+ const tally = stallingWrites(args);+ tally.stall = 3;+ expect((await runSubagentOneshot(args)).kind).toBe('done');+ expect(tally.providerCalls).toBe(1);+ expect(tally.requestIds.slice(0, 4).every(id => id === tally.requestIds[0])).toBe(true);+ expect(await ledger(ctx.id)).toEqual(['complete', 'complete']);+ });- test('a write that commits during the job wait completes in one run without another provider call (#5474)', async () => {- const ctx = await makeCtx(DATA); const args = makeArgs(ctx, DATA, VALID_RESPONSE);- const run = queuedThenCommitted(args);- run.queued = 2;- expect((await runSubagentOneshot(args)).kind).toBe('done');- expect(run.chatCalls).toBe(1); expect(run.ids.slice(0, 3)).toEqual(Array(3).fill(run.ids[0]));- expect(await toolRowStatuses(ctx.id)).toEqual(['complete', 'complete']);+ test('recovery of a pending ledger row replays it rather than failing the attempt', async () => {+ const ctx = await makeCtx(DATA); const args = makeArgs(ctx, DATA, VALID_RESPONSE);+ const tally = stallingWrites(args);+ tally.stall = Number.MAX_SAFE_INTEGER;+ await expect(runSubagentOneshot({ ...args, ctx: { ...ctx, deadlineAtMs: Date.now() + 40_000 } })).rejects.toMatchObject({ code: 'write_pending' });+ expect(await ledger(ctx.id)).toEqual(['pending', 'pending']);+ const firstId = tally.requestIds[0];+ tally.stall = 2; tally.requestIds.length = 0;+ expect((await runSubagentOneshot(args)).kind).toBe('done');+ expect(tally.providerCalls).toBe(1);+ expect(tally.requestIds.slice(0, 3)).toEqual([firstId, firstId, firstId]);+ expect(await ledger(ctx.id)).toEqual(['complete', 'complete']);+ });});test('happy path: validates, writes both pages via put_page, ledger rows land, transcript persisted', async () => {diff --git a/test/minions/subagent-pending-write-runners.test.ts b/test/minions/subagent-pending-write-runners.test.tsnew file mode 100644index 0000000000..a01ce5a746--- /dev/null+++ b/test/minions/subagent-pending-write-runners.test.ts@@ -0,0 +1,103 @@+/**+ * #5474 at the runner level: a gateway-loop child whose brain write is still+ * pending after the tool's own wait must finish its attempt once the write+ * commits, on both the worker and the dream inline drain, instead of being+ * retried to death.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { LATEST_VERSION } from '../../src/core/migrate.ts';+import { MinionQueue } from '../../src/core/minions/queue.ts';+import { MinionWorker } from '../../src/core/minions/worker.ts';+import { runSubagentsInline } from '../../src/core/cycle/inline-drain.ts';+import { makeSubagentHandler } from '../../src/core/minions/handlers/subagent.ts';+import type { ToolDef } from '../../src/core/minions/types.ts';+import { __setChatTransportForTests, configureGateway, resetGateway, type ChatResult } from '../../src/core/ai/gateway.ts';++let engine: PGLiteEngine;+let providerTurns = 0;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ __setChatTransportForTests(null);+ resetGateway();+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', String(LATEST_VERSION));+ await engine.setConfig('agent.use_gateway_loop', 'true');+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,+ expansion_model: 'anthropic:claude-haiku-4-5', env: { ANTHROPIC_API_KEY: 'stub', OPENAI_API_KEY: 'stub' } } as never);+ providerTurns = 0;+ __setChatTransportForTests(async () => {+ providerTurns++;+ const first = providerTurns === 1;+ return { text: first ? '' : 'saved', stopReason: first ? 'tool_calls' : 'end',+ blocks: first ? [{ type: 'tool-call', toolCallId: 'write-1', toolName: 'brain_put_page', input: { slug: 'notes/runner-example', content: 'x' } }]+ : [{ type: 'text', text: 'saved' }],+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'openai:gpt-4o', providerId: 'openai' } satisfies ChatResult;+ });+});++/** put_page whose write reports `running` for the first `slowFor` dispatches; dispatch slowFor+1 commits. */+function slowCommit(slowFor: number) {+ const requestIds: unknown[] = [];+ const tool: ToolDef = { name: 'brain_put_page', description: 'example put_page', input_schema: { type: 'object' }, idempotent: true,+ async execute(input) {+ const request_id = (input as Record<string, unknown>).request_id; requestIds.push(request_id);+ return requestIds.length > slowFor ? { request_id, state: 'committed', retry_after_ms: null } : { request_id, state: 'running', retry_after_ms: 10 };+ } };+ return { tool, requestIds };+}++const gatewayHandler = (tool: ToolDef) => makeSubagentHandler({ engine, config: {} as never, toolRegistry: [tool],+ makeAnthropic: () => ({ messages: { create: async () => { throw new Error('legacy path must not run'); } } }) as never });++const finished = (status: string) => ['completed', 'failed', 'dead', 'cancelled'].includes(status);++async function viaWorker(tool: ToolDef): Promise<number> {+ const queue = new MinionQueue(engine);+ const job = await queue.add('subagent', { prompt: 'save the example', model: 'openai:gpt-4o' }, {}, { allowProtectedSubmit: true });+ const worker = new MinionWorker(engine, { pollInterval: 20 });+ worker.register('subagent', gatewayHandler(tool));+ const loop = worker.start();+ const until = Date.now() + 15_000;+ while (Date.now() < until && !finished((await queue.getJob(job.id))!.status)) await new Promise(resolve => setTimeout(resolve, 20));+ worker.stop();+ await loop;+ return job.id;+}++async function viaInlineDrain(tool: ToolDef): Promise<number> {+ const queue = new MinionQueue(engine);+ const queueName = `example-inline-${Date.now()}`;+ const job = await queue.add('subagent', { prompt: 'save the example', model: 'openai:gpt-4o' }, { queue: queueName }, { allowProtectedSubmit: true });+ await runSubagentsInline(engine, queue, queueName, undefined, gatewayHandler(tool));+ return job.id;+}++describe('a slow-committing subagent write does not cost the child its attempts (#5474)', () => {+ for (const [runner, run] of [['worker', viaWorker], ['dream inline drain', viaInlineDrain]] as const) {+ test(`${runner}: the child completes once its write commits`, async () => {+ const { tool, requestIds } = slowCommit(6);+ const jobId = await run(tool);+ const job = (await new MinionQueue(engine).getJob(jobId))!;+ expect(job.status).toBe('completed');+ expect({ failedAttempts: job.attempts_made, error: job.error_text ?? null }).toEqual({ failedAttempts: 0, error: null });+ expect(requestIds).toHaveLength(7);+ expect(new Set(requestIds).size).toBe(1);+ expect(providerTurns).toBe(2);+ const rows = await engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id=$1', [jobId]);+ expect(rows.map(row => row.status)).toEqual(['complete']);+ }, 30_000);+ }+});diff --git a/test/subagent-handler.test.ts b/test/subagent-handler.test.tsindex 416050d171..bc4c746f88 100644--- a/test/subagent-handler.test.ts+++ b/test/subagent-handler.test.ts@@ -23,6 +23,8 @@ import {} from '../src/core/minions/handlers/subagent.ts';import type { ToolDef, MinionJobContext } from '../src/core/minions/types.ts';import type Anthropic from '@anthropic-ai/sdk';+import { OperationError } from '../src/core/ops/contract.ts';+import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';let engine: PGLiteEngine;let queue: MinionQueue;@@ -195,25 +197,6 @@ describe('subagent handler happy path', () => {expect(out).toEqual({ echoed: { value: 'v1' } });});- test('a tool write still queued after its own wait is replayed until it commits, without another model call (#5474)', async () => {- const ids: unknown[] = [];- const tool: ToolDef = { ...makeEchoTool('brain_put_page'), async execute(input) {- const request_id = (input as Record<string, unknown>).request_id; ids.push(request_id);- return { request_id, state: ids.length < 3 ? 'queued' : 'committed', retry_after_ms: 20 };- } };- const client = new FakeMessagesClient([- { content: [{ type: 'tool_use', id: 'tu_1', name: 'brain_put_page', input: { slug: 'notes/pending-example' } } as any], stop_reason: 'tool_use' as any },- { content: [{ type: 'text', text: 'done' }] as any, stop_reason: 'end_turn' },- ]);- const ctx = await makeCtx({ prompt: 'go' });- const result = await makeSubagentHandler({ engine, client, toolRegistry: [tool] })(ctx);- expect(result.stop_reason).toBe('end_turn');- expect(client.calls.length).toBe(2);- expect(ids).toEqual(Array(3).fill(ids[0]));- const rows = await engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id = $1', [ctx.id]);- expect(rows.map(row => row.status)).toEqual(['complete']);- });-test('tool throws: row goes failed, model sees error, loop continues', async () => {const tool = makeThrowingTool();const client = new FakeMessagesClient([@@ -1458,3 +1441,118 @@ describe('handler-entry capability gate on the resolved model', () => {}});});++describe('legacy loop: an accepted tool write that is still pending (#5474)', () => {+ // A deadline this far out leaves a replay window well past every case below.+ const farDeadline = () => Date.now() + 10 * 60_000;+ /** A put_page whose write is pending for `pendingFor` dispatches, then lands in `settles`. */+ function stagedWrite(pendingFor: number, opts: { throwPending?: boolean; settles?: 'committed' | 'failed'; retryAfterMs?: number } = {}) {+ const requestIds: unknown[] = [];+ const tool: ToolDef = { ...makeEchoTool('brain_put_page'), async execute(input) {+ const request_id = (input as Record<string, unknown>).request_id; requestIds.push(request_id);+ if (requestIds.length > pendingFor) return { request_id, state: opts.settles ?? 'committed', retry_after_ms: null };+ const receipt = { request_id, state: 'queued', retry_after_ms: opts.retryAfterMs ?? 10 };+ if (!opts.throwPending) return receipt;+ const pending = new OperationError('write_pending', 'The write is accepted and is still pending.', 'Read its receipt.');+ pending.writeRequest = receipt as never; pending.writeError = 'write_pending';+ throw pending;+ } };+ return { tool, requestIds };+ }+ const oneWriteThenDone = () => new FakeMessagesClient([+ { content: [{ type: 'tool_use', id: 'tu_w', name: 'brain_put_page', input: { slug: 'notes/staged-example', content: 'x' } } as any], stop_reason: 'tool_use' as any },+ { content: [{ type: 'text', text: 'done' }] as any, stop_reason: 'end_turn' },+ ]);+ const rowStatuses = async (jobId: number) =>+ (await engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id = $1', [jobId])).map(r => r.status);++ for (const throwPending of [false, true]) {+ test(`a ${throwPending ? 'thrown write_pending' : 'returned queued receipt'} is replayed under one request id until it commits`, async () => {+ const { tool, requestIds } = stagedWrite(4, { throwPending });+ const client = oneWriteThenDone();+ const ctx = { ...(await makeCtx({ prompt: 'go' })), deadlineAtMs: farDeadline() };+ const result = await makeSubagentHandler({ engine, client, toolRegistry: [tool] })(ctx);+ expect(result.stop_reason).toBe('end_turn');+ expect(client.calls.length).toBe(2);+ expect(requestIds).toHaveLength(5);+ expect(new Set(requestIds).size).toBe(1);+ expect(await rowStatuses(ctx.id)).toEqual(['complete']);+ });+ }++ test('the replay window follows the job deadline, not the shorter maintenance wait', async () => {+ const restore = __setMaintenanceWriteWaitForTests(0);+ try {+ const { tool, requestIds } = stagedWrite(3);+ const ctx = { ...(await makeCtx({ prompt: 'go' })), deadlineAtMs: farDeadline() };+ const result = await makeSubagentHandler({ engine, client: oneWriteThenDone(), toolRegistry: [tool] })(ctx);+ expect(result.stop_reason).toBe('end_turn');+ expect(requestIds).toHaveLength(4);+ } finally { restore(); }+ });++ test('a job without a deadline replays only for the maintenance wait, then stays pending', async () => {+ const restore = __setMaintenanceWriteWaitForTests(120);+ try {+ const { tool, requestIds } = stagedWrite(Number.MAX_SAFE_INTEGER);+ const client = oneWriteThenDone();+ const ctx = await makeCtx({ prompt: 'go' });+ const started = Date.now();+ const failure = await makeSubagentHandler({ engine, client, toolRegistry: [tool] })(ctx).then(() => null, (e: unknown) => e);+ expect(failure).toMatchObject({ code: 'write_pending', writeRequest: { request_id: requestIds[0] } });+ expect(Date.now() - started).toBeGreaterThanOrEqual(100);+ expect(Date.now() - started).toBeLessThan(3_000);+ expect(requestIds.length).toBeGreaterThan(2);+ expect(new Set(requestIds).size).toBe(1);+ expect(client.calls.length).toBe(1);+ expect(await rowStatuses(ctx.id)).toEqual(['pending']);+ } finally { restore(); }+ });++ test('a job already inside its deadline reserve does not replay', async () => {+ const { tool, requestIds } = stagedWrite(Number.MAX_SAFE_INTEGER);+ const ctx = { ...(await makeCtx({ prompt: 'go' })), deadlineAtMs: Date.now() + 40_000 };+ await expect(makeSubagentHandler({ engine, client: oneWriteThenDone(), toolRegistry: [tool] })(ctx)).rejects.toMatchObject({ code: 'write_pending' });+ expect(requestIds).toHaveLength(1);+ expect(await rowStatuses(ctx.id)).toEqual(['pending']);+ });++ test('cancelling the job ends a long pause with the pending receipt and dispatches nothing more', async () => {+ const { tool, requestIds } = stagedWrite(Number.MAX_SAFE_INTEGER, { retryAfterMs: 20_000 });+ const cancel = new AbortController();+ const ctx = { ...(await makeCtx({ prompt: 'go' })), deadlineAtMs: farDeadline(), signal: cancel.signal };+ const started = Date.now();+ const settled = makeSubagentHandler({ engine, client: oneWriteThenDone(), toolRegistry: [tool] })(ctx).then(() => null, (e: unknown) => e);+ setTimeout(() => cancel.abort(new Error('example cancel')), 80);+ expect(await settled).toMatchObject({ code: 'write_pending', writeRequest: { request_id: requestIds[0], state: 'queued' } });+ expect(Date.now() - started).toBeLessThan(5_000);+ await new Promise(resolve => setTimeout(resolve, 150));+ expect(requestIds).toHaveLength(1);+ expect(await rowStatuses(ctx.id)).toEqual(['pending']);+ });++ test('a write that ended failed is reported to the model, not replayed', async () => {+ const { tool, requestIds } = stagedWrite(0, { settles: 'failed' });+ const client = oneWriteThenDone();+ const ctx = { ...(await makeCtx({ prompt: 'go' })), deadlineAtMs: farDeadline() };+ const result = await makeSubagentHandler({ engine, client, toolRegistry: [tool] })(ctx);+ expect(result.stop_reason).toBe('end_turn');+ expect(requestIds).toHaveLength(1);+ expect(client.calls.length).toBe(2);+ expect(await rowStatuses(ctx.id)).toEqual(['failed']);+ });++ test('a tool that is not a journal mutation passes a queued-looking result straight through', async () => {+ let dispatches = 0;+ const lookalike: ToolDef = { ...makeEchoTool('brain_search'), async execute() {+ dispatches++; return { request_id: '00000000-0000-4000-8000-000000000000', state: 'queued', retry_after_ms: 10 };+ } };+ const client = new FakeMessagesClient([+ { content: [{ type: 'tool_use', id: 'tu_s', name: 'brain_search', input: { query: 'x' } } as any], stop_reason: 'tool_use' as any },+ { content: [{ type: 'text', text: 'done' }] as any, stop_reason: 'end_turn' },+ ]);+ const ctx = { ...(await makeCtx({ prompt: 'go' })), deadlineAtMs: farDeadline() };+ expect((await makeSubagentHandler({ engine, client, toolRegistry: [lookalike] })(ctx)).stop_reason).toBe('end_turn');+ expect(dispatches).toBe(1);+ });+});diff --git a/test/subagent-pending-tool-write.test.ts b/test/subagent-pending-tool-write.test.tsdeleted file mode 100644index 08b8ec8bb2..0000000000--- a/test/subagent-pending-tool-write.test.ts+++ /dev/null@@ -1,172 +0,0 @@-/**- * #5474: a subagent child whose accepted brain write is still committing when- * the tool's own bounded wait ends replays the same request id until the write- * is terminal, up to the job deadline, instead of leaving the handler as a- * failed attempt. Before the fix every runner counted `write_pending` as an- * ordinary failure: the dream inline drain retried at once, the worker after- * 1 s and 2 s, so a write committing after its third 5 s wait killed the child- * although the page committed, and the next cycle paid to synthesize it again.- * Existing tests pin the handler's rejection after one wait and the resumed- * replay, not the child's outcome under a runner. Uses the existing gateway- * chat-transport and maintenance-wait test seams.- */-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';-import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { resetPgliteState } from './helpers/reset-pglite.ts';-import { LATEST_VERSION } from '../src/core/migrate.ts';-import { MinionQueue } from '../src/core/minions/queue.ts';-import { MinionWorker } from '../src/core/minions/worker.ts';-import { runSubagentsInline } from '../src/core/cycle/inline-drain.ts';-import { makeSubagentHandler } from '../src/core/minions/handlers/subagent.ts';-import { OperationError } from '../src/core/ops/contract.ts';-import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';-import { WIRE_WRITE_WAIT_MAX_MS } from '../src/core/persistence/params.ts';-import { WRITE_ADMISSION_HEADROOM_MS } from '../src/core/persistence/write-wait.ts';-import type { MinionJobContext, ToolDef } from '../src/core/minions/types.ts';-import { __setChatTransportForTests, configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';--let engine: PGLiteEngine;-let modelTurns = 0;-beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); });-afterAll(async () => { __setChatTransportForTests(null); resetGateway(); await engine.disconnect(); });-beforeEach(async () => {- await resetPgliteState(engine);- await engine.setConfig('version', String(LATEST_VERSION));- await engine.setConfig('agent.use_gateway_loop', 'true');- configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,- expansion_model: 'anthropic:claude-haiku-4-5', env: { ANTHROPIC_API_KEY: 'stub', OPENAI_API_KEY: 'stub' } } as never);- modelTurns = 0;- __setChatTransportForTests(async () => {- modelTurns++;- return { text: modelTurns === 1 ? '' : 'done', blocks: modelTurns === 1- ? [{ type: 'tool-call', toolCallId: 'call-1', toolName: 'brain_put_page', input: { slug: 'notes/pending-example', content: 'fixture' } }]- : [{ type: 'text', text: 'done' }], stopReason: modelTurns === 1 ? 'tool_calls' : 'end',- usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },- model: 'openai:gpt-4o', providerId: 'openai' } satisfies ChatResult;- });-});--type Shape = 'returned receipt' | 'thrown write_pending';-/** A put_page whose write commits on dispatch `commitsOn`; earlier dispatches report it queued, as the real tool does after its 5 s wait. */-function putPage(shape: Shape, commitsOn: number, retryAfterMs: (dispatch: number) => number = () => 20) {- const ids: unknown[] = [];- const tool: ToolDef = { name: 'brain_put_page', description: 'p', input_schema: { type: 'object' }, idempotent: true,- execute: async input => {- const request_id = (input as Record<string, unknown>).request_id; ids.push(request_id);- if (ids.length >= commitsOn) return { request_id, state: 'committed', retry_after_ms: null };- const receipt = { request_id, state: 'queued', retry_after_ms: retryAfterMs(ids.length) };- if (shape === 'returned receipt') return receipt;- const error = new OperationError('write_pending', 'The write is accepted and is still pending.', 'Read the receipt until it is terminal.');- error.writeRequest = receipt as never; error.writeError = 'write_pending';- throw error;- } };- return { tool, ids };-}-const handlerFor = (tool: ToolDef) => makeSubagentHandler({ engine, config: {} as never, toolRegistry: [tool],- makeAnthropic: () => ({ messages: { create: async () => { throw new Error('legacy path unused'); } } }) as never });-const toolRows = (jobId: number) => engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id=$1', [jobId]);--async function runOnWorker(handler: ReturnType<typeof handlerFor>): Promise<number> {- const queue = new MinionQueue(engine);- const job = await queue.add('subagent', { prompt: 'persist the fixture', model: 'openai:gpt-4o' }, {}, { allowProtectedSubmit: true });- const worker = new MinionWorker(engine, { pollInterval: 25 });- worker.register('subagent', handler);- const running = worker.start();- for (let i = 0; i < 400 && !['completed', 'dead', 'failed'].includes((await queue.getJob(job.id))!.status); i++) await new Promise(r => setTimeout(r, 25));- worker.stop(); await running;- return job.id;-}-async function runInline(handler: ReturnType<typeof handlerFor>): Promise<number> {- const queue = new MinionQueue(engine);- const queueName = `dream-inline-${Date.now()}-5474abcd`;- const job = await queue.add('subagent', { prompt: 'persist the fixture', model: 'openai:gpt-4o' }, { queue: queueName }, { allowProtectedSubmit: true });- await runSubagentsInline(engine, queue, queueName, undefined, handler);- return job.id;-}--describe('a child waits for its accepted tool write instead of dying (#5474)', () => {- // A child with a deadline waits up to it: the maintenance wait (here 50 ms)- // bounds only a job without one.- let restoreWait: () => void = () => {};- beforeEach(() => { restoreWait = __setMaintenanceWriteWaitForTests(50); });- afterEach(() => restoreWait());-- const cases = (['dream inline drain', 'worker'] as const).flatMap(runner =>- (['returned receipt', 'thrown write_pending'] as const).map(shape => [runner, shape] as const));- test.each(cases)('%s, %s: the write commits after several bounded waits and the child completes', async (runner, shape) => {- const { tool, ids } = putPage(shape, 8);- const jobId = await (runner === 'worker' ? runOnWorker : runInline)(handlerFor(tool));- const job = (await new MinionQueue(engine).getJob(jobId))!;- expect({ status: job.status, error: job.error_text }).toEqual({ status: 'completed', error: null });- expect(ids).toHaveLength(8);- expect(new Set(ids).size).toBe(1);- expect(modelTurns).toBe(2);- expect((await toolRows(jobId)).map(row => row.status)).toEqual(['complete']);- }, 20_000);-- test.each([- // Inside the reserve (the longest model wait_ms plus admission headroom) the wait ends at once,- // so the retry starts before the runner's timeout marks the job dead.- ['the job deadline is inside its reserve', { deadlineInMs: 30_000, abortInMs: null, replays: false }],- // The fourth receipt asks for a 10 s pause; the cancellation must end it.- ['the job is cancelled', { deadlineInMs: 120_000, abortInMs: 300, replays: true }],- ] as const)('a write still pending when %s leaves the handler pending before the deadline', async (_when, { deadlineInMs, abortInMs, replays }) => {- const { tool, ids } = putPage('thrown write_pending', Number.POSITIVE_INFINITY, dispatch => dispatch < 4 ? 20 : 10_000);- const queue = new MinionQueue(engine);- const job = await queue.add('subagent', { prompt: 'persist the fixture', model: 'openai:gpt-4o' }, {}, { allowProtectedSubmit: true });- const abort = new AbortController();- if (abortInMs !== null) setTimeout(() => abort.abort(new Error('cancelled')), abortInMs);- const deadlineAtMs = Date.now() + deadlineInMs;- const ctx = { id: job.id, name: 'subagent', data: job.data, attempts_made: 0, signal: abort.signal, deadlineAtMs, shutdownSignal: new AbortController().signal,- updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {}, isActive: async () => true, readInbox: async () => [] } as MinionJobContext;- const started = Date.now();- const error = await handlerFor(tool)(ctx).then(() => null, (e: unknown) => e as OperationError);- expect(error).toMatchObject({ code: 'write_pending', writeRequest: { state: 'queued', request_id: ids[0] } });- expect(Date.now()).toBeLessThan(deadlineAtMs);- expect(Date.now() - started).toBeLessThan(5_000);- expect(ids.length > 1).toBe(replays);- expect(new Set(ids).size).toBe(1);- expect(modelTurns).toBe(1);- expect((await toolRows(job.id)).map(row => row.status)).toEqual(['pending']);- // An aborted wait stops replaying: no dispatch lands after the handler left.- const dispatched = ids.length;- await new Promise(r => setTimeout(r, 200));- expect(ids).toHaveLength(dispatched);- }, 20_000);-- async function directCtx(deadlineAtMs: number | null) {- const job = await new MinionQueue(engine).add('subagent', { prompt: 'persist the fixture', model: 'openai:gpt-4o' }, {}, { allowProtectedSubmit: true });- return { id: job.id, name: 'subagent', data: job.data, attempts_made: 0, signal: new AbortController().signal, deadlineAtMs,- shutdownSignal: new AbortController().signal, updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {},- isActive: async () => true, readInbox: async () => [] } as MinionJobContext;- }-- test('a write that never commits holds the job until the deadline less the reserve, then leaves it pending', async () => {- const holdMs = 600;- const { tool, ids } = putPage('returned receipt', Number.POSITIVE_INFINITY);- const deadlineAtMs = Date.now() + WIRE_WRITE_WAIT_MAX_MS + WRITE_ADMISSION_HEADROOM_MS + holdMs;- const ctx = await directCtx(deadlineAtMs);- const started = Date.now();- await expect(handlerFor(tool)(ctx)).rejects.toMatchObject({ code: 'write_pending', writeRequest: { state: 'queued' } });- const held = Date.now() - started;- expect(held).toBeGreaterThanOrEqual(holdMs - 100);- expect(held).toBeLessThan(holdMs + 2_000);- expect(ids.length).toBeGreaterThan(5);- expect(new Set(ids).size).toBe(1);- expect(modelTurns).toBe(1);- expect((await toolRows(ctx.id)).map(row => row.status)).toEqual(['pending']);- }, 20_000);-- test('a write that ended failed is not replayed; the model sees the failure on its next turn', async () => {- const ids: unknown[] = [];- const tool: ToolDef = { name: 'brain_put_page', description: 'p', input_schema: { type: 'object' }, idempotent: true,- execute: async input => {- const request_id = (input as Record<string, unknown>).request_id; ids.push(request_id);- return { request_id, state: 'failed', retry_after_ms: null };- } };- const ctx = await directCtx(Date.now() + 120_000);- await handlerFor(tool)(ctx);- expect(ids).toHaveLength(1);- expect(modelTurns).toBe(2);- }, 20_000);-});