Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(claude-cli): map the output-cap error envelope to finishReason length (#6523)
garrytan72e8c38dde38
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex afe6cf4f41..bf16c696f6 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -46,6 +46,7 @@ link it here rather than raising the cap.| [Core Minions (2/2)](key-files/core-minions-2.md) | `src/core/minions/run-child.ts` through `src/core/minions/worker.ts` || [Core Persistence](key-files/core-persistence.md) | `src/core/persistence/` write journal, coordinator, effects, canonical projections and managed sync || [Core Persistence (continued)](key-files/core-persistence-continued.md) | `worktree-refresh*.ts`, `persistence/connector-*.ts`, `connectors/item-holds*.ts`, checkpoint validation, no-op kernel, accepted-pending receipts, verb types/errors, attribution, purge-deleted, fact retirement, sync orphans |+| [Core Persistence (managed facts)](key-files/core-persistence-facts.md) | `facts-maintenance.ts`, `facts-prepare.ts`, `derived-facts.ts`, `src/core/facts/conversation-publication.ts` || [Core Persistence (engine graduation)](key-files/core-persistence-graduation.md) | `engine-graduation*.ts`, `graduation-*.ts`, `src/commands/migrate-graduation.ts`, its doctor finding || [Managed sync and persistence stalls](key-files/persistence-stalls.md) | preparation budgets, `claim-phase.ts`, `consumer.ts`, `group-publish.ts`, `journal.ts`, `diagnostics.ts`, `worktree-manifest.ts` || [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/read-policy-sql.ts` |diff --git a/docs/architecture/key-files/core-ai-continued.md b/docs/architecture/key-files/core-ai-continued.mdindex 13cea12271..f7a5f18298 100644--- a/docs/architecture/key-files/core-ai-continued.md+++ b/docs/architecture/key-files/core-ai-continued.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.Provider adapters, recipes and the Voyage width plumbing.-- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter over the local `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt JSON: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt asks for no id and a stray `id` is ignored (nothing round-trips it; the loop pairs results in memory within one turn). Every child gets `--settings '{"disableAllHooks":true}'` (#5820: user/project hooks never run, so gbrain's own Stop hook cannot bank the call; login is untouched; managed-policy hooks still run on 2.1.287). A CLI that rejects any flag (`unknown option`) fails with `claude CLI 2.0.60 or newer required (found <version>)` (`MIN_CLAUDE_CLI_VERSION`, probed: 2.0.59 rejects `--disable-slash-commands`). No doStream: gateway.toolLoop uses doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`. `claudeCliFinishReason` maps the CLI's `stop_reason` to the finish reason (`max_tokens` → `length`, `refusal` → `content-filter`, parsed tool calls → `tool-calls`, anything else → `stop`), so callers can refuse clipped answers (`test/claude-cli-stop-reason.test.ts`). `renderPrompt` replays an earlier tool call with its input as JSON (`[tool_use name({...})]`). #6424: a positive integer `maxOutputTokens` reaches the child as `CLAUDE_CODE_MAX_OUTPUT_TOKENS` (env, `--settings` env).+- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter over the local `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt JSON: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt asks for no id and a stray `id` is ignored (nothing round-trips it; the loop pairs results in memory within one turn). Every child gets `--settings '{"disableAllHooks":true}'` (#5820: user/project hooks never run, so gbrain's own Stop hook cannot bank the call; login is untouched; managed-policy hooks still run on 2.1.287). A CLI that rejects any flag (`unknown option`) fails with `claude CLI 2.0.60 or newer required (found <version>)` (`MIN_CLAUDE_CLI_VERSION`, probed: 2.0.59 rejects `--disable-slash-commands`). No doStream: gateway.toolLoop uses doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`. `claudeCliFinishReason` maps the CLI's `stop_reason` to the finish reason (`max_tokens` → `length`, `refusal` → `content-filter`, parsed tool calls → `tool-calls`, anything else → `stop`), so callers can refuse clipped answers (`test/claude-cli-stop-reason.test.ts`). `renderPrompt` replays an earlier tool call with its input as JSON (`[tool_use name({...})]`). #6424: a positive integer `maxOutputTokens` reaches the child as `CLAUDE_CODE_MAX_OUTPUT_TOKENS` (env, `--settings` env). #6523: the CLI reports a response that hit that cap (or its own default) as an `is_error` envelope whose `result` starts `API Error: Claude's response exceeded the N output token maximum`; `isOutputCapEnvelope` (anchored prefix, `is_error: true`, no `api_error_status`, string `result`, any cap, any exit code) resolves it as a success with empty text and `stop_reason: 'max_tokens'`, so callers see `length` and their escalation ladders run (loops_extract 2048 → 8192, facts/extract 1× → 2×); every other error envelope stays `ClaudeCliProcessError` (`test/claude-cli-output-cap.test.ts`).- `src/core/ai/providers/claude-cli-scratch.ts` — the claude-cli provider's per-PID scratch dirs (`claudeCliCwdDir`/`claudeCliConfigDir` off the `CLAUDE_CLI_CWD_PREFIX`/`CLAUDE_CLI_CONFIG_PREFIX` basename constants, plus `sweepDeadClaudeCliScratchDirs`), split into a dependency-light module so transcript discovery (`src/core/transcripts/discover.ts`) can call `isClaudeCliSelfTranscriptPath(path)` WITHOUT importing the provider's @ai-sdk surface. Each `claude --print` subprocess runs with cwd = a per-PID scratch dir (context isolation — no local CLAUDE.md auto-discovery), and Claude Code records a session transcript for that cwd under `~/.claude/projects/<slugified-cwd>/`; those sessions are gbrain's OWN internal LLM calls, and importing them back is a self-ingestion feedback loop (prompt scaffolding + page content re-entering as "conversations"). The prefix is lowercase `[a-z-]` only, so it survives Claude Code's cwd slugification verbatim and a substring match on the discovered path is a reliable self-exclusion fingerprint. `claudeCliSelfSessionIds(projectsRoot = claudeProjectsDir())` lists the session ids of those harness transcripts; `isClaudeCliSelfSessionId(id, projectDirs = claudeCliSelfProjectDirs())` is the single-session classifier (#5820) shared by the serve-side writeback harvest, the sweep and doctor `self_capture`: one listing of the projects root, then an existence check per prefix-matched scratch project (path-shaped ids are refused); the session-end hook named each corpus file `<session id>.txt`, so dream discovery and the sweep's corpus pass use the set to skip self-captures written before the hook refused them (best-effort: a pruned harness transcript leaves its capture unclassifiable). Pinned by `test/transcripts-self-exclusion.test.ts`.diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.mdnew file mode 100644index 0000000000..0707d64ddf--- /dev/null+++ b/docs/architecture/key-files/core-persistence-facts.md@@ -0,0 +1,9 @@+# Key files: Core Persistence (managed facts)++[Subsystem index](../KEY_FILES.md) · [Core Persistence](core-persistence.md). Read only the entries relevant to your change.+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+Managed facts extraction: the entity-intent preparer and publisher, conversation facts batches and the unmanaged derived index. The extraction pipeline itself is in [Google and Loops (continued)](google-and-loops-continued.md) (`src/core/facts/backstop.ts`) and [Core Services (2/3)](core-services-2.md) (`src/core/facts/extract.ts`).++- `src/core/persistence/{facts-maintenance,facts-prepare}.ts` — the managed facts publisher and preparer behind the backstop's `publishManagedFacts` / `resumeManagedFacts` and the explicit fact writers (`managed-fact-write.ts`, `remember`); the shared maintenance dispatch they ride is in [Core Persistence](core-persistence.md). `facts-maintenance.ts` / `facts-prepare.ts` (#6506): an automatic extraction's entity intent carries `withdrawn: 'skip'` (set by the backstop's `publishManagedFacts` call, never by `managed-fact-write.ts` or `remember`), under which `prepareManagedFactsMutation` skips a candidate `isFactWithdrawn` matches (after `assertFactNotPurged`, which still refuses `purged_content`) and counts it as `withdrawn_skipped` on the entity outcome, summed into the completion outcome, `ManagedFactsResult` and the `extract_facts` result (the unmanaged pipeline counts its own B-10 skip into the same field); without the flag the refusal stands. At locked validation the per-entry purge and withdrawal checks run before the page's fence re-validation, and under the flag a claim forgotten since preparation refuses `revision_conflict` with `error.withdrawn` (so the receipt's `error_detail.origin` is `withdrawal`); no `extract_facts` request is re-prepared. `resumeManagedFacts` runs `followWithdrawalRefusals` for an input-keyed session (`inputKeyed`, no request id): the `followFileRefusals` walk generalized as `followRefusals`, matching entity refusals by `withdrawnFromDetail(error_detail)` or the pre-detail `invalid_params` + `FACT_WITHDRAWN_MESSAGE` pair, re-admitting the retained facts under `digest([batchKey, 'withdrawal-retry', n])` with the flag (`readmitWithdrawnFacts`: a fact forgotten at its retained visibility keeps that visibility so preparation skips it instead of narrowing it to private), bounded by `MAX_FILE_REFUSAL_RETRIES`, historical receipts untouched. Tests: `test/managed-facts-withdrawn-skip-6506.test.ts`, `test/managed-facts-withdrawal-recovery-6506.test.ts` (PGLite and Postgres).+- `src/core/persistence/derived-facts.ts` — `writeDerivedFacts`: the unmanaged conversation fact index commits in one maintenance transaction under the maintenance principal; on a managed brain it refuses with `writer_coordinator_required`, because every managed facts/takes writer publishes a receipted maintenance request (`test/receipt-coverage.test.ts` lists every coordinated write site). Tests: `test/write-attribution-misc.test.ts`.+- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` batch requests (`submitDatabaseMaintenanceIntent` on `ANCHOR_SLUG`, a dot-led slug no page can hold, dispatched from `prepareMaintenanceMutation`). Each page's frozen entry (`buildConversationPage`: `FrozenExtractedFact` rows, its generation and attempt, vectors only under the brain's facts embedding signature) joins the run's batch; `enqueueManagedPage` publishes it once `DEFAULT_BATCH_CAPS` is reached (25 pages, 10 with extracted facts, 8 MiB) and `flushManagedBatch` at the end of the run. The generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, selectors, newest extractor row id) is checked before model work by `startManagedPage` against `loadGenerationIndex` (the writer's unsettled and failed batches on the anchor, read once per run): a member of an unsettled batch waits and replays its receipt, a member of a retryably failed batch is resubmitted from its stored entry, a deterministic failure or three failed batches block it; all without model calls. The batch request id digests its members' (generation, attempt) pairs. The preparer locks every member's key and applies each on its own (`applyEntry`): a deleted, replaced or moved page is skipped and reported, a page whose rows fail validation gets a durable `blocked:` not-extractable outcome, vectors under another signature are dropped; none fails the batch. `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest entry cannot fit before any model call; `assertConversationAdmissionHeadroom` stops admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the run's planned batches and before each new batch. `replaceConversationFacts` deletes the page's extractor rows (expiring referenced and keeping label-retired ones) and inserts the entry numbered above every remaining row, failing on a lost insert. Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 6315cca10f..f0aaa1c89a 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -4,6 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.The page operations that submit through this layer are in [Core Services (2/3)](core-services-2.md).Connector ingestion, item holds, checkpoint validation and the single-write fast path (`switches.ts`) continue in [Core Persistence (continued)](core-persistence-continued.md).+Managed facts extraction (withdrawn-candidate skip and recovery, conversation facts batches, the unmanaged derived index) is in [Core Persistence (managed facts)](core-persistence-facts.md).- `src/core/persistence/connector-google-receipts.ts` — the managed Google attachment-repair preparer checks account/thread/message ownership from the current canonical snapshot, changes only the owned receipt frontmatter field, and installs provider-free text projections under the existing source-before-page publication locks. Page identity/revision, current authorization, source incarnation and file recovery guards remain mandatory; body, unrelated frontmatter, tags and the withdrawal ledger are preserved. It schedules no embeddings, loop detection or fact extraction. `connector-sync.ts` admits this narrow mutation and banks its committed receipts through the existing managed connector checkpoints.@@ -15,14 +16,12 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.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. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. `facts-maintenance.ts` / `facts-prepare.ts` (#6506): an automatic extraction's entity intent carries `withdrawn: 'skip'` (set by the backstop's `publishManagedFacts` call, never by `managed-fact-write.ts` or `remember`), under which `prepareManagedFactsMutation` skips a candidate `isFactWithdrawn` matches (after `assertFactNotPurged`, which still refuses `purged_content`) and counts it as `withdrawn_skipped` on the entity outcome, summed into the completion outcome, `ManagedFactsResult` and the `extract_facts` result (the unmanaged pipeline counts its own B-10 skip into the same field); without the flag the refusal stands. At locked validation the per-entry purge and withdrawal checks run before the page's fence re-validation, and under the flag a claim forgotten since preparation refuses `revision_conflict` with `error.withdrawn` (so the receipt's `error_detail.origin` is `withdrawal`); no `extract_facts` request is re-prepared. `resumeManagedFacts` runs `followWithdrawalRefusals` for an input-keyed session (`inputKeyed`, no request id): the `followFileRefusals` walk generalized as `followRefusals`, matching entity refusals by `withdrawnFromDetail(error_detail)` or the pre-detail `invalid_params` + `FACT_WITHDRAWN_MESSAGE` pair, re-admitting the retained facts under `digest([batchKey, 'withdrawal-retry', n])` with the flag (`readmitWithdrawnFacts`: a fact forgotten at its retained visibility keeps that visibility so preparation skips it instead of narrowing it to private), bounded by `MAX_FILE_REFUSAL_RETRIES`, historical receipts untouched. Tests: `test/managed-facts-withdrawn-skip-6506.test.ts`, `test/managed-facts-withdrawal-recovery-6506.test.ts` (PGLite and Postgres).+- `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. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. Managed facts extraction (the withdrawn-candidate skip and its recovery route, the conversation facts batches, the unmanaged derived index) continues in [Core Persistence (managed facts)](core-persistence-facts.md).- `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.Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. `submitMaintenanceIntent` admits a maintenance request with its own intent kind keyed by the intent; `prepareMaintenanceMutation` also handles `managed_maintenance_phantom_merge` and `managed_maintenance_phantom_delete` (both delegated to `cycle/phantom-redirect-managed.ts`). `publishMaintenancePage` accepts an optional `eventProjection` (Life Chronicle): the event page and its depth-page timeline row commit in the same publication with the depth page key locked. Remote maintenance remains refused.-- `src/core/persistence/derived-facts.ts` — `writeDerivedFacts`: the unmanaged conversation fact index commits in one maintenance transaction under the maintenance principal; on a managed brain it refuses with `writer_coordinator_required`, because every managed facts/takes writer publishes a receipted maintenance request (`test/receipt-coverage.test.ts` lists every coordinated write site). Tests: `test/write-attribution-misc.test.ts`.-- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` batch requests (`submitDatabaseMaintenanceIntent` on `ANCHOR_SLUG`, a dot-led slug no page can hold, dispatched from `prepareMaintenanceMutation`). Each page's frozen entry (`buildConversationPage`: `FrozenExtractedFact` rows, its generation and attempt, vectors only under the brain's facts embedding signature) joins the run's batch; `enqueueManagedPage` publishes it once `DEFAULT_BATCH_CAPS` is reached (25 pages, 10 with extracted facts, 8 MiB) and `flushManagedBatch` at the end of the run. The generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, selectors, newest extractor row id) is checked before model work by `startManagedPage` against `loadGenerationIndex` (the writer's unsettled and failed batches on the anchor, read once per run): a member of an unsettled batch waits and replays its receipt, a member of a retryably failed batch is resubmitted from its stored entry, a deterministic failure or three failed batches block it; all without model calls. The batch request id digests its members' (generation, attempt) pairs. The preparer locks every member's key and applies each on its own (`applyEntry`): a deleted, replaced or moved page is skipped and reported, a page whose rows fail validation gets a durable `blocked:` not-extractable outcome, vectors under another signature are dropped; none fails the batch. `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest entry cannot fit before any model call; `assertConversationAdmissionHeadroom` stops admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the run's planned batches and before each new batch. `replaceConversationFacts` deletes the page's extractor rows (expiring referenced and keeping label-retired ones) and inserts the entry numbered above every remaining row, failing on a lost insert. Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; #6226 rows the older citation reading filed for either body are `superseded` (deleted by every writer) or, carrying their own detail, `superseded_annotated` (kept, never materialized); a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. Fence refusals are typed `invalid_fence` (`fence-repair/refusal.ts`): `compileCanonicalProjections`, the validation-only entry, refuses the first defect `scanCanonicalFences` finds (repeated marker, any strict-parser warning, a row number used twice on the page) with wire `invalid_params`; a new fence row whose number belongs to a database-only take refuses as `stored_row_collision` with wire `take_row_collision`. When the prior takes fence does not parse, the page's stored `takes.row_num` count as prior canonical rows (TE1), so a row Tier 1 normalized updates its take instead of colliding. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres). A write that would drop rows held by a fence quoted in markdown code (readers project nothing from it) is refused as `invalid_fence` / `quoted_fence_rows` instead of deleting them. Pinned by `test/fence-marker-projection.test.ts`. #5969 (D3): an ordinary `put_page` / `put_pages` intent carries a `TimelineWritePolicy` (`timeline-omission.ts`) that changes only the rows the writer saw (`removed`, `removed_marked`): an explicitly empty section deletes them for every writer class; an omitted section keeps them for a local preserving writer (`materialize`) and deletes them with `drop_timeline`; maintenance, reconcile and file writers pass no policy. The pinned timeline `DELETE` returns what it removed, and the projection closure returns `{ timelineRowsRemoved: { count, earliest, latest } }` counting only `removed`/`removed_marked` rows it actually deleted (a row changed after preparation is neither deleted nor counted); `timelineRowsToRemove` judges the same set ahead of publication. #6259: a quarantined page (gate `quarantine` marker) projects no facts or takes (timeline rows still project); rows projected before it was quarantined stay as they are.- `src/core/persistence/timeline-omission.ts` — #5969 (D3): `timelineSectionOf` reads a put_page body's Timeline section from the caller's raw content before normalization (`omitted`: no timeline sentinel and no `## Timeline`/`## History` heading outside code; `emptied`: a section with no entries; `present`). Admission (`page-mutations.ts`) records it on the intent as `timeline_section` (a caller-sent value is stripped; failed-writes replay passes the stored one through `submitPageMutation`'s `timelineSection`). `assertTimelineNotOmitted` refuses a remote omission that would delete rows with `timeline_rows_would_be_removed` (fix: `get_page include_content:true`, then the `drop_timeline: true` retry) before admission and again during preparation; `timelineWritePolicy` builds the projection policy. Successful deletes surface as the receipt's `timeline_rows_removed` advisory (`page-advisories.ts`, dates only), copied onto `put_pages` entries (`page-batch.ts`, which accepts `drop_timeline` per entry).diff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.tsindex bd00b8ecd7..a96199898a 100644--- a/src/core/ai/providers/claude-cli-language-model.ts+++ b/src/core/ai/providers/claude-cli-language-model.ts@@ -186,6 +186,36 @@ function parseResultEnvelope(stdout: string): EnvelopeParse {* surfacing `api_error_status` + the human-readable `result` message instead of* an opaque blob.*/+/**+ * #6523: Claude Code reports a response that hit CLAUDE_CODE_MAX_OUTPUT_TOKENS+ * (the cap #6424 forwards, or the CLI's own default) as an error envelope,+ * not as a success with `stop_reason: 'max_tokens'`:+ * "API Error: Claude's response exceeded the 2048 output token maximum. To+ * configure this behavior, set the CLAUDE_CODE_MAX_OUTPUT_TOKENS+ * environment variable."+ * Rejecting on it hid the cap from every caller that escalates on `length`+ * (loops_extract 2048 → 8192, facts/extract 1× → 2×), so the minion queue+ * retried the same capped call and the job died. The match is the anchored+ * prefix only: the trailing advice has already changed wording once, the+ * reported cap may be the default rather than the forwarded one, and the exit+ * code varies by CLI version. A quoted prefix mid-answer, a success envelope,+ * a non-string result or an envelope carrying an API status never match.+ */+const OUTPUT_CAP_RE = /^API Error: Claude's response exceeded the \d+ output token maximum\b/;++function isOutputCapEnvelope(envelope: ClaudeJsonResult): boolean {+ return envelope.type === 'result'+ && envelope.is_error === true+ && envelope.api_error_status === undefined+ && typeof envelope.result === 'string'+ && OUTPUT_CAP_RE.test(envelope.result);+}++/** The cap envelope as the success the API would have returned: no text, `max_tokens`, usage as reported. */+function outputCapAsLength(envelope: ClaudeJsonResult): ClaudeJsonResult {+ return { ...envelope, is_error: false, result: '', stop_reason: 'max_tokens' };+}+function envelopeError(envelope: ClaudeJsonResult, exitCode: number | undefined): ClaudeCliProcessError {const status = typeof envelope.api_error_status === 'number' ? envelope.api_error_status : undefined;const detail = envelope.result || envelope.subtype;@@ -440,6 +470,10 @@ function runClaude(// reason lives in stderr, so it falls through to the blob fallback// (as does any stdout without a parseable envelope).const attempt = parseResultEnvelope(stdout);+ if (attempt.ok && isOutputCapEnvelope(attempt.envelope)) {+ resolve(outputCapAsLength(attempt.envelope));+ return;+ }if (attempt.ok && attempt.envelope.type === 'result' && attempt.envelope.is_error === true) {reject(envelopeError(attempt.envelope, code ?? undefined));return;@@ -468,6 +502,10 @@ function runClaude(return;}const envelope = attempt.envelope;+ if (isOutputCapEnvelope(envelope)) {+ resolve(outputCapAsLength(envelope));+ return;+ }if (envelope.is_error) {reject(envelopeError(envelope, 0));return;diff --git a/test/claude-cli-output-cap.test.ts b/test/claude-cli-output-cap.test.tsnew file mode 100644index 0000000000..14a0a5eaee--- /dev/null+++ b/test/claude-cli-output-cap.test.ts@@ -0,0 +1,291 @@+/**+ * #6523: since #6424 forwarded a call's `maxTokens` as+ * CLAUDE_CODE_MAX_OUTPUT_TOKENS, Claude Code reports a response that hits+ * that cap as an `is_error: true` result envelope ("API Error: Claude's+ * response exceeded the N output token maximum. ..."), not as a success with+ * `stop_reason: 'max_tokens'`. `runClaude` rejected on `is_error`, so no+ * caller ever saw `finishReason: 'length'` and the escalation ladders+ * (loops_extract 2048 → 8192, facts/extract 1× → 2×) never fired: the minion+ * queue retried the same capped call three times and the job died.+ *+ * The provider now maps that envelope (anchored prefix, `is_error: true`, no+ * `api_error_status`, any cap, any exit code) to `length` with empty text and+ * the usage as reported. Every other error envelope stays a typed failure.+ *+ * A POSIX shell stub at GBRAIN_CLAUDE_CLI_BIN plays the CLI; it records the+ * cap it was handed so the ladder cases can assert the sequence of calls.+ * "Real gateway" below means the gateway code path with the stub transport;+ * no live provider account is used.+ *+ * Supersedes PR #6525 (@javieraldape), whose full-sentence match and exit-code+ * gate missed the discriminator cases below (R16).+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { LanguageModelV2CallOptions } from '@ai-sdk/provider';+import { ClaudeCliLanguageModel, ClaudeCliProcessError } from '../src/core/ai/providers/claude-cli-language-model.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { LoopsExtractRetryableError, runLoopsExtract } from '../src/core/google/loops-extract.ts';+import { extractFactsFromTurnWithOutcome } from '../src/core/facts/extract.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const capMessage = (cap: number) =>+ `API Error: Claude's response exceeded the ${cap} output token maximum. To configure this behavior, set the CLAUDE_CODE_MAX_OUTPUT_TOKENS environment variable.`;+const USAGE = { input_tokens: 10, output_tokens: 2048, cache_read_input_tokens: 3, cache_creation_input_tokens: 2 };++function envelope(result: string, extra: Record<string, unknown> = {}): Record<string, unknown> {+ return {+ type: 'result', subtype: 'error_during_execution', is_error: true,+ result, stop_reason: null, session_id: 'synthetic-session', num_turns: 1, usage: USAGE,+ ...extra,+ };+}++interface Stub { dir: string; caps: () => string[] }++/**+ * Stage a stub `claude`. `responses` maps the forwarded cap (the env value,+ * '' when none was forwarded) to the stdout it prints and its exit code; `'*'`+ * is the fallback. Raw strings are printed verbatim (malformed stdout).+ */+async function withCli<T>(+ responses: Record<string, { body: unknown; exit: number }>,+ run: (stub: Stub) => Promise<T>,+): Promise<T> {+ const dir = mkdtempSync(join(tmpdir(), 'claude-output-cap-'));+ const capsPath = join(dir, 'caps');+ const lines = ['#!/bin/sh', 'cat > /dev/null', `printf '%s\\n' "$CLAUDE_CODE_MAX_OUTPUT_TOKENS" >> "${capsPath}"`];+ for (const [cap, { body, exit }] of Object.entries(responses)) {+ const file = join(dir, `response-${cap === '*' ? 'default' : cap}.txt`);+ writeFileSync(file, typeof body === 'string' ? body : JSON.stringify(body));+ if (cap !== '*') lines.push(`if [ "$CLAUDE_CODE_MAX_OUTPUT_TOKENS" = "${cap}" ]; then cat "${file}"; exit ${exit}; fi`);+ else lines.push(`cat "${file}"; exit ${exit}`);+ }+ if (!responses['*']) lines.push('echo "unexpected cap $CLAUDE_CODE_MAX_OUTPUT_TOKENS" >&2; exit 99');+ const bin = join(dir, 'claude');+ writeFileSync(bin, lines.join('\n') + '\n');+ chmodSync(bin, 0o755);+ const stub: Stub = { dir, caps: () => (existsSync(capsPath) ? readFileSync(capsPath, 'utf8').trimEnd().split('\n') : []) };+ try {+ return await withEnv({ GBRAIN_CLAUDE_CLI_BIN: bin, CLAUDE_CODE_MAX_OUTPUT_TOKENS: undefined }, () => run(stub));+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++function options(maxOutputTokens?: number): LanguageModelV2CallOptions {+ return {+ prompt: [{ role: 'user', content: [{ type: 'text', text: 'Synthetic thread' }] }],+ ...(maxOutputTokens === undefined ? {} : { maxOutputTokens }),+ } as LanguageModelV2CallOptions;+}++const generate = (opts = options(2048)) => new ClaudeCliLanguageModel('claude-sonnet-4-6').doGenerate(opts);++async function rejection(run: () => Promise<unknown>): Promise<unknown> {+ try {+ await run();+ } catch (error) {+ return error;+ }+ throw new Error('expected the call to reject');+}++describe('claude-cli output-cap envelope finishes as length (#6523)', () => {+ const positives: Array<[string, unknown, number, number | undefined]> = [+ ['exit 0, error_during_execution', envelope(capMessage(2048)), 0, 2048],+ ['exit 1', envelope(capMessage(2048)), 1, 2048],+ ['exit 2', envelope(capMessage(2048)), 2, 2048],+ ['verbose event-array form', [{ type: 'system', subtype: 'init' }, { type: 'assistant' }, envelope(capMessage(2048))], 1, 2048],+ ['subtype success as field-reported', envelope(capMessage(2048), { subtype: 'success' }), 1, 2048],+ ['no forwarded cap (the default cap was hit)', envelope(capMessage(32000)), 1, undefined],+ ['reported cap differs from the forwarded cap', envelope(capMessage(8192)), 1, 2048],+ ['changed trailing wording after the anchored prefix', envelope("API Error: Claude's response exceeded the 2048 output token maximum. Raise the limit in settings."), 1, 2048],+ ];+ for (const [label, body, exit, cap] of positives) {+ test(`${label} → length, empty text, usage as reported`, async () => {+ await withCli({ '*': { body, exit } }, async (stub) => {+ const out = await generate(options(cap));+ expect(out.finishReason).toBe('length');+ expect(out.content).toEqual([{ type: 'text', text: '' }]);+ expect(out.usage).toEqual({ inputTokens: 15, outputTokens: 2048, totalTokens: 2063, cachedInputTokens: 3 });+ expect(stub.caps()).toEqual([cap === undefined ? '' : String(cap)]);+ });+ });+ }++ test('usage absent → length with undefined usage, nothing invented', async () => {+ await withCli({ '*': { body: envelope(capMessage(2048), { usage: undefined }), exit: 1 } }, async () => {+ const out = await generate();+ expect(out.finishReason).toBe('length');+ expect(out.content).toEqual([{ type: 'text', text: '' }]);+ expect(out.usage).toEqual({ inputTokens: undefined, outputTokens: undefined, totalTokens: undefined, cachedInputTokens: undefined });+ });+ });++ test('error envelopes that are not the cap stay ClaudeCliProcessError with their status and exit code', async () => {+ const negatives: Array<[string, Record<string, unknown>]> = [+ ['api_error_status on the cap text', envelope(capMessage(2048), { api_error_status: 429 })],+ ['cap text after another sentence', envelope(`Authentication failed. ${capMessage(2048)}`, { api_error_status: 401 })],+ ['cap text quoted mid-answer', envelope(`Quoted provider documentation: ${capMessage(2048)}`)],+ ['insufficient credits', envelope('API Error: insufficient credits', { api_error_status: 402 })],+ ['server error carrying stop_reason max_tokens', envelope('API Error: transient server error', { stop_reason: 'max_tokens', api_error_status: 500 })],+ ['a non-string result', envelope(capMessage(2048), { result: { message: capMessage(2048) } })],+ ['is_error as a string', envelope(capMessage(2048), { is_error: 'true' })],+ ];+ for (const [label, body] of negatives) {+ for (const exit of [0, 1, 2]) {+ await withCli({ '*': { body, exit } }, async () => {+ const error = await rejection(generate);+ expect(error, `${label} (exit ${exit})`).toBeInstanceOf(ClaudeCliProcessError);+ expect((error as ClaudeCliProcessError).apiErrorStatus, label).toBe(body.api_error_status as number | undefined);+ expect((error as ClaudeCliProcessError).exitCode, label).toBe(exit);+ });+ }+ }+ });++ test('a success envelope quoting the prefix is ordinary model text', async () => {+ const quote = `The CLI said: ${capMessage(2048)}`;+ await withCli({ '*': { body: envelope(quote, { is_error: false, subtype: 'success', stop_reason: 'end_turn' }), exit: 0 } }, async () => {+ const out = await generate();+ expect(out.finishReason).toBe('stop');+ expect(out.content).toEqual([{ type: 'text', text: quote }]);+ });+ await withCli({ '*': { body: envelope(capMessage(2048), { is_error: false, subtype: 'success', stop_reason: 'end_turn' }), exit: 0 } }, async () => {+ const out = await generate();+ expect(out.finishReason).toBe('stop');+ expect(out.content).toEqual([{ type: 'text', text: capMessage(2048) }]);+ });+ });++ test('success + non-zero exit, exit 137 without an envelope, malformed stdout and a resultless event array still fail', async () => {+ await withCli({ '*': { body: envelope(capMessage(2048), { is_error: false, subtype: 'success' }), exit: 1 } }, async () => {+ const error = await rejection(generate);+ expect(error).toBeInstanceOf(ClaudeCliProcessError);+ expect((error as ClaudeCliProcessError).exitCode).toBe(1);+ });+ await withCli({ '*': { body: capMessage(2048), exit: 137 } }, async () => {+ const error = await rejection(generate);+ expect(error).toBeInstanceOf(ClaudeCliProcessError);+ expect((error as ClaudeCliProcessError).exitCode).toBe(137);+ });+ for (const body of [capMessage(2048), '"' + capMessage(2048) + '"', 'null', '2048']) {+ await withCli({ '*': { body, exit: 0 } }, async () => {+ const error = await rejection(generate);+ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain('claude-cli output not JSON');+ });+ }+ await withCli({ '*': { body: [{ type: 'system', subtype: 'init' }, { type: 'assistant', message: capMessage(2048) }], exit: 0 } }, async () => {+ const error = await rejection(generate);+ expect((error as Error).message).toContain('had no "result" event');+ });+ });+});++const success = (text: string, usage: Record<string, number> = { input_tokens: 10, output_tokens: 30 }) =>+ envelope(text, { is_error: false, subtype: 'success', stop_reason: 'end_turn', usage });++describe('escalation ladders through the gateway with the stub transport', () => {+ const engines: Array<{ backend: string; engine: BrainEngine }> = [];+ const dbDir = mkdtempSync(join(tmpdir(), 'claude-output-cap-db-'));+ let closePostgres: (() => Promise<void>) | undefined;++ beforeAll(async () => {+ for (const backend of testBackends()) {+ if (backend === 'pglite') {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dbDir });+ await engine.initSchema();+ engines.push({ backend, engine });+ } else {+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push({ backend, engine: isolated.engine });+ closePostgres = isolated.close;+ }+ }+ }, 120_000);+ afterEach(resetGateway);+ afterAll(async () => {+ for (const { engine } of engines) await engine.disconnect();+ await closePostgres?.();+ rmSync(dbDir, { recursive: true, force: true });+ });++ async function thread(engine: BrainEngine, slug: string) {+ await engine.executeRaw('DELETE FROM open_loops');+ await engine.putPage(slug, {+ type: 'email', title: 'Synthetic decision',+ compiled_truth: 'Which week works for the kickoff?',+ frontmatter: { thread_id: `thread-${slug}` },+ }, { sourceId: 'default' });+ configureGateway({ chat_model: 'claude-cli:claude-sonnet-4-6', env: {} });+ }++ test('loops_extract: a 2048 cap escalates once to 8192 and publishes the decision', async () => {+ const complete = success(JSON.stringify({+ commitments: [], decisions_pending: [{ text: 'Pick a kickoff week', quote: 'Which week works for the kickoff?' }],+ }));+ for (const { backend, engine } of engines) {+ await withCli({ '2048': { body: envelope(capMessage(2048)), exit: 1 }, '8192': { body: complete, exit: 0 } }, async (stub) => {+ await thread(engine, 'emails/output-cap-escalates');+ const result = await runLoopsExtract(engine, { slug: 'emails/output-cap-escalates', sourceId: 'default' });+ expect(result.status, backend).toBe('extracted');+ expect(result.decisions, backend).toBe(1);+ expect(stub.caps(), backend).toEqual(['2048', '8192']);+ const rows = await engine.executeRaw<{ summary: string }>('SELECT summary FROM open_loops');+ expect(rows.map(row => row.summary), backend).toEqual(['Pick a kickoff week']);+ });+ }+ }, 120_000);++ test('loops_extract: two cap failures stop at the ceiling as a retryable truncation with no rows and no third call', async () => {+ for (const { backend, engine } of engines) {+ await withCli({ '2048': { body: envelope(capMessage(2048)), exit: 1 }, '8192': { body: envelope(capMessage(8192)), exit: 1 } }, async (stub) => {+ await thread(engine, 'emails/output-cap-ceiling');+ const error = await rejection(() => runLoopsExtract(engine, { slug: 'emails/output-cap-ceiling', sourceId: 'default' }));+ expect(error, backend).toBeInstanceOf(LoopsExtractRetryableError);+ expect((error as LoopsExtractRetryableError).reason, backend).toBe('truncated');+ expect((error as Error).message, backend).toContain('8192-token');+ expect(stub.caps(), backend).toEqual(['2048', '8192']);+ expect(await engine.executeRaw('SELECT id FROM open_loops'), backend).toHaveLength(0);+ });+ }+ }, 120_000);++ test('facts/extract: a cap at the configured maximum retries once at twice the cap', async () => {+ const facts = success(JSON.stringify({+ facts: [{ fact: 'Alice-example will confirm the kickoff week in November.', entity: 'people/alice-example', kind: 'fact', confidence: 0.9, notability: 'medium' }],+ }));+ await withCli({ '4000': { body: envelope(capMessage(4000)), exit: 1 }, '8000': { body: facts, exit: 0 } }, async (stub) => {+ configureGateway({ chat_model: 'claude-cli:claude-sonnet-4-6', env: {} });+ const outcome = await extractFactsFromTurnWithOutcome({+ turnText: 'Alice-example said she will confirm the kickoff week in November.', source: 'test:output-cap',+ model: 'claude-cli:claude-sonnet-4-6',+ });+ expect(outcome.ok).toBe(true);+ if (outcome.ok) expect(outcome.facts.map(f => f.fact)).toEqual(['Alice-example will confirm the kickoff week in November.']);+ expect(stub.caps()).toEqual(['4000', '8000']);+ });+ }, 60_000);++ test('facts/extract: caps at both rungs end as truncated_output after exactly two calls', async () => {+ await withCli({ '4000': { body: envelope(capMessage(4000)), exit: 1 }, '8000': { body: envelope(capMessage(8000)), exit: 2 } }, async (stub) => {+ configureGateway({ chat_model: 'claude-cli:claude-sonnet-4-6', env: {} });+ const outcome = await extractFactsFromTurnWithOutcome({+ turnText: 'Alice-example said she will confirm the kickoff week in November.', source: 'test:output-cap',+ model: 'claude-cli:claude-sonnet-4-6',+ });+ expect(outcome.ok).toBe(false);+ if (!outcome.ok) expect(outcome.reason).toBe('truncated_output');+ expect(stub.caps()).toEqual(['4000', '8000']);+ });+ }, 60_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 183198b526..11b2570a83 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -18,6 +18,7 @@ test/behavior-change-notice.test.tstest/capture-consent-admission.test.tstest/capture-dispatch-provenance-6524.test.tstest/chronicle-backfill-max-usd.test.ts+test/claude-cli-output-cap.test.tstest/colon-slug-windows-5032.test.tstest/company-brain-policy.test.tstest/company-brain-runtime.test.ts