Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sweep): chat_unavailable leaves corpus files pending; cap paid retries of failing windows (#6785, #6786)

garrytan297c84752d7e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aa43192f51..9fff5bfab5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,34 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**Session transcripts are no longer marked done with zero facts, and a write that fails after extraction stops being paid for forever.** Two corpus-sweep bugs. `gbrain bootstrap verify` ran the corpus pass in a process that could not reach the extraction model, so every pending transcript came back `chat_unavailable`, got an `.ingested` marker with zero facts, and was deleted by retention a month later (#6786). Separately, when the fact write after extraction was refused (a canonical worktree claimed but not activated), nothing recorded the window, so the `serve --http` drain paid for the same extraction every 10 minutes, for hours, and threw the error away (#6785).
+
+### What you'd see
+
+| Situation | Before | Now |
+|---|---|---|
+| `gbrain bootstrap verify` with pending transcripts | each one marked `.ingested` with `skipped: chat_unavailable` and 0 facts | verify skips the corpus pass; the transcripts stay pending |
+| The sweep or a harvest has no usable extraction model | the file was marked done with 0 facts | the file stays pending (`corpus_chat_unavailable`) and is extracted once a model works |
+| A file an earlier build marked `skipped: chat_unavailable` | never extracted; deleted after 30 days | extracted again by the next sweeps, with its source binding and retired turns kept; kept until then (90 days by default) |
+| A source whose canonical worktree is claimed but not activated | paid for the extraction, then the write was refused, every sweep | held before any model call (`writer_coordinator_required`), naming `gbrain sources writer status <source>` |
+| A window keeps failing after its model call | paid again on every sweep, without limit | retried on the next sweep, then after 10, 20 and 40 minutes, then stopped (`corpus_window_dead_lettered`); one model or provider change retries it once |
+| Retrying stopped windows | no supported way | `gbrain sweep --retry-failed` previews, `--apply` retries (paid); `gbrain doctor` names it as the fix |
+| `serve --http` drain errors | discarded | skip reasons and failures go to serve's stderr |
+
+After upgrading, transcripts an earlier verify marked this way are extracted again. That is a one-time paid catch-up, bounded by the sweep's window caps (8 windows per file, 32 per sweep; `GBRAIN_CORPUS_WINDOWS_PER_SWEEP` lowers the total). `GBRAIN_SWEEP=0` or `gbrain config set facts.extraction_enabled false` pauses it. The upgrade itself rewrites nothing.
+
+### Itemized changes
+
+- `src/core/context/corpus-segments.ts`: `corpusFileCompletion` is the one completion classifier for sweep selection, the under-claim re-check and retention GC (`corpusSidecarState` for the HTTP drain and the doctor backlog). A sidecar whose `skipped` is `chat_unavailable` is pending, and only finished files get the plain retention; unavailable, partial and rewritten files keep the un-ingested ceiling. The failure record format (`<file>.failures.json`, `CORPUS_WINDOW_FAILURE_CAP` 5) lives here too, and the session-end hook reaps it with its `.txt`.
+- `src/core/context/corpus-windows.ts`: `runCorpusWindows` returns `unavailable` without recording the window, and rewinds a progress an earlier build finished as `chat_unavailable` to its retired turns under the same compare-and-set that takes the lease. A failure thrown after a chat call counts against the window's start and the source incarnation; neither tail growth nor the error label resets it, and a commit of that window clears it. One change of the extraction-config fingerprint (model, provider, key presence; no values) re-arms a stopped window once.
+- `src/core/sweep.ts`: the corpus pass runs the facts-absorb owner-readiness preflight (#5362) per source before any model call, applies the failure cap to writeback turn files as well, stops the pass on `chat_unavailable`, and logs thrown errors with their code. `corpus: false` skips the pass. `armCorpusDrain` logs the sweep's diagnostics (each distinct line once) and its skip reasons whenever they change.
+- `src/core/context/checkpoint-harvest.ts`: the compact and writeback lanes run the same preflight; the compact lane writes no receipt for an `unavailable`, backing-off or stopped window.
+- `src/core/bootstrap/verify.ts`: the in-process sweep runs passes 1 and 2 only.
+- `gbrain sweep --retry-failed [--apply] [--json]` (`src/commands/sweep.ts`); doctor `memory_writeback` warns about stopped windows and names `gbrain sweep --retry-failed --apply` (paid) as its fix. `corpus_chat_unavailable`, `corpus_window_backoff` and `corpus_window_dead_lettered` are registered, so `gbrain errors <code>` explains them.
+- Tests: `test/sweep-corpus-chat-unavailable-6786.test.ts` (unservable model in the sweep and the compact harvest; legacy sidecars with and without `.progress`, asserting the facts exist; GC then sweep and sweep then GC with an aged file) and `test/sweep-corpus-failure-cap-6785.test.ts` (a claim landing mid-call, the harvest preflight, the drain log, the retry schedule, the re-arm, doctor's fix and the operator retry). A new `bootstrap-verify.serial.test.ts` case runs the real verify with a keyed report and no gateway. The new behavior cases fail on the previous tree.
+
## [0.60.250.0] - 2026-10-15
**Hosted and remote agents can now pull contradiction findings.** Before this release, `find_contradictions` gave any remote agent, and any caller with a source filter or a token trust floor, an empty list with a "temporarily available" note. The reason was that a stored probe report copies both sides' text verbatim, including private takes, and doesn't record which source each side came from. Now those callers get the findings they are allowed to see. gbrain re-reads each side from the brain under the caller's own permissions and returns a finding only when the caller can read both sides now and both still say what the judge saw. Each side comes with its source and trust tier. The bare local `gbrain find-contradictions` works exactly as before.
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index c26f12505a..e68b80ea53 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -21,8 +21,8 @@
- Read-time TTL validity (there is no sweeper): ACTIVE fact reads in BOTH engines (`listFactsByEntity/Since/BySession`, every `findCandidateDuplicates` arm, `countUnconsolidatedFacts`, `getFactsHealth` active buckets) carry `AND (valid_until IS NULL OR valid_until > now())` — `valid_until` is temporal validity, not retention; history paths (`listSupersessions`, `findTrajectory`, `--asof`) deliberately still see lapsed rows; a re-stated expired fact re-inserts fresh. Pinned by `test/facts/ttl-validity.test.ts` + engine-parity additions.
- Diagnostics: `src/commands/doctor/checks/memory-writeback.ts` (`memory_writeback`, BRAIN category) — quiet-ok when off, but the OFF branch still probes receipt + canonical instruction paths and WARNS on a lingering block (off-but-still-instructing) with the converge command; plane-compare warns when the file mirror disagrees with the DB row (the Stop hook acting on the wrong truth) naming the re-sync; a read_error reports the state as UNKNOWN, never "off (default)"; resolved bundle + BOTH visibility postures + audience/reasons; on both branches an explicit private `facts.default_visibility` on a non-shared brain with remote readers (a harness receipt, or HTTP MCP clients active in 30d; listed in `private_default_remote_readers`) warns with the shared `PRIVATE_DEFAULT_REMOTE_CONSEQUENCE` text (`writeback-config.ts`), the same text `bootstrap harness` prints before consent; instruction blocks receipt-vs-live-probe-vs-drift compare (drift fix names the `config set` + `bootstrap harness` combo — the config set re-stamps the posture mirror so the re-render converges even after an out-of-band visibility flip) + AGENTS.override.md detection — and a receipt target in state `failed` is a STANDING warn regardless of the live probe (the one physical-survival path — a smoke-rollback strip that itself threw — leaves a current-looking block directing sessions at a rolled-back endpoint, and only the receipt state knows) naming the `bootstrap harness --yes` / `--remove` converge; validity-lapsed count; 7d counters (verbs usage sidecar's additive `remember_status` [stamped in `src/mcp/dispatch.ts`, ALL-MCP-callers semantics labeled honestly] + `writeback`/`writeback-bank` heartbeat events; `turns_banked` counts flush_skip_* — banked, enqueue declined); when at least 10 serve-side harvests finished (ok + error; a `writer_busy_requeued` retry is not finished) in those 7d and more than 20% failed, a warn names the failure count, the top error reason and the `gbrain sweep --once` recovery; `details.corpus_backlog` counts corpus files with no `.ingested` sidecar (pending, oldest age, past retention, deletion day) and, with writeback on, warns once one is past plain retention (E-N1) with the local/lossy disclosure. Null-engine runs report the file mirror honestly. `cross_lane_duplicates_7d` / `near_duplicates_shadow_7d` sum the `writeback_dedup` heartbeat events in both the on and off branches.
- Tests: `test/writeback-config.test.ts`, `test/mcp-instructions-writeback.test.ts`, `test/facts/writeback-gate.test.ts`, `test/hook-writeback-stop.serial.test.ts`, writeback-lane cases in `test/checkpoint-harvest.serial.test.ts`, `test/bootstrap-instructions-block.test.ts` + harness serial additions, `test/writeback-nudge.serial.test.ts`, `test/doctor-memory-writeback.test.ts`, the hermetic 5-step `test/ambient-writeback-lifecycle.serial.test.ts`, and the NON-GATING real-codex door (`test/e2e/bootstrap-real-codex.serial.test.ts`, ambient-writeback describe).
-- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no `.ingested` sidecar; never overlaps itself; pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window's facts batch is keyed by its text (the sweep passes `reAdmitFileRefusals`), so when the canonical file check refused some of its entity requests, `resumeManagedFacts` admits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned by `test/managed-sweep-refused-window-retry.test.ts`.
-- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `retireCorpusFile` / `retireCorpusTurns` (#6091) record a file or its off-period turns as finished without extracting (`skipped_reason`; a retire overrides another extractor's lease, and a later rewrite extracts only unrecorded turns). `parseCorpusTurns` (defined in the provider-free `corpus-turns.ts`, re-exported here) splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended` with cumulative counts; an aborted window records nothing and transport errors release the lease and throw. `finishedCorpusFileState` decides `.ingested` files by stat compare (no rehash); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).
+- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no final `.ingested` sidecar; never overlaps itself; its sweep diagnostics and thrown ticks reach stderr, each distinct line once per run, plus the skip reasons whenever their set changes (#6785); pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `bootstrap verify` runs the sweep in-process with `corpus: false` (#6786: its engine has no configured gateway, so every window answered `chat_unavailable`). Before any model call the corpus pass runs the facts-absorb owner-readiness preflight per source (`assertSourceLegacyWriter` in `persistence/filesystem-guard.ts`): a claimed, not activated canonical worktree skips the file as `writer_coordinator_required` and logs `gbrain sources writer status <id>` (#6785; the compact and writeback harvest lanes do the same). A `chat_unavailable` result is not terminal: the windowed file or `.wb-` turn keeps no sidecar, nothing is recorded, and the pass stops (`corpus_chat_unavailable`). Failures thrown after a chat call are counted per window (`<file>.failures.json`, see `corpus-windows.ts`) and skipped as `corpus_window_backoff` / `corpus_window_dead_lettered`; `gbrain sweep --retry-failed [--apply]` previews or clears them (doctor `memory_writeback` names the paid retry as its fix). Pinned by `test/sweep-corpus-chat-unavailable-6786.test.ts` and `test/sweep-corpus-failure-cap-6785.test.ts`. `gbrain sweep --once` is the trusted CLI seam for operator catch-up runs (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window's facts batch is keyed by its text (the sweep passes `reAdmitFileRefusals`), so when the canonical file check refused some of its entity requests, `resumeManagedFacts` admits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned by `test/managed-sweep-refused-window-retry.test.ts`.
+- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `retireCorpusFile` / `retireCorpusTurns` (#6091) record a file or its off-period turns as finished without extracting (`skipped_reason`; a retire overrides another extractor's lease, and a later rewrite extracts only unrecorded turns). `parseCorpusTurns` (defined in the provider-free `corpus-turns.ts`, re-exported here) splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended`/`changed`/`source_changed`/`unavailable`/`backoff`/`dead_lettered` with cumulative counts; an aborted or `unavailable` window records nothing, and a progress a pre-#6786 build finished with `skipped_reason: chat_unavailable` is rewound under the lease CAS to its retired turns (source binding, totals and links kept). Transport and write errors release the lease and throw; one thrown after a chat call (`extractUnderFailureCount`, observed through the AI invocation preflight) counts against the window's start key (`<turn sha256>@<offset>`) and source incarnation in `<file>.failures.json`: retried on the next sweep, then after 10, 20 and 40 minutes (`CORPUS_WINDOW_RETRY_BASE_MS`), stopped at `CORPUS_WINDOW_FAILURE_CAP` (5); tail growth and error labels never reset it, a commit of that window removes it, and one change of `extractionConfigFingerprint` (model, provider, key presence) re-arms a stopped window once (#6785). `corpusFileCompletion` in `corpus-segments.ts` is the one completion classifier (selection, the under-claim re-check, retention GC; `corpusSidecarState` for the drain and the doctor backlog): a `chat_unavailable` sidecar is pending, and only `done`/`legacy` files get the plain retention (#6786); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).
- `src/core/context/corpus-source.ts` — #6268, the session's source for every corpus file. Writers (`hook.ts` compact/stop/session-end, the OpenClaw `compact()`) call `openSessionCorpus`, which freezes one source per session at first use (GBRAIN_SOURCE, then the `.gbrain-source` dotfile, else unresolved) into `<sid>.source.json` in the `sourced/` spool and stamps it into the file name (`.src-<id>`, `default` included; `_unresolved` cannot collide with a real id). Pre-stamp sweepers never list the spool. `resolveCorpusFileSource` is the sweep/harvest/serve read: the stamp or frozen record, else the brain's cwd chain once (frozen, tier `engine`); legacy top-level files are held (`corpus_legacy_unstamped`) unless a legacy wb stamp, a frozen record or a single-source brain proves the source, never assigned the pass source. The first engine resolution binds the source incarnation; a recreated source holds the session (`corpus_source_incarnation_changed`). `gbrain sweep --assign-corpus <source>` is the operator mapping (preview, then `--apply`); doctor `memory_writeback` reports `details.corpus_source_holds`. Tests: `test/corpus-source-stamp.test.ts`.
- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). #6317 (D1 a′), managed Postgres brains: `maybeDelegateManagedSyncToServe(engine, args, opts)` runs post-connect from `runSingleSourceSync` right before `performSync`; it probes the host's live full `serve` consumer through `persistence_consumers` (`consumer-heartbeat.ts`, the database, never a socket), admits the catch-up's flags (`--no-bulk`, `--lanes`/`--no-lanes`, `--json`, the processing flags), sends the CLI's durable `cli` registration in `sync_start`, prints the drain's own numbered lines from `sync_status` (`managed`, `lines`, `drain`, `next`) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (`withVerifiedLocalRegistration`) and runs `performSync({ drain: true })` as that writer under `withHumanLineSink`; the shared-secret lane stays under `withLegacySyncDelegation` and is still refused on a managed brain; a denied, revoked or stdio registration answers `sync_start` with `permission_denied` and the envelope (`refusal`), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch, `stale_serve` / `unsupported_kind` from an older serve, `source_mismatch`, a serve lost mid-drain) runs without the serve with one actionable line; only the opt-out, a serve not answering its socket and a `stale_serve` serve call `forceOwnConsumer` (#6543), the rest admit writes the serve consumes under `persistence.single_consumer`. #6696: both builders send `explicitProcessing` as computed, so a flagless run sends `[]` and adopts an unfinished cursor's stored options exactly as in-process; the serve reads a payload without the list (an older CLI) as explicit for each processing boolean it sends `true`, a flagless payload as `[]`, and keeps a supplied list as sent. Wire `embedDeferred` (sent only when true) carries the cost gate's runtime deferral, so adopting a cursor that stores `noEmbed=false` never embeds in that run. `maybeDelegateManagedSyncToServe` refuses `--skip-failed` / `--include-gitignored` on a managed source with `managed_sync_flag_refused` before any probe or socket call (`test/sync-delegated-options-6696.serial.test.ts`, `test/sync-managed-forbidden-flags-6696.test.ts`). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/serve-sync-handoff.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step) and `test/e2e/serve-delegated-managed-sync.serial.test.ts` (Postgres, spawned serve, MCP latency printed).
- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.
diff --git a/docs/guides/ambient-writeback.md b/docs/guides/ambient-writeback.md
index 569539a559..61145b00db 100644
--- a/docs/guides/ambient-writeback.md
+++ b/docs/guides/ambient-writeback.md
@@ -203,6 +203,19 @@ the file's claim and before any provider call:
`dream.synthesize.corpus_retention_days` (90 days by default), and
`gbrain doctor` warns in `memory_writeback` once one is past plain
retention. `GBRAIN_SWEEP=0` turns every serve sweep and drain off.
+ The drain writes its skip reasons and failures to serve's stderr.
+
+ **Extraction that keeps failing stops costing money.** When a window's
+ extraction fails after the model call (for example the fact write is
+ refused), the sweep retries it on the next pass, then after 10, 20 and
+ 40 minutes, and then stops paying for it (`corpus_window_dead_lettered`).
+ Changing the extraction model or provider retries it once more. Fix the
+ cause, then run `gbrain sweep --retry-failed` to see the stopped files
+ and `gbrain sweep --retry-failed --apply` to retry them (paid). A source
+ whose canonical worktree is claimed but not activated is held before any
+ model call; `gbrain sources writer status <source>` says what to do.
+ With no usable extraction model, files stay pending instead of being
+ marked done with zero facts.
**Say to your agent:** *"Make sure the turns my brain could not extract
are swept."* (the agent runs `gbrain sweep --once --budget-ms 600000` on
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index a763f639b9..4eb24c0f12 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -724,6 +724,30 @@ More: [docs/guides/core-memory.md#owner-only](../../docs/guides/core-memory.md#o
More: [docs/guides/core-memory.md#remote-edits](../../docs/guides/core-memory.md#remote-edits)
+### corpus_chat_unavailable
+
+<a id="corpus_chat_unavailable"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The sweep's corpus pass stopped because the extraction model is not servable in this process; the captured session files stay pending (no `.ingested` sidecar), so nothing was lost. | No servable model is a state of the extracting process, not of the transcript. Before #6786 it was recorded as a finished file with zero facts, and retention later deleted the text. | Configure the extraction model (gbrain models shows it) or run the sweep from a process that has its key; the next sweep extracts the pending files. Run: gbrain models --json | agent | `gbrain doctor --json` | 1 | no |
+
+### corpus_window_backoff
+
+<a id="corpus_window_backoff"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A corpus window failed after its model call and waits out its retry delay (the next sweep, then 10, 20 and 40 minutes) before the sweep pays for it again. | Without a delay a write that fails after extraction (#6785) was paid for again on every drain. | Wait briefly, then retry the same request (writes: reuse the same request_id). Run: gbrain sweep --retry-failed --json | agent | `repeat the read that failed` | 1 | yes |
+
+### corpus_window_dead_lettered
+
+<a id="corpus_window_dead_lettered"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A corpus window failed after its model call on every allowed attempt, so the sweep stopped paying for it; its file stays pending until an operator retries it. | A window that can never commit was re-extracted forever before #6785. The count is per window and source incarnation; tail growth and changing error codes do not reset it, and one extraction-config change (model, provider, key presence) retries it once. | Fix the cause the last code names (for writer_coordinator_required: gbrain sources writer status <source>), then ask the user before gbrain sweep --retry-failed --apply: the retry pays for the extraction again. Run: gbrain sweep --retry-failed --json | agent | `repeat the read that failed` | 1 | no |
+
### cost_cap_exceeded
<a id="cost_cap_exceeded"></a>
diff --git a/src/commands/doctor/checks/memory-writeback.ts b/src/commands/doctor/checks/memory-writeback.ts
index 1c94a422f1..0f91e7d9be 100644
--- a/src/commands/doctor/checks/memory-writeback.ts
+++ b/src/commands/doctor/checks/memory-writeback.ts
@@ -40,7 +40,7 @@ import { classifyBrainAudience } from '../../../core/facts/writeback-audience.ts
import { readVerbUsage } from '../../../core/verbs/usage-log.ts';
import { readClientOpUsage } from '../../../core/mcp-usage.ts';
import { OPENCLAW_COMPACT_EVENT, readHeartbeatTail } from '../../../core/context/hook-heartbeat.ts';
-import { CORPUS_UNINGESTED_RETENTION_FACTOR, corpusBacklog, corpusSpoolDir } from '../../../core/context/corpus-segments.ts';
+import { CORPUS_UNINGESTED_RETENTION_FACTOR, CORPUS_WINDOW_FAILURE_CAP, corpusBacklog, corpusSpoolDir, listCorpusFailures } from '../../../core/context/corpus-segments.ts';
import { listCorpusSourceHolds } from '../../../core/context/corpus-source.ts';
import { readHarnessReceiptState } from '../../../core/bootstrap/format.ts';
import { mutedFirstRunDecisionsNotice } from '../../../core/onboard/mcp-onboarding.ts';
@@ -175,6 +175,36 @@ async function corpusBacklogProblem(engine: BrainEngine, fileCfg: ReturnType<typ
+ `(oldest ${oldestDays}d); they are deleted at ${purgeDays}d. Extract them now: gbrain sweep --once --budget-ms 600000`;
}
+/** #6785: the problem text a stopped corpus window carries; the check's fix keys on it. */
+const CORPUS_RETRY_COMMAND = 'gbrain sweep --retry-failed --apply';
+
+/**
+ * #6785: corpus windows the sweep stopped paying for after
+ * CORPUS_WINDOW_FAILURE_CAP failures past the model call. Nothing retries
+ * them until the operator does (paid), so the check names the retry as its
+ * fix. Records `details.corpus_failed_windows`.
+ */
+async function corpusFailureProblem(engine: BrainEngine, fileCfg: ReturnType<typeof loadConfig>, details: Record<string, unknown>): Promise<string | null> {
+ const dir = await sessionCorpusDir(engine, fileCfg);
+ const failed = [...listCorpusFailures(corpusSpoolDir(dir)), ...listCorpusFailures(dir)];
+ const stopped = failed.filter((f) => f.record.count >= CORPUS_WINDOW_FAILURE_CAP);
+ if (!failed.length) return null;
+ const codes = new Map<string, number>();
+ for (const f of stopped) codes.set(f.record.last_code, (codes.get(f.record.last_code) ?? 0) + 1);
+ details.corpus_failed_windows = { retrying: failed.length - stopped.length, stopped: stopped.length, last_codes: Object.fromEntries(codes) };
+ if (!stopped.length) return null;
+ const [topCode] = [...codes.entries()].sort((a, b) => b[1] - a[1])[0]!;
+ return `${stopped.length} captured session file(s) stopped extracting after ${CORPUS_WINDOW_FAILURE_CAP} failed attempts at one window (top: ${topCode}); `
+ + `fix the cause, then retry them (paid): ${CORPUS_RETRY_COMMAND}`;
+}
+
+const CORPUS_RETRY_FIX = {
+ argv: ['gbrain', 'sweep', '--retry-failed', '--apply'], consent: ['paid'] as Effect[], actor: 'agent' as const, requires_exclusive: false,
+ why: 'Clears the failure counts of corpus windows the sweep stopped retrying, so the next sweep pays to extract them again.',
+ user_message: 'Some captured session text stopped being turned into memory because extracting it kept failing (gbrain doctor names the error). Once the cause is fixed, retrying costs model calls. OK to retry them?',
+ verify: { argv: ['gbrain', 'doctor', '--only', MEMORY_WRITEBACK_CHECK_NAME, '--json'] },
+};
+
export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Promise<Check> {
try {
const fileCfg = loadConfig();
@@ -280,9 +310,12 @@ export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Pro
if (offHoldProblem) offProblems.push(offHoldProblem);
const offCompactProblem = explicitOff ? null : await openclawCompactionProblem(details).catch(() => null);
if (offCompactProblem) offProblems.push(offCompactProblem);
+ const offFailureProblem = explicitOff ? null : await corpusFailureProblem(engine, fileCfg, details).catch(() => null);
+ if (offFailureProblem) offProblems.push(offFailureProblem);
if (explicitOff) details.restart_after_off = WRITEBACK_RESTART_AFTER_OFF;
return {
name: MEMORY_WRITEBACK_CHECK_NAME,
+ ...(offFailureProblem && !lingering.length ? { fix: CORPUS_RETRY_FIX } : {}),
status: offProblems.length ? 'warn' : 'ok',
message: offProblems.length
? `ambient writeback off: ${offProblems.join('; ')}`
@@ -300,6 +333,8 @@ export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Pro
if (holdProblem) problems.push(holdProblem);
const compactProblem = await openclawCompactionProblem(details).catch(() => null);
if (compactProblem) problems.push(compactProblem);
+ const failureProblem = await corpusFailureProblem(engine, fileCfg, details).catch(() => null);
+ if (failureProblem) problems.push(failureProblem);
if (!wb.ttl_valid) {
problems.push(`memory.auto_writeback_transient_ttl is invalid — using '${wb.transient_ttl}'`);
}
@@ -441,6 +476,7 @@ export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Pro
why: 'Rewrites the gbrain memory instruction block in each harness config from the current writeback settings.',
user_message: "gbrain's memory instructions in your agent app's config are missing or out of date. OK if I reinstall them?",
verify: { argv: ['gbrain', 'doctor', '--only', MEMORY_WRITEBACK_CHECK_NAME, '--json'] } } }
+ : failureProblem ? { fix: CORPUS_RETRY_FIX }
: problems.length ? { fix_unavailable_reason: 'operator_judgement' as const } : {}),
};
} catch (e) {
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index 4b9f7140ce..868b433a4d 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -72,7 +72,7 @@ import {
decideCorpusMode,
gcCorpusArtifacts,
gcCorpusTurnFiles,
- CORPUS_PROGRESS_SUFFIX,
+ CORPUS_FAILURE_SUFFIX, CORPUS_PROGRESS_SUFFIX,
CORPUS_PROGRESS_LOCK_SUFFIX,
HARVEST_RECEIPT_SUFFIX,
segmentHash,
@@ -1850,7 +1850,7 @@ async function hookSessionEnd(io: HookIo): Promise<number> {
const retentionMs = corpusRetentionDays(cfg) * 24 * 60 * 60 * 1000;
for (const gcDir of [dir, root]) { // the spool and the legacy top level
gcCorpusTurnFiles(gcDir, retentionMs); // [G15]; un-ingested turns kept longer (E-N1)
- gcCorpusArtifacts(gcDir, retentionMs, [CORPUS_INGESTED_SUFFIX, CORPUS_CLAIM_SUFFIX, CORPUS_PROGRESS_SUFFIX, CORPUS_PROGRESS_LOCK_SUFFIX, HARVEST_RECEIPT_SUFFIX], [dir, root]); // #6611
+ gcCorpusArtifacts(gcDir, retentionMs, [CORPUS_INGESTED_SUFFIX, CORPUS_CLAIM_SUFFIX, CORPUS_PROGRESS_SUFFIX, CORPUS_PROGRESS_LOCK_SUFFIX, HARVEST_RECEIPT_SUFFIX, CORPUS_FAILURE_SUFFIX], [dir, root]); // #6611
}
}
}
diff --git a/src/commands/sweep.ts b/src/commands/sweep.ts
index e7a71f6bbe..36cf4353e3 100644
--- a/src/commands/sweep.ts
+++ b/src/commands/sweep.ts
@@ -26,6 +26,7 @@ export const SWEEP_HELP = `gbrain sweep — run the serve-resident maintenance s
Usage:
gbrain sweep --once [--source <id>] [--budget-ms <n>] [--batch-limit <n>] [--json]
gbrain sweep --assign-corpus <source> [--session <id>] [--apply] [--json]
+ gbrain sweep --retry-failed [--apply] [--json]
Runs the three bounded sweep passes against the connected brain:
1. facts-fence reconciliation (zero-LLM): recently-modified pages with a
@@ -52,6 +53,14 @@ which held sessions would be mapped to <source>; --apply records the
mapping (a session that already names a source is never changed), and the
next sweep extracts them there. --session limits it to one session.
+Failed windows (#6785): a corpus window whose extraction fails after the
+model call (the fence write was refused, the provider errored) is retried
+on the next sweep, then after 10, 20 and 40 minutes, then no longer paid
+for: the sweep skips it as corpus_window_dead_lettered. An extraction-config change (model, provider,
+key presence) retries it once more. --retry-failed lists the files waiting
+or stopped; --apply clears their failure counts so the next sweep pays to
+extract those windows again.
+
Exit codes: 0 = success or partial (see "skipped" in the report);
1 = total failure (every pass errored). Local-only; never runs over MCP.
`;
@@ -87,6 +96,10 @@ export async function runSweep(engine: BrainEngine, args: string[]): Promise<voi
await runAssignCorpus(engine, args);
return;
}
+ if (args.includes('--retry-failed')) {
+ await runRetryFailed(engine, args);
+ return;
+ }
if (!args.includes('--once')) {
console.error('gbrain sweep: --once is required (one bounded sweep, then exit).');
console.error('Run `gbrain sweep --help` for usage.');
@@ -146,6 +159,50 @@ export async function runSweep(engine: BrainEngine, args: string[]): Promise<voi
}
}
+async function sessionCorpusDir(engine: BrainEngine): Promise<string> {
+ const dir = await engine.getConfig('dream.synthesize.session_corpus_dir');
+ if (dir) return dir;
+ const { configDir } = await import('../core/config.ts');
+ const { join } = await import('node:path');
+ return join(configDir(), 'transcripts', 'corpus');
+}
+
+/** #6785: preview (default) or clear the failure counts of corpus windows that keep failing after the model call. */
+async function runRetryFailed(engine: BrainEngine, args: string[]): Promise<void> {
+ const json = jsonRequested(args);
+ const apply = args.includes('--apply');
+ const { CORPUS_SPOOL_SUBDIR, CORPUS_WINDOW_FAILURE_CAP, corpusSpoolDir, listCorpusFailures } = await import('../core/context/corpus-segments.ts');
+ const { clearCorpusFailure } = await import('../core/context/corpus-windows.ts');
+ const dir = await sessionCorpusDir(engine);
+ const files = [
+ ...listCorpusFailures(corpusSpoolDir(dir)).map(f => ({ ...f, label: `${CORPUS_SPOOL_SUBDIR}/${f.name}` })),
+ ...listCorpusFailures(dir).map(f => ({ ...f, label: f.name })),
+ ];
+ if (apply) for (const f of files) await clearCorpusFailure(f.full);
+ const rows = files.map(f => ({
+ file: f.label,
+ attempts: f.record.count,
+ stopped: f.record.count >= CORPUS_WINDOW_FAILURE_CAP,
+ last_code: f.record.last_code,
+ last_failed_at: new Date(f.record.last_at).toISOString(),
+ }));
+ if (json) {
+ console.log(JSON.stringify({ applied: apply, cap: CORPUS_WINDOW_FAILURE_CAP, files: rows }, null, 2));
+ return;
+ }
+ if (!rows.length) {
+ console.log('No corpus window is waiting on a failed extraction.');
+ return;
+ }
+ console.log(apply
+ ? `Cleared the failure counts of ${rows.length} corpus file(s); the next sweep pays to extract their windows again (gbrain sweep --once).`
+ : `${rows.length} corpus file(s) have a window that failed after the model call:`);
+ for (const r of rows) {
+ console.log(` ${r.file}: ${r.attempts} failed attempt(s), last ${r.last_code} at ${r.last_failed_at}${r.stopped ? ' (stopped)' : ' (retrying with backoff)'}`);
+ }
+ if (!apply) console.log('Fix the cause first (the last code names it), then retry them (paid): gbrain sweep --retry-failed --apply');
+}
+
/** #6268: preview (default) or apply the operator's source mapping for held session files. */
async function runAssignCorpus(engine: BrainEngine, args: string[]): Promise<void> {
const json = jsonRequested(args);
@@ -166,12 +223,7 @@ async function runAssignCorpus(engine: BrainEngine, args: string[]): Promise<voi
'sweep', { json }));
return;
}
- let dir = await engine.getConfig('dream.synthesize.session_corpus_dir');
- if (!dir) {
- const { configDir } = await import('../core/config.ts');
- const { join } = await import('node:path');
- dir = join(configDir(), 'transcripts', 'corpus');
- }
+ const dir = await sessionCorpusDir(engine);
const { assignCorpusSessions, listCorpusSourceHolds } = await import('../core/context/corpus-source.ts');
const sources = await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id LIMIT 2');
const holds = listCorpusSourceHolds(dir, sources.length === 1);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1d6359f1e2..adc2ad758b 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -642,6 +642,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.249.0', text: 'On a brain without managed persistence, `extract_facts` (and the v0.32.2 fence step) now fences unfenced facts of a database-only page (no recorded file and none at its slug path) into the page\'s database body when such a write is database-only (`sync.write_through` off, or on Postgres an unbound source with `persistence.unbound_write=database_only`, which stamps the page `unbound_source`), instead of reporting a missing canonical file and halting the facts fence every run. Without that opt-in the rows stay unfenced and their page skips reconciliation, but they no longer count as pending (`legacyRowsPending`) or trigger the guard; doctor `fence_integrity` lists them under `unbound_legacy_facts` and asks the user about the opt-in, and the migration reports them as `skipped_unbound_source`.' },
{ since: '0.60.249.0', text: 'On a brain without managed persistence, `gbrain restore` / `restore_page` of a soft-deleted page whose recorded file is gone from the checkout now refuses (`source_changed`, detail `canonical_file_absent`) when the restore writes no file, instead of restoring a page the next `gbrain sync --full` deletes again. Put the file back and sync, or pass `--detach` (`detach: true`) to restore it database-only (`database_only_reason=detached`, no `source_path`); a file synced back at its path binds the page again. New doctor check `missing_recorded_files` lists live pages a full sync would delete this way.' },
{ since: '0.60.250.0', text: 'Remote agents and token-floor connections now get stored contradiction findings from `find_contradictions` instead of an availability note or a refusal: only findings whose two sides they can read now, each side re-read live with its `source_id` and `trust_tier`, never the stored report text; `min_trust` and the token floor filter instead of refusing. A local `gbrain find-contradictions --source <id>` (or `GBRAIN_SOURCE`) now gets that scoped view instead of the note; the bare command still reads the whole stored run.' },
+ { since: '0.60.250.0', text: 'A session transcript whose extraction answered `chat_unavailable` (no usable extraction model, as in every `gbrain bootstrap verify` before this release) is no longer marked ingested: it stays pending, and files an earlier build marked `skipped: chat_unavailable` are extracted again by the next sweeps. That is a one-time paid catch-up after upgrading, bounded by the sweep window caps (8 windows per file and 32 per sweep; `GBRAIN_CORPUS_WINDOWS_PER_SWEEP` lowers the total) and paused by `GBRAIN_SWEEP=0` or `gbrain config set facts.extraction_enabled false`. Nothing is rewritten during the upgrade, and retention keeps those files for 3x `dream.synthesize.corpus_retention_days` until they are extracted. `bootstrap verify` no longer runs the corpus pass. The sweep and both harvest lanes check a claimed but not activated canonical worktree before any model call and skip it as `writer_coordinator_required`, naming `gbrain sources writer status <source>`. A corpus window that fails after its model call is retried on the next sweep, then after 10, 20 and 40 minutes, then no longer paid for (`corpus_window_dead_lettered`) until `gbrain sweep --retry-failed --apply` (paid, preview without `--apply`) or one extraction model or provider change. The `serve --http` corpus drain writes its skip reasons and failures to stderr.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.ts
index f02dead312..244964d9ca 100644
--- a/src/core/bootstrap/verify.ts
+++ b/src/core/bootstrap/verify.ts
@@ -858,13 +858,16 @@ async function runRoundtrip(
}
// 2. Sweep — the `gbrain sweep --once` equivalent, run in-process because
- // verify's caller holds the engine [CX2-5].
+ // verify's caller holds the engine [CX2-5]. #6786: passes 1 and 2 only.
+ // The probes never need the corpus pass, and verify's engine runs without
+ // the gateway extraction would use: every pending transcript came back
+ // chat_unavailable and was marked ingested with zero facts.
const caps = opts.capabilities ?? detectCapabilities();
try {
const report = await runMaintenanceSweep(engine, {
sourceId,
budgetMs: opts.sweepBudgetMs ?? 20_000,
- capabilities: caps,
+ corpus: false,
log: opts.log,
});
opts.log?.(`[verify] sweep: facts=${report.factsReconciled} links=${report.linksExtracted} timeline=${report.timelineExtracted}`);
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 3f4f5581c7..a6746da420 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -117,7 +117,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--brain', '--check-only', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--refs', '--remediation-plan', '--source', '--swap-only', '--tags', '--version', '--yes'],
- 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--scopes', '--source', '--source-guard', '--sources', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
+ 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--sources', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
'setup': ['--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--surface', '--token', '--url', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
@@ -127,7 +127,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--delete', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
- 'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--session', '--source', '--timeout', '--wait'],
+ 'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--timeout', '--wait'],
'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
diff --git a/src/core/context/checkpoint-harvest.ts b/src/core/context/checkpoint-harvest.ts
index 8f46d9715d..6551688c98 100644
--- a/src/core/context/checkpoint-harvest.ts
+++ b/src/core/context/checkpoint-harvest.ts
@@ -409,6 +409,7 @@ async function runOne(job: HarvestJob): Promise<{
if (!(await isFactsExtractionEnabled(job.engine))) {
return { outcome: 'degraded', reason: 'extraction_disabled' };
}
+ if (await writerRefused(job)) return { outcome: 'degraded', reason: 'writer_coordinator_required' };
const fileStat = corpusFileStat(await stat(full));
const raw = await readFile(full, 'utf-8');
@@ -452,6 +453,9 @@ async function runOne(job: HarvestJob): Promise<{
if (abort.signal.aborted || run.status === 'aborted') return { outcome: 'degraded', reason: 'aborted' };
if (run.status === 'contended') return { outcome: 'degraded', reason: 'claimed_elsewhere' };
if (run.status === 'source_changed') return { outcome: 'degraded', reason: 'corpus_source_changed' };
+ // #6786/#6785: nothing was recorded for window 1; the sweep retries it under the same gates.
+ if (run.status === 'unavailable') return { outcome: 'degraded', reason: 'extract_skipped_chat_unavailable' };
+ if (run.status === 'backoff' || run.status === 'dead_lettered') return { outcome: 'degraded', reason: `corpus_window_${run.status}` };
windowsPending = run.status !== 'complete';
const r = run.result;
@@ -582,6 +586,7 @@ async function runWritebackTurn(job: HarvestJob, full: string, ingestedPath: str
if (!(await isFactsExtractionEnabled(job.engine))) {
return { outcome: 'degraded', reason: 'extraction_disabled' };
}
+ if (await writerRefused(job)) return { outcome: 'degraded', reason: 'writer_coordinator_required' };
const raw = await readFile(full, 'utf-8');
const { runFactsPipeline } = await import('../facts/backstop.ts');
@@ -632,6 +637,25 @@ async function runWritebackTurn(job: HarvestJob, full: string, ingestedPath: str
return { outcome: 'ok', inserted: r.inserted, duplicate: r.duplicate, superseded: r.superseded };
}
+/**
+ * #6785: the facts-absorb owner-readiness preflight (#5362) before any model
+ * call. A claimed but not activated canonical worktree refuses the fence
+ * write after extraction; the turn stays banked (no sidecar) for the sweep,
+ * which holds it under the same check until `gbrain sources writer activate`.
+ */
+async function writerRefused(job: HarvestJob): Promise<boolean> {
+ const { assertSourceLegacyWriter } = await import('../persistence/filesystem-guard.ts');
+ try {
+ await assertSourceLegacyWriter(job.engine, job.sourceId);
+ return false;
+ } catch (e) {
+ if ((e as { code?: unknown }).code !== 'writer_coordinator_required') throw e;
+ logFirstHarvestError(job, 'writer_coordinator_required', new Error(
+ `${e instanceof Error ? e.message : String(e)} Check the writer: gbrain sources writer status ${job.sourceId}`));
+ return true;
+ }
+}
+
async function readReceipt(path: string): Promise<HarvestReceipt | null> {
try {
const raw = await readFile(path, 'utf-8');
diff --git a/src/core/context/corpus-segments.ts b/src/core/context/corpus-segments.ts
index 8860837b95..cbfbf75d30 100644
--- a/src/core/context/corpus-segments.ts
+++ b/src/core/context/corpus-segments.ts
@@ -33,6 +33,7 @@ import { createHash } from 'node:crypto';
import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { basename, join } from 'node:path';
import type { WindowTurn } from './entity-salience.ts';
+import type { CorpusFileStat, CorpusProgress } from './corpus-windows.ts';
import { toCorpusText, type ToolCallRecord } from '../transcripts/claude-code-jsonl.ts';
import { mapOpenclawLine } from '../transcripts/openclaw.ts';
import { stripPastedContent, stripPastedContentFromCorpus } from '../transcripts/pasted-content.ts';
@@ -614,8 +615,149 @@ export const CORPUS_UNINGESTED_RETENTION_FACTOR = 3;
/** Completion sidecar suffix (sweep.ts CORPUS_INGESTED_SUFFIX; duplicated to stay engine-free). */
const INGESTED_SUFFIX = '.ingested';
+/**
+ * #6786: `.ingested` skip reasons that record a state of the extracting
+ * process (no servable extraction model), not anything about the file. A
+ * sidecar carrying one is not a completion: selection, the HTTP drain, the
+ * doctor backlog and retention GC all treat the file as pending, and the
+ * sweep extracts it once a model serves (pre-#6786 builds wrote these).
+ */
+export const CORPUS_NON_TERMINAL_SKIPS: readonly string[] = ['chat_unavailable'];
+
+/**
+ * #6786: what `<full>.ingested` says. `absent` (no sidecar), `unavailable`
+ * (a non-terminal skip), or `final` (a completion; an unreadable or
+ * non-JSON sidecar counts as one, as every build before #6786 did). Never throws.
+ */
+export function corpusSidecarState(full: string): 'absent' | 'unavailable' | 'final' {
+ let text: string;
+ try {
+ text = readFileSync(full + INGESTED_SUFFIX, 'utf8');
+ } catch (e) {
+ return (e as NodeJS.ErrnoException).code === 'ENOENT' ? 'absent' : 'final';
+ }
+ try {
+ const skipped = (JSON.parse(text) as { skipped?: unknown } | null)?.skipped;
+ return typeof skipped === 'string' && CORPUS_NON_TERMINAL_SKIPS.includes(skipped) ? 'unavailable' : 'final';
+ } catch {
+ return 'final';
+ }
+}
+
+function isFileStat(v: unknown): v is CorpusFileStat {
+ const s = v as CorpusFileStat;
+ return !!s && typeof s === 'object' && Number.isFinite(s.size) && Number.isFinite(s.mtime_ms) && Number.isFinite(s.ino);
+}
+
+/** #5887 `.progress` parse (context/corpus-windows.ts); null when unparseable (replayed safely). */
+export function parseCorpusProgress(text: string): CorpusProgress | null {
+ let p: CorpusProgress;
+ try { p = JSON.parse(text) as CorpusProgress; } catch { return null; }
+ if (!p || typeof p !== 'object' || p.version !== 1 || !Number.isSafeInteger(p.generation)) return null;
+ if (!Array.isArray(p.turns) || !p.turns.every((t) => t && typeof t.sha256 === 'string')) return null;
+ if (p.continuation !== null && !(p.continuation && typeof p.continuation.turn_sha256 === 'string'
+ && Number.isSafeInteger(p.continuation.stripped_offset))) return null;
+ if (p.finished !== null && !isFileStat(p.finished)) return null;
+ if (!p.totals || !Array.isArray(p.entity_slugs)) return null;
+ if (p.source != null && !(typeof p.source.id === 'string' && typeof p.source.incarnation === 'string')) return null;
+ return p;
+}
+
+/**
+ * How a corpus file stands (#6786: the one classifier for sweep selection,
+ * the under-claim re-check and retention GC):
+ * 'pending' — no `.ingested` sidecar;
+ * 'unavailable' — the sidecar records a non-terminal skip: pending;
+ * 'done' — its `.progress` finished this exact file (stat match);
+ * 'changed' — rewritten since; re-enter (turn hashes decide resume);
+ * 'legacy' — finished before `.progress` existed and not rewritten
+ * since (the sidecar is newer than the file): adopt;
+ * 'legacy_changed' — finished before `.progress` existed, rewritten after.
+ * Writeback turn files are immutable single turns: a final sidecar is 'done'.
+ * Only 'done' and 'legacy' are finished. Stat and progress read errors throw.
+ */
+export type CorpusFileCompletion = 'pending' | 'unavailable' | 'done' | 'changed' | 'legacy' | 'legacy_changed';
+
+export function corpusFileCompletion(full: string, name: string): CorpusFileCompletion {
+ const sidecar = corpusSidecarState(full);
+ if (sidecar !== 'final') return sidecar === 'absent' ? 'pending' : 'unavailable';
+ if (parseWbFileName(name)) return 'done';
+ const st = statSync(full);
+ let progress: CorpusProgress | null = null;
+ try {
+ progress = parseCorpusProgress(readFileSync(full + CORPUS_PROGRESS_SUFFIX, 'utf8'));
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;
+ return statSync(full + INGESTED_SUFFIX).mtimeMs >= st.mtimeMs ? 'legacy' : 'legacy_changed';
+ }
+ if (!progress) return statSync(full + INGESTED_SUFFIX).mtimeMs >= st.mtimeMs ? 'legacy' : 'legacy_changed';
+ const f = progress.finished;
+ return f && f.size === st.size && f.mtime_ms === st.mtimeMs && f.ino === st.ino ? 'done' : 'changed';
+}
+
+export function corpusFileFinished(state: CorpusFileCompletion): boolean {
+ return state === 'done' || state === 'legacy';
+}
+
+/**
+ * #6785: per-file record of the one corpus window (or writeback turn) whose
+ * extraction keeps failing after the model call. Written under the file's
+ * `.in-progress` claim by context/corpus-windows.ts; removed when that
+ * window commits, or by `gbrain sweep --retry-failed --apply`.
+ */
+export const CORPUS_FAILURE_SUFFIX = '.failures.json';
+/** Failed attempts after which a window is not retried until an operator retry or one extraction-config change. */
+export const CORPUS_WINDOW_FAILURE_CAP = 5;
+
+export interface CorpusFailureRecord {
+ version: 1;
+ /** The failing window's start (`<turn sha256>@<offset>`), or `turn` for a writeback turn file. */
+ key: string;
+ source_incarnation: string | null;
+ count: number;
+ first_at: number;
+ last_at: number;
+ /** Error code or class of the last failure; never its message. */
+ last_code: string;
+ /** extraction-config fingerprint (model, provider, key presence) at the last failure. */
+ fingerprint: string | null;
+ /** True once a fingerprint change re-armed a capped window; a second change does not. */
+ rearmed: boolean;
+}
+
+/** The failure record, or null when absent or unparseable. Never throws. */
+export function readCorpusFailure(full: string): CorpusFailureRecord | null {
+ try {
+ const r = JSON.parse(readFileSync(full + CORPUS_FAILURE_SUFFIX, 'utf8')) as CorpusFailureRecord;
+ if (!r || r.version !== 1 || typeof r.key !== 'string' || !Number.isSafeInteger(r.count) || r.count < 1
+ || !Number.isFinite(r.last_at) || !Number.isFinite(r.first_at) || typeof r.last_code !== 'string'
+ || !(r.source_incarnation === null || typeof r.source_incarnation === 'string')
+ || !(r.fingerprint === null || typeof r.fingerprint === 'string') || typeof r.rearmed !== 'boolean') return null;
+ return r;
+ } catch {
+ return null;
+ }
+}
+
+/** Every corpus `.txt` in `dir` with a failure record. Missing dir = empty; never throws. */
+export function listCorpusFailures(dir: string): Array<{ name: string; full: string; record: CorpusFailureRecord }> {
+ let names: string[];
+ try {
+ names = readdirSync(dir);
+ } catch {
+ return [];
+ }
+ const present = new Set(names);
+ const out: Array<{ name: string; full: string; record: CorpusFailureRecord }> = [];
+ for (const name of names.filter((n) => n.endsWith('.txt') && present.has(n + CORPUS_FAILURE_SUFFIX)).sort()) {
+ const record = readCorpusFailure(join(dir, name));
+ if (record) out.push({ name, full: join(dir, name), record });
+ }
+ return out;
+}
+
export interface CorpusBacklog {
- /** `.txt` files with no `.ingested` sidecar. */
+ /** `.txt` files with no final `.ingested` sidecar. */
pending: number;
/** mtime of the oldest pending file, or null with none pending. */
oldestPendingMtimeMs: number | null;
@@ -634,7 +776,8 @@ export function corpusBacklog(dir: string, retentionMs: number, now = Date.now()
}
const present = new Set(names);
for (const name of names) {
- if (!name.endsWith('.txt') || present.has(name + INGESTED_SUFFIX)) continue;
+ if (!name.endsWith('.txt')) continue;
+ if (present.has(name + INGESTED_SUFFIX) && corpusSidecarState(join(dir, name)) === 'final') continue;
let mtimeMs: number;
try {
mtimeMs = statSync(join(dir, name)).mtimeMs;
@@ -649,21 +792,23 @@ export function corpusBacklog(dir: string, retentionMs: number, now = Date.now()
}
/**
- * Retention GC for corpus turn files: an extracted file (`.ingested`
- * sidecar present) goes at `retentionMs`; one nothing has extracted stays
- * until `CORPUS_UNINGESTED_RETENTION_FACTOR` x `retentionMs` (E-N1).
+ * Retention GC for corpus turn files: a finished file (corpusFileCompletion
+ * 'done' or 'legacy') goes at `retentionMs`; one nothing has finished
+ * extracting (no sidecar, a non-terminal skip such as `chat_unavailable`
+ * #6786, windows still pending, or rewritten since) stays until
+ * `CORPUS_UNINGESTED_RETENTION_FACTOR` x `retentionMs` (E-N1).
* Best-effort per file; never throws.
*/
export function gcCorpusTurnFiles(dir: string, retentionMs: number, now = Date.now()): void {
try {
- const names = readdirSync(dir);
- const present = new Set(names);
- for (const name of names) {
+ for (const name of readdirSync(dir)) {
if (!name.endsWith('.txt')) continue;
- const ageLimit = present.has(name + INGESTED_SUFFIX) ? retentionMs : retentionMs * CORPUS_UNINGESTED_RETENTION_FACTOR;
const p = join(dir, name);
try {
- if (statSync(p).mtimeMs < now - ageLimit) rmSync(p, { force: true });
+ const age = now - statSync(p).mtimeMs;
+ if (age <= retentionMs) continue;
+ const ageLimit = corpusFileFinished(corpusFileCompletion(p, name)) ? retentionMs : retentionMs * CORPUS_UNINGESTED_RETENTION_FACTOR;
+ if (age > ageLimit) rmSync(p, { force: true });
} catch {
/* per-file best effort */
}
diff --git a/src/core/context/corpus-windows.ts b/src/core/context/corpus-windows.ts
index 0a9c225be2..46dee3c7b5 100644
--- a/src/core/context/corpus-windows.ts
+++ b/src/core/context/corpus-windows.ts
@@ -32,8 +32,12 @@ import { readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { MAX_TURN_TEXT_CHARS } from '../facts/extract.ts';
import type { runFactsPipeline } from '../facts/backstop.ts';
+import { isAIInvocationPolicyError, withAIInvocationPreflight } from '../ai/invocation-guard.ts';
import { parseCorpusTurns, type CorpusTurn } from './corpus-turns.ts';
-import { CORPUS_PROGRESS_LOCK_SUFFIX, CORPUS_PROGRESS_SUFFIX, parseWbFileName } from './corpus-segments.ts';
+import {
+ CORPUS_FAILURE_SUFFIX, CORPUS_NON_TERMINAL_SKIPS, CORPUS_PROGRESS_LOCK_SUFFIX, CORPUS_PROGRESS_SUFFIX, CORPUS_WINDOW_FAILURE_CAP,
+ corpusFileCompletion, corpusFileFinished, parseCorpusProgress, readCorpusFailure, type CorpusFailureRecord,
+} from './corpus-segments.ts';
export { parseCorpusTurns, type CorpusTurn };
@@ -95,7 +99,13 @@ export interface CorpusProgressSource {
}
export interface CorpusWindowRun {
- status: 'complete' | 'partial' | 'aborted' | 'contended' | 'changed' | 'source_changed';
+ /**
+ * #6786 `unavailable`: the extractor answered a non-terminal skip (no
+ * servable model); nothing was recorded for that window. #6785 `backoff` /
+ * `dead_lettered`: the next window failed after its model call before and
+ * waits out its retry delay, or reached CORPUS_WINDOW_FAILURE_CAP.
+ */
+ status: 'complete' | 'partial' | 'aborted' | 'contended' | 'changed' | 'source_changed' | 'unavailable' | 'backoff' | 'dead_lettered';
windowsDone: number;
windowsRemaining: number;
/** Cumulative across every sweep that worked on this file. */
@@ -210,28 +220,10 @@ export function resumePoint(turns: CorpusTurn[], progress: CorpusProgress | null
return { turn, offset };
}
-function isFileStat(v: unknown): v is CorpusFileStat {
- const s = v as CorpusFileStat;
- return !!s && typeof s === 'object' && Number.isFinite(s.size) && Number.isFinite(s.mtime_ms) && Number.isFinite(s.ino);
-}
-
-function parseProgress(text: string): CorpusProgress | null {
- let p: CorpusProgress;
- try { p = JSON.parse(text) as CorpusProgress; } catch { return null; }
- if (!p || typeof p !== 'object' || p.version !== 1 || !Number.isSafeInteger(p.generation)) return null;
- if (!Array.isArray(p.turns) || !p.turns.every((t) => t && typeof t.sha256 === 'string')) return null;
- if (p.continuation !== null && !(p.continuation && typeof p.continuation.turn_sha256 === 'string'
- && Number.isSafeInteger(p.continuation.stripped_offset))) return null;
- if (p.finished !== null && !isFileStat(p.finished)) return null;
- if (!p.totals || !Array.isArray(p.entity_slugs)) return null;
- if (p.source != null && !(typeof p.source.id === 'string' && typeof p.source.incarnation === 'string')) return null;
- return p;
-}
-
/** The progress sidecar, or null when absent or unparseable (replayed safely). I/O errors throw. */
export async function readCorpusProgress(full: string): Promise<CorpusProgress | null> {
try {
- return parseProgress(await readFile(full + CORPUS_PROGRESS_SUFFIX, 'utf8'));
+ return parseCorpusProgress(await readFile(full + CORPUS_PROGRESS_SUFFIX, 'utf8'));
} catch (e) {
if ((e as NodeJS.ErrnoException).code === 'ENOENT') return null;
throw e;
@@ -330,27 +322,6 @@ function resultOf(p: CorpusProgress): PipelineResult {
};
}
-/**
- * How a corpus file that HAS an `.ingested` sidecar stands:
- * 'done' — its `.progress` finished this exact file (stat match);
- * 'changed' — rewritten since; re-enter (turn hashes decide resume);
- * 'legacy' — finished before `.progress` existed and not rewritten
- * since (the sidecar is newer than the file): adopt;
- * 'legacy_changed' — finished before `.progress` existed, rewritten after.
- * Writeback turn files are immutable single turns: always 'done'.
- */
-export async function finishedCorpusFileState(
- full: string,
- name: string,
-): Promise<'done' | 'changed' | 'legacy' | 'legacy_changed'> {
- if (parseWbFileName(name)) return 'done';
- const st = await stat(full);
- const progress = await readCorpusProgress(full);
- if (progress) return sameCorpusFileStat(progress.finished, corpusFileStat(st)) ? 'done' : 'changed';
- const ingested = await stat(full + '.ingested');
- return ingested.mtimeMs >= st.mtimeMs ? 'legacy' : 'legacy_changed';
-}
-
/**
* V6 — record a file finished before windowed extraction as fully extracted
* at its current turns, so later growth extracts only the appended turns and
@@ -430,14 +401,160 @@ function mergeTurns(recorded: CorpusProgress['turns'], turns: CorpusTurn[]): Cor
return [...recorded, ...added].slice(-MAX_RECORDED_TURNS);
}
+/** A failed window is retried on the next sweep, then after this delay, doubling per failure (10, 20, 40 minutes). */
+export const CORPUS_WINDOW_RETRY_BASE_MS = 10 * 60_000;
+/** The failure key of a writeback turn file (one turn, one call). */
+export const CORPUS_TURN_FAILURE_KEY = 'turn';
+
+/** Where a window starts: its first turn's hash and the offset into it. Stable while the file only grows. */
+function windowKey(turns: CorpusTurn[], at: { turn: number; offset: number }): string {
+ return `${turns[at.turn]?.sha256 ?? 'end'}@${at.offset}`;
+}
+
+/**
+ * #6785: whether the window at `key` may be paid for now. A record for
+ * another window or another source incarnation does not apply. A capped
+ * window stays stopped, except once when the extraction-config fingerprint
+ * changed since its last failure.
+ */
+export function corpusFailureGate(
+ record: CorpusFailureRecord | null,
+ key: string,
+ incarnation: string | null,
+ fingerprint: string | null,
+ nowMs: number,
+): 'run' | 'backoff' | 'dead_lettered' {
+ if (!record || record.key !== key || record.source_incarnation !== incarnation) return 'run';
+ if (record.count >= CORPUS_WINDOW_FAILURE_CAP) return rearms(record, fingerprint) ? 'run' : 'dead_lettered';
+ if (record.count === 1) return 'run';
+ return nowMs < record.last_at + CORPUS_WINDOW_RETRY_BASE_MS * 2 ** (record.count - 2) ? 'backoff' : 'run';
+}
+
+function rearms(record: CorpusFailureRecord, fingerprint: string | null): boolean {
+ return !record.rearmed && record.fingerprint !== null && fingerprint !== null && record.fingerprint !== fingerprint;
+}
+
+/**
+ * #6785: run one extraction; when it throws after reaching a chat model call
+ * (the spend), count a failure against the window at `key`, then rethrow.
+ * A throw before any model call, an abort, a spend-policy refusal, or capture
+ * switched off mid-call (the next sweep retires the file) costs nothing to
+ * retry and is not counted.
+ */
+export async function extractUnderFailureCount<T>(
+ failure: { full: string; record: CorpusFailureRecord | null; key: string; incarnation: string | null; fingerprint: string | null; nowMs: () => number; signal?: AbortSignal },
+ extract: () => Promise<T>,
+): Promise<T> {
+ let chatCalled = false;
+ try {
+ return await withAIInvocationPreflight(async (call) => { if (call.kind === 'chat') chatCalled = true; }, extract);
+ } catch (e) {
+ const counts = chatCalled && !failure.signal?.aborted && !(e instanceof Error && e.name === 'AbortError')
+ && !isAIInvocationPolicyError(e) && (e as { code?: unknown } | null)?.code !== 'ambient_capture_off';
+ if (counts) {
+ await recordCorpusFailure(failure.full, failure.record, failure.key, failure.incarnation, failure.fingerprint, failure.nowMs(), e).catch(() => {});
+ }
+ throw e;
+ }
+}
+
+function failureCode(e: unknown): string {
+ const { code, reason, name } = (e ?? {}) as { code?: unknown; reason?: unknown; name?: unknown };
+ for (const v of [code, reason, name]) if (typeof v === 'string' && /^[A-Za-z][A-Za-z0-9_:-]{0,63}$/.test(v)) return v;
+ return 'error';
+}
+
+/**
+ * #6785: count one failed attempt of the window at `key` (caller holds the
+ * file's `.in-progress` claim). Another window or incarnation starts a new
+ * count; the error label never resets it. A capped window re-armed by a
+ * fingerprint change starts over once. Returns the record written.
+ */
+export async function recordCorpusFailure(
+ full: string,
+ prev: CorpusFailureRecord | null,
+ key: string,
+ incarnation: string | null,
+ fingerprint: string | null,
+ nowMs: number,
+ error: unknown,
+): Promise<CorpusFailureRecord> {
+ const same = !!prev && prev.key === key && prev.source_incarnation === incarnation;
+ const rearm = same && prev!.count >= CORPUS_WINDOW_FAILURE_CAP && rearms(prev!, fingerprint);
+ const record: CorpusFailureRecord = {
+ version: 1,
+ key,
+ source_incarnation: incarnation,
+ count: same && !rearm ? prev!.count + 1 : 1,
+ first_at: same ? prev!.first_at : nowMs,
+ last_at: nowMs,
+ last_code: failureCode(error),
+ fingerprint,
+ rearmed: same ? prev!.rearmed || rearm : false,
+ };
+ const path = full + CORPUS_FAILURE_SUFFIX;
+ const tmp = `${path}.tmp-${process.pid}`;
+ await writeFile(tmp, JSON.stringify(record) + '\n', { mode: 0o600 });
+ await rename(tmp, path);
+ return record;
+}
+
+/** Remove the failure record once its window committed. */
+export async function clearCorpusFailure(full: string): Promise<void> {
+ await rm(full + CORPUS_FAILURE_SUFFIX, { force: true });
+}
+
+/**
+ * #6785/#6786: one writeback turn file (one call, no `.progress`) under the
+ * same failure cap and non-terminal rule as a window. `complete` carries the
+ * result (the caller writes `.ingested`); `unavailable` records nothing.
+ */
+export async function runCorpusTurn(opts: {
+ full: string;
+ signal?: AbortSignal;
+ incarnation: string | null;
+ failures?: { fingerprint: string | null; now?: () => number };
+ extract: () => Promise<PipelineResult>;
+}): Promise<{ status: 'complete'; result: PipelineResult } | { status: 'unavailable' | 'backoff' | 'dead_lettered' }> {
+ const fingerprint = opts.failures?.fingerprint ?? null;
+ const clock = opts.failures?.now ?? Date.now;
+ const record = readCorpusFailure(opts.full);
+ const gate = corpusFailureGate(record, CORPUS_TURN_FAILURE_KEY, opts.incarnation, fingerprint, clock());
+ if (gate !== 'run') return { status: gate };
+ const result = await extractUnderFailureCount(
+ { full: opts.full, record, key: CORPUS_TURN_FAILURE_KEY, incarnation: opts.incarnation, fingerprint, nowMs: clock, signal: opts.signal },
+ opts.extract,
+ );
+ if (result.skipped_reason && CORPUS_NON_TERMINAL_SKIPS.includes(result.skipped_reason)) return { status: 'unavailable' };
+ if (record) await clearCorpusFailure(opts.full).catch(() => {});
+ return { status: 'complete', result };
+}
+
+/**
+ * #6786: a progress whose windows answered a non-terminal skip (pre-#6786
+ * builds recorded those turns as done) is rewound to its retired turns, so
+ * every other turn is extracted again. The source binding, retired turns,
+ * totals and entity links stay.
+ */
+function rewindNonTerminal(cur: CorpusProgress): Omit<CorpusProgress, 'generation'> {
+ if (!cur.skipped_reason || !CORPUS_NON_TERMINAL_SKIPS.includes(cur.skipped_reason)) return cur;
+ const retired = retiredTurns(cur);
+ const { skipped_reason: _dropped, ...rest } = cur;
+ return { ...rest, turns: cur.turns.filter((t) => retired.has(t.sha256)), continuation: null, finished: null };
+}
+
/**
* Extract up to `maxWindows` non-empty windows of `raw` (the snapshot whose
* stat is `fileStat`), committing `.progress` after each one. `complete`
* means every window of this snapshot is done (the caller may write
* `.ingested`); `partial` means the cap stopped it; `aborted` means the
* signal or budget fired (nothing uncommitted is recorded); `contended`
- * means another extractor holds the lease or advanced the progress first.
- * Transport errors throw after the lease is released.
+ * means another extractor holds the lease or advanced the progress first;
+ * `unavailable` means the extractor had no servable model (#6786: nothing is
+ * recorded, and a progress a pre-#6786 build finished that way is rewound
+ * first). Transport and write errors throw after the lease is released; each
+ * one thrown after a model call counts against its window (#6785:
+ * `backoff`, then `dead_lettered` at CORPUS_WINDOW_FAILURE_CAP).
*/
export async function runCorpusWindows(opts: {
full: string;
@@ -449,8 +566,13 @@ export async function runCorpusWindows(opts: {
signal: AbortSignal;
/** #6268: the file's resolved source; binds on the first run, refuses a resume under another. */
source?: CorpusProgressSource;
+ /** #6785: the extraction-config fingerprint that may re-arm a capped window once (null: never), and the clock. */
+ failures?: { fingerprint: string | null; now?: () => number };
}): Promise<CorpusWindowRun> {
const { full, fileStat, signal, source } = opts;
+ const incarnation = source?.incarnation ?? null;
+ const fingerprint = opts.failures?.fingerprint ?? null;
+ const clock = opts.failures?.now ?? Date.now;
const owner = `${process.pid}:${randomUUID()}`;
const now = Date.now();
let sourceChanged = false;
@@ -460,7 +582,7 @@ export async function runCorpusWindows(opts: {
return null;
}
if (cur?.lease && cur.lease.owner !== owner && now - cur.lease.at < CORPUS_PROGRESS_LEASE_STALE_MS) return null;
- return { ...(cur ?? freshProgress()), ...(source && !cur?.source ? { source } : {}), lease: { owner, at: now } };
+ return { ...(cur ? rewindNonTerminal(cur) : freshProgress()), ...(source && !cur?.source ? { source } : {}), lease: { owner, at: now } };
});
const turns = parseCorpusTurns(opts.raw);
if (!state) {
@@ -471,17 +593,24 @@ export async function runCorpusWindows(opts: {
let cursor = resumePoint(turns, state);
const windows = planCorpusWindows(turns, cursor, MAX_TURN_TEXT_CHARS, retiredTurns(state));
+ let failure = readCorpusFailure(full);
let done = 0;
let status: CorpusWindowRun['status'] = 'complete';
let holding = true;
try {
for (let w = 0; w < windows.length; w++) {
const win = windows[w];
+ const key = windowKey(turns, cursor);
+ let r: PipelineResult | null = null;
if (win.text) {
if (done >= opts.maxWindows) { status = 'partial'; break; }
if (opts.overBudget() || signal.aborted) { status = 'aborted'; break; }
+ const gate = corpusFailureGate(failure, key, incarnation, fingerprint, clock());
+ if (gate !== 'run') { status = gate; break; }
+ const text = win.text;
+ r = await extractUnderFailureCount({ full, record: failure, key, incarnation, fingerprint, nowMs: clock, signal }, () => opts.extract(text));
+ if (r.skipped_reason && CORPUS_NON_TERMINAL_SKIPS.includes(r.skipped_reason)) { status = 'unavailable'; break; }
}
- const r = win.text ? await opts.extract(win.text) : null;
if (signal.aborted) { status = 'aborted'; break; }
const finishedTurns = turns.slice(cursor.turn, win.endOffset === null ? win.endTurn + 1 : win.endTurn);
const isLast = w === windows.length - 1;
@@ -507,6 +636,10 @@ export async function runCorpusWindows(opts: {
});
if (!next) { status = 'contended'; break; }
state = next;
+ if (failure?.key === key) {
+ await clearCorpusFailure(full).catch(() => {});
+ failure = null;
+ }
if (r) done++;
if (isLast) holding = false;
cursor = win.endOffset === null ? { turn: win.endTurn + 1, offset: 0 } : { turn: win.endTurn, offset: win.endOffset };
@@ -534,8 +667,9 @@ export async function runCorpusWindows(opts: {
}
/**
- * The sweep's candidate list: files without `.ingested`, plus finished files
- * that changed since `.progress` recorded them (stat compare, no rehash). A
+ * The sweep's candidate list: files without a final `.ingested` (#6786: a
+ * `chat_unavailable` sidecar is not final), plus finished files that changed
+ * since `.progress` recorded them (stat compare, no rehash). A
* pre-window `.ingested` file is adopted at its current turns (budget
* permitting) so only later growth is extracted. Returns the candidates (at
* most `batchLimit`) and how many files are already done.
@@ -551,12 +685,12 @@ export async function selectCorpusCandidates(
let alreadyIngested = 0;
for (const name of txtFiles) {
const full = join(dir, name);
- let state: Awaited<ReturnType<typeof finishedCorpusFileState>> | 'new' = 'new';
+ let state: ReturnType<typeof corpusFileCompletion> = 'pending';
if (entrySet.has(name + '.ingested')) {
- state = await finishedCorpusFileState(full, name).catch(() => 'changed' as const);
+ try { state = corpusFileCompletion(full, name); } catch { state = 'changed'; }
if (state === 'legacy' && !overBudget()) await adoptFinishedCorpusFile(full).catch(() => false);
}
- if (state === 'done' || state === 'legacy') alreadyIngested++;
+ if (corpusFileFinished(state)) alreadyIngested++;
else if (candidates.length < batchLimit) candidates.push(name);
}
return { candidates, alreadyIngested };
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 01178a9914..089d6691b5 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -135,6 +135,17 @@ export const CODES = {
why: 'Read-only: lists the held file with the two slugs and the rendered paragraph; the user decides which page keeps the slug before anything is edited.',
verify: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'] } } },
content_rejected: { class: 'caller', summary: "The content-sanity gate rejected the content because the operator set `content_sanity.junk_disposition` to `reject`.", why: "A junk-pattern or operator-literal hit is refused instead of quarantined under that setting, so the page was not written. The same content refuses on every retry.", suggestion: 'Remove the matched junk from the file, or switch `content_sanity.junk_disposition` back to `quarantine` (a user decision), then import it again.' },
+ corpus_chat_unavailable: { class: 'unavailable', summary: "The sweep's corpus pass stopped because the extraction model is not servable in this process; the captured session files stay pending (no `.ingested` sidecar), so nothing was lost.",
+ why: "No servable model is a state of the extracting process, not of the transcript. Before #6786 it was recorded as a finished file with zero facts, and retention later deleted the text.",
+ suggestion: 'Configure the extraction model (gbrain models shows it) or run the sweep from a process that has its key; the next sweep extracts the pending files.',
+ fix: { argv: ['gbrain', 'models', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: shows the facts extraction model and whether its provider is configured.' } },
+ corpus_window_backoff: { class: 'retryable', summary: "A corpus window failed after its model call and waits out its retry delay (the next sweep, then 10, 20 and 40 minutes) before the sweep pays for it again.",
+ why: 'Without a delay a write that fails after extraction (#6785) was paid for again on every drain.',
+ fix: { argv: ['gbrain', 'sweep', '--retry-failed', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists the failing files, their attempt counts and the last error code.' } },
+ corpus_window_dead_lettered: { class: 'consent', summary: "A corpus window failed after its model call on every allowed attempt, so the sweep stopped paying for it; its file stays pending until an operator retries it.",
+ why: 'A window that can never commit was re-extracted forever before #6785. The count is per window and source incarnation; tail growth and changing error codes do not reset it, and one extraction-config change (model, provider, key presence) retries it once.',
+ suggestion: 'Fix the cause the last code names (for writer_coordinator_required: gbrain sources writer status <source>), then ask the user before gbrain sweep --retry-failed --apply: the retry pays for the extraction again.',
+ fix: { argv: ['gbrain', 'sweep', '--retry-failed', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists the stopped files, their attempt counts and the last error code.' } },
core_budget_exceeded: { class: 'caller', summary: "The write would push always-loaded core memory over its brain-wide character budget or page limit.", why: "Core pages enter every session's prompt in every harness, so their total size is capped on the write path.", docs: 'docs/guides/core-memory.md#budget', fix: { argv: ['gbrain', 'core', 'status', '--json'], consent: [], actor: 'agent', why: "Shows core usage against the budget and the largest core pages, read-only.", requires_exclusive: false } },
core_delete_owner_only: { class: 'consent', summary: "A remote caller tried to delete an always-loaded core page; only the owner can remove pages from core.", docs: 'docs/guides/core-memory.md#owner-only', actor: 'user' },
core_mark_owner_only: { class: 'consent', summary: "A remote caller tried to change always_load or core_priority; only the owner designates core pages.", docs: 'docs/guides/core-memory.md#owner-only', actor: 'user' },
diff --git a/src/core/facts/extraction-availability.ts b/src/core/facts/extraction-availability.ts
index ead557c52e..874519b85a 100644
--- a/src/core/facts/extraction-availability.ts
+++ b/src/core/facts/extraction-availability.ts
@@ -14,7 +14,8 @@
import type { BrainEngine } from '../engine.ts';
import type { CapabilityReport } from '../capability.ts';
-import { isAvailable } from '../ai/gateway.ts';
+import { createHash } from 'node:crypto';
+import { getEmbeddingModel, isAvailable } from '../ai/gateway.ts';
import { getFactsExtractionModel } from './extract.ts';
/** The resolved extraction model and whether the gateway can serve it. A
@@ -36,3 +37,20 @@ export async function extractionAvailableForEngine(
if (capabilityOverride) return capabilityOverride.extraction.available;
return (await resolveExtractionAvailability(engine)).available;
}
+
+/**
+ * #6785: a fingerprint of the extraction configuration (the resolved model,
+ * its provider, and whether the chat and embedding models are servable),
+ * never a key or other value. A corpus window capped after repeated failures
+ * is retried once when it changes.
+ */
+export async function extractionConfigFingerprint(engine: BrainEngine): Promise<string> {
+ const { model, available } = await resolveExtractionAvailability(engine);
+ let embedding: { model: string | null; available: boolean } = { model: null, available: false };
+ try {
+ const m = getEmbeddingModel();
+ embedding = { model: m, available: isAvailable('embedding', m) };
+ } catch { /* gateway unconfigured: no embedding model */ }
+ const provider = model.includes(':') ? model.slice(0, model.indexOf(':')) : null;
+ return createHash('sha256').update(JSON.stringify({ model, provider, chat: available, embedding })).digest('hex').slice(0, 16);
+}
diff --git a/src/core/persistence/filesystem-guard.ts b/src/core/persistence/filesystem-guard.ts
index 86f0636ec9..4ae4d7049e 100644
--- a/src/core/persistence/filesystem-guard.ts
+++ b/src/core/persistence/filesystem-guard.ts
@@ -3,7 +3,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
import { isAbsolute, relative, resolve, sep } from 'node:path';
import { OperationError } from '../ops/contract.ts';
import type { SqlEngine } from './model.ts';
-import { readPersistenceBrain } from './managed-mode.ts';
+import { readManagedMode, readPersistenceBrain } from './managed-mode.ts';
import { canonicalFilesystemPath, managedRootMarkerFor, recordManagedRoots, registeredManagedRootRecords, type ManagedRootRecord } from './root-registry.ts';
interface FileCapability { roots: string[]; active: boolean; }
@@ -76,3 +76,14 @@ export async function assertLegacyFilesystemWriter(engine: SqlEngine, path: stri
await refreshManagedFilesystemRoots(engine);
assertManagedFilesystemWrite(path);
}
+/**
+ * #5362/#6785: the legacy fence writer's refusal for a source's checkout,
+ * checked before a lane pays for extraction (a claimed but not activated
+ * canonical worktree refuses every fence write with writer_coordinator_required).
+ * A managed brain writes through the coordinator and is never refused here.
+ */
+export async function assertSourceLegacyWriter(engine: SqlEngine, sourceId: string): Promise<void> {
+ if (await readManagedMode(engine)) return;
+ const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [sourceId]);
+ if (source?.local_path) await assertLegacyFilesystemWriter(engine, source.local_path);
+}
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index c8c4515c5b..943168e83e 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -92,6 +92,9 @@ const CORPUS_WINDOW_SKIP = {
partial: 'corpus_windows_pending',
changed: 'corpus_changed',
source_changed: 'corpus_source_changed',
+ unavailable: 'corpus_chat_unavailable',
+ backoff: 'corpus_window_backoff',
+ dead_lettered: 'corpus_window_dead_lettered',
} as const;
export interface SweepOpts {
@@ -113,6 +116,12 @@ export interface SweepOpts {
* configured gateway (facts/extraction-availability.ts) — no network.
*/
capabilities?: CapabilityReport;
+ /**
+ * #6786: false skips the corpus pass (pass 3). `bootstrap verify` passes
+ * false: its probes need only passes 1 and 2, and its process may not have
+ * the gateway the extraction would use.
+ */
+ corpus?: boolean;
}
export interface SweepSkip {
@@ -256,7 +265,9 @@ export async function runMaintenanceSweep(
// ── Pass 3: corpus ingest [CX-P0.1] — spend-gated [CX-P0.5] ───────
try {
- if (overBudget()) {
+ if (opts.corpus === false) {
+ // #6786: the caller asked for passes 1 and 2 only.
+ } else if (overBudget()) {
skip('budget_exhausted:corpus');
} else {
// E-N2: the budget stops the corpus pass BETWEEN files and windows
@@ -270,6 +281,7 @@ export async function runMaintenanceSweep(
overBudget,
signal: new AbortController().signal,
capabilities: opts.capabilities,
+ now,
report,
skip,
log,
@@ -598,10 +610,11 @@ async function runCorpusIngestPass(
ctx: PassCtx & {
signal: AbortSignal;
capabilities?: CapabilityReport;
+ now: () => number;
log: (msg: string) => void;
},
): Promise<void> {
- const { batchLimit, overBudget, signal, report, skip, log } = ctx;
+ const { batchLimit, overBudget, signal, report, skip, log, now } = ctx;
// Corpus dir: dream's session corpus (transcripts.ts:66 precedent);
// default ~/.gbrain/transcripts/corpus (GBRAIN_HOME-aware via configDir).
@@ -613,7 +626,7 @@ async function runCorpusIngestPass(
// #6268: source-stamped files live in the spool subdirectory (listed
// first); top-level files are the legacy, unstamped corpus.
- const { CORPUS_SPOOL_SUBDIR, corpusSpoolDir, parseWbFileName, selfCaptureSidecarJson, corpusFileSessionId, corpusTextForExtraction } = await import('./context/corpus-segments.ts');
+ const { CORPUS_SPOOL_SUBDIR, corpusSpoolDir, parseWbFileName, selfCaptureSidecarJson, corpusFileSessionId, corpusTextForExtraction, corpusFileCompletion, corpusFileFinished, CORPUS_WINDOW_FAILURE_CAP } = await import('./context/corpus-segments.ts');
const spoolDir = corpusSpoolDir(dir);
const windows = await import('./context/corpus-windows.ts');
type Candidate = { base: string; name: string; location: 'spool' | 'legacy'; label: string };
@@ -683,6 +696,11 @@ async function runCorpusIngestPass(
return;
}
+ // #6785: a capped window re-arms once when this fingerprint changed since its last failure.
+ const { extractionConfigFingerprint } = await import('./facts/extraction-availability.ts');
+ const fingerprint = await extractionConfigFingerprint(engine).catch(() => null);
+ const writerRefused = await corpusWriterPreflight(engine, log);
+
const { runFactsPipeline } = await import('./facts/backstop.ts');
const { isDreamOutput } = await import('./cycle/transcript-discovery.ts');
const { claudeCliSelfProjectDirs, isClaudeCliSelfSessionId } = await import('./ai/providers/claude-cli-scratch.ts');
@@ -713,10 +731,8 @@ async function runCorpusIngestPass(
// Re-check under the claim: another sweep may have finished this file
// between our readdir and our claim (it releases its claim only after
// writing the .ingested sidecar, so this closes the double-spend gap).
- const doneAlready = await stat(full + CORPUS_INGESTED_SUFFIX).then(
- () => windows.finishedCorpusFileState(full, name).then(s => s === 'done' || s === 'legacy', () => false),
- () => false,
- );
+ let doneAlready = false;
+ try { doneAlready = corpusFileFinished(corpusFileCompletion(full, name)); } catch { /* unreadable: not done */ }
if (doneAlready) {
skip('already_ingested');
continue;
@@ -763,6 +779,10 @@ async function runCorpusIngestPass(
skip(fileSource.reason);
continue;
}
+ if (await writerRefused(fileSource.sourceId)) {
+ skip('writer_coordinator_required');
+ continue;
+ }
const pipelineCtx: FactsBackstopCtx = {
engine,
sourceId: fileSource.sourceId,
@@ -785,20 +805,32 @@ async function runCorpusIngestPass(
// at turn boundaries (#5887) and may finish over several sweeps.
let r: Awaited<ReturnType<typeof runFactsPipeline>>;
if (wbMeta) {
- windowsLeft -= 1;
- r = await runFactsPipeline(corpusTextForExtraction(name, raw), pipelineCtx);
+ const turn = await windows.runCorpusTurn({
+ full, signal, incarnation: fileSource.incarnation, failures: { fingerprint, now },
+ extract: () => runFactsPipeline(corpusTextForExtraction(name, raw), pipelineCtx),
+ });
+ if (turn.status !== 'backoff' && turn.status !== 'dead_lettered') windowsLeft -= 1;
+ if (turn.status !== 'complete') {
+ abortLoop = turn.status === 'unavailable';
+ skip(CORPUS_WINDOW_SKIP[turn.status], abortLoop ? candidates.length - i : 1);
+ if (turn.status === 'dead_lettered') log(deadLetterLine(label, CORPUS_WINDOW_FAILURE_CAP));
+ continue;
+ }
+ r = turn.result;
} else {
const run = await windows.runCorpusWindows({
full, raw, fileStat, overBudget, signal,
source: { id: fileSource.sourceId, incarnation: fileSource.incarnation },
maxWindows: Math.min(windows.CORPUS_WINDOWS_PER_SWEEP, windowsLeft),
extract: text => runFactsPipeline(text, pipelineCtx),
+ failures: { fingerprint, now },
});
windowsLeft -= run.windowsDone;
report.corpus_files.push({ file: label, windows_done: run.windowsDone, windows_remaining: run.windowsRemaining });
if (run.status !== 'complete') {
- abortLoop = run.status === 'aborted';
+ abortLoop = run.status === 'aborted' || run.status === 'unavailable';
skip(CORPUS_WINDOW_SKIP[run.status], abortLoop ? candidates.length - i : 1);
+ if (run.status === 'dead_lettered') log(deadLetterLine(label, CORPUS_WINDOW_FAILURE_CAP));
continue;
}
r = run.result;
@@ -822,32 +854,7 @@ async function runCorpusIngestPass(
// the guaranteed lane (receipt retry); here a publish failure is
// fail-open and `.ingested` is written regardless (facts are durable;
// re-extracting just to retry a link append is the worse trade).
- let linksBanked = 0;
- if (r.entity_slugs.length) {
- try {
- const segs = await import('./context/corpus-segments.ts');
- const parsed = segs.parseSegmentFileName(name);
- if (parsed) {
- const verified: Array<{ slug: string; title: string }> = [];
- for (const slug of r.entity_slugs) {
- try {
- const page = await engine.getPage(slug, { sourceId: fileSource.sourceId });
- if (page) verified.push({ slug, title: page.title || slug });
- } catch { /* a non-resolvable link is never banked */ }
- }
- if (verified.length) {
- const ss = await import('./context/session-state.ts');
- const ledger = segs.readSegmentLedger(base, parsed.sessionId);
- const n = Math.max(1, ledger.findIndex((e) => e.hash === parsed.hash) + 1);
- const ok = await ss.appendCheckpointManifest(
- engine, fileSource.sourceId, null, parsed.sessionId, verified,
- { seg: parsed.hash, n },
- );
- if (ok) linksBanked = verified.length;
- }
- }
- } catch { /* link publish is best-effort on the backstop lane */ }
- }
+ const linksBanked = r.entity_slugs.length ? await bankSegmentLinks(engine, base, name, fileSource.sourceId, r.entity_slugs) : 0;
// Sidecar AFTER success — a crash before this line re-processes the
// file next sweep (dedup absorbs the repeats), never loses it.
@@ -873,7 +880,8 @@ async function runCorpusIngestPass(
skip('writeback_off_inflight');
} else {
skip('corpus_file_error');
- log(`[sweep] corpus ingest failed for ${name}: ${e instanceof Error ? e.message : String(e)}`);
+ const code = (e as { code?: unknown }).code;
+ log(`[sweep] corpus ingest failed for ${name}${typeof code === 'string' ? ` (${code})` : ''}: ${e instanceof Error ? e.message : String(e)}`);
}
} finally {
// Success (its .ingested sidecar now stands in) and failure (retry next
@@ -884,6 +892,60 @@ async function runCorpusIngestPass(
}
}
+/** Cathedral 5: publish a compaction segment's verified entity links to its session manifest; the count banked, 0 on any failure. */
+async function bankSegmentLinks(engine: BrainEngine, base: string, name: string, sourceId: string, slugs: string[]): Promise<number> {
+ try {
+ const segs = await import('./context/corpus-segments.ts');
+ const parsed = segs.parseSegmentFileName(name);
+ if (!parsed) return 0;
+ const verified: Array<{ slug: string; title: string }> = [];
+ for (const slug of slugs) {
+ try {
+ const page = await engine.getPage(slug, { sourceId });
+ if (page) verified.push({ slug, title: page.title || slug });
+ } catch { /* a non-resolvable link is never banked */ }
+ }
+ if (!verified.length) return 0;
+ const ss = await import('./context/session-state.ts');
+ const ledger = segs.readSegmentLedger(base, parsed.sessionId);
+ const n = Math.max(1, ledger.findIndex((e) => e.hash === parsed.hash) + 1);
+ const ok = await ss.appendCheckpointManifest(engine, sourceId, null, parsed.sessionId, verified, { seg: parsed.hash, n });
+ return ok ? verified.length : 0;
+ } catch {
+ return 0; /* link publish is best-effort on the backstop lane */
+ }
+}
+
+/**
+ * #6785: the facts-absorb owner-readiness preflight (#5362), once per source
+ * per pass and before any model call: a claimed but not activated canonical
+ * worktree refuses the fence write AFTER extraction, which every later sweep
+ * would pay for again. Returns whether the source is held.
+ */
+async function corpusWriterPreflight(engine: BrainEngine, log: (msg: string) => void): Promise<(sourceId: string) => Promise<boolean>> {
+ const { assertSourceLegacyWriter } = await import('./persistence/filesystem-guard.ts');
+ const held = new Map<string, boolean>();
+ return async (sourceId) => {
+ if (!held.has(sourceId)) {
+ try {
+ await assertSourceLegacyWriter(engine, sourceId);
+ held.set(sourceId, false);
+ } catch (e) {
+ if ((e as { code?: unknown }).code !== 'writer_coordinator_required') throw e;
+ held.set(sourceId, true);
+ log(`[sweep] corpus extraction into source ${sourceId} is held before any model call: writer_coordinator_required `
+ + `(${e instanceof Error ? e.message : String(e)}). Check the writer: gbrain sources writer status ${sourceId}`);
+ }
+ }
+ return held.get(sourceId)!;
+ };
+}
+
+function deadLetterLine(label: string, cap: number): string {
+ return `[sweep] ${label}: corpus_window_dead_lettered — its next window failed ${cap} times after the model call, `
+ + 'so the sweep stopped paying for it. Fix the cause, then preview a retry: gbrain sweep --retry-failed';
+}
+
/**
* Try to claim a corpus file for ingestion. O_EXCL (`wx`) create is the
* atomic primitive; a live existing claim (< CORPUS_CLAIM_STALE_MS old)
@@ -977,24 +1039,33 @@ export interface CorpusDrainOpts {
clearIntervalFn?: (handle: unknown) => void;
/** Sweep body override (tests). Default: runMaintenanceSweep with CORPUS_DRAIN_BUDGET_MS. */
sweep?: (engine: BrainEngine) => Promise<unknown>;
+ /** #6785: diagnostic sink. Default: stderr (serve.err). */
+ log?: (msg: string) => void;
}
-/** True when the corpus dir holds a `.txt` with no `.ingested` sidecar. Missing dir = false. */
+/** True when the corpus dir holds a `.txt` with no final `.ingested` sidecar (#6786). Missing dir = false. */
async function corpusHasPendingFiles(engine: BrainEngine): Promise<boolean> {
let dir = await engine.getConfig('dream.synthesize.session_corpus_dir');
if (!dir) {
const { configDir } = await import('./config.ts');
dir = join(configDir(), 'transcripts', 'corpus');
}
- const { corpusSpoolDir } = await import('./context/corpus-segments.ts');
+ const { corpusSidecarState, corpusSpoolDir } = await import('./context/corpus-segments.ts');
for (const base of [corpusSpoolDir(dir), dir]) {
const names = await readdir(base).catch(() => [] as string[]);
const present = new Set(names);
- if (names.some(n => n.endsWith('.txt') && !present.has(n + CORPUS_INGESTED_SUFFIX))) return true;
+ if (names.some(n => n.endsWith('.txt') && (!present.has(n + CORPUS_INGESTED_SUFFIX) || corpusSidecarState(join(base, n)) !== 'final'))) return true;
}
return false;
}
+/** #6785: the drain's skip reasons worth an operator's eye (every reason but `already_ingested`), sorted. */
+function drainSkipReasons(report: unknown): string[] {
+ const skipped = (report as Partial<SweepReport> | null)?.skipped;
+ if (!Array.isArray(skipped)) return [];
+ return skipped.filter(s => s.reason !== 'already_ingested').map(s => `${s.reason} x${s.count}`).sort();
+}
+
/**
* X8 (D18): the corpus drain a `serve --http` process owns. A stdio serve
* sweeps at startup and on idle ticks; the HTTP serve never swept, so a turn
@@ -1004,7 +1075,9 @@ async function corpusHasPendingFiles(engine: BrainEngine): Promise<boolean> {
* one bounded sweep runs under the corpus pass's own gates (keyless skip,
* the writeback gate, claims, per-file and per-sweep window caps). Never
* overlaps itself; unref'd; never throws. `tick` runs one decision now.
- * Returns null when GBRAIN_SWEEP=0.
+ * #6785: the sweep's diagnostics and a thrown tick reach `log` (stderr),
+ * each distinct line once per serve run, and the skip reasons whenever
+ * their set changes. Returns null when GBRAIN_SWEEP=0.
*/
export function armCorpusDrain(
engine: BrainEngine,
@@ -1015,17 +1088,32 @@ export function armCorpusDrain(
const setI = opts.setIntervalFn ?? ((fn: () => void, ms: number) => setInterval(fn, ms));
const clearI = opts.clearIntervalFn
?? ((h: unknown) => clearInterval(h as ReturnType<typeof setInterval>));
+ const sink = opts.log ?? ((msg: string) => { process.stderr.write(`${msg}\n`); });
+ const seen = new Set<string>();
+ const log = (msg: string): void => {
+ if (seen.has(msg)) return;
+ if (seen.size >= 1000) seen.clear();
+ seen.add(msg);
+ sink(msg);
+ };
const run = opts.sweep
- ?? ((e: BrainEngine) => runMaintenanceSweep(e, { sourceId: opts.sourceId, budgetMs: CORPUS_DRAIN_BUDGET_MS }));
+ ?? ((e: BrainEngine) => runMaintenanceSweep(e, { sourceId: opts.sourceId, budgetMs: CORPUS_DRAIN_BUDGET_MS, log }));
let inFlight = false;
let cancelled = false;
+ let lastReasons = '';
const tick = async (): Promise<void> => {
if (inFlight || cancelled) return;
inFlight = true;
try {
- if (await corpusHasPendingFiles(engine)) await run(engine);
- } catch {
- /* the drain is best-effort; never kill serve */
+ if (await corpusHasPendingFiles(engine)) {
+ const reasons = drainSkipReasons(await run(engine));
+ const set = reasons.map(r => r.slice(0, r.lastIndexOf(' x'))).join(',');
+ if (set !== lastReasons && reasons.length) sink(`[sweep] corpus drain skipped: ${reasons.join(', ')}`);
+ lastReasons = set;
+ }
+ } catch (e) {
+ // The drain is best-effort and never kills serve, but it says why.
+ log(`[sweep] corpus drain failed: ${e instanceof Error ? e.message : String(e)}`);
} finally {
inFlight = false;
}
diff --git a/test/bootstrap-verify.serial.test.ts b/test/bootstrap-verify.serial.test.ts
index 481653f1f0..61aac764f7 100644
--- a/test/bootstrap-verify.serial.test.ts
+++ b/test/bootstrap-verify.serial.test.ts
@@ -331,6 +331,28 @@ describe('verifyWorkspace — write-through disabled by config', () => {
}, 240_000);
});
+describe('verifyWorkspace — pending corpus transcripts (#6786)', () => {
+ test('a keyed report in a process that cannot serve the extraction model leaves pending transcripts pending', async () => {
+ const corpusDir = mkdtempSync(join(tmpdir(), 'gb-verify-corpus-'));
+ const spool = join(corpusDir, 'sourced');
+ mkdirSync(spool, { recursive: true });
+ const transcript = join(spool, 'sess-verify-example.src-workspace.txt');
+ writeFileSync(transcript, '[user]\nI keep a written log of every product decision.\n\n[assistant]\nNoted.\n');
+ const KEYED: CapabilityReport = { embeddings: { available: false }, extraction: { available: true, provider: 'anthropic' }, search: 'keyword-only', mode: 'keyed' };
+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpusDir);
+ try {
+ // verify's engine never configures the gateway, so no extraction model is servable.
+ const res = await verifyWorkspace(engine, ws, { sourceId: 'workspace', gbrainHomeDir: home, capabilities: KEYED });
+ expect(check(res.checks, 'graph_floor')[0].ok).toBe(true);
+ expect(existsSync(`${transcript}.ingested`)).toBe(false);
+ expect(existsSync(`${transcript}.progress`)).toBe(false);
+ } finally {
+ await engine.unsetConfig('dream.synthesize.session_corpus_dir');
+ rmSync(corpusDir, { recursive: true, force: true });
+ }
+ }, 240_000);
+});
+
describe('verifyWorkspace — probe cleanup on an early roundtrip exit (#6001)', () => {
test('a roundtrip that fails before its cleanup step still removes both probe pages', async () => {
// A DIRECTORY where the second probe's file must go: the entity probe lands (row + file), the
diff --git a/test/sweep-corpus-chat-unavailable-6786.test.ts b/test/sweep-corpus-chat-unavailable-6786.test.ts
new file mode 100644
index 0000000000..06f33d3d9f
--- /dev/null
+++ b/test/sweep-corpus-chat-unavailable-6786.test.ts
@@ -0,0 +1,334 @@
+/**
+ * #6786 — `chat_unavailable` is not a finished corpus file.
+ *
+ * `bootstrap verify` ran the corpus pass with a keyed capability report in a
+ * process whose gateway could not serve the extraction model. Every window
+ * came back `chat_unavailable`; the window runner recorded its turns as done
+ * and the sweep wrote `.ingested {"skipped":"chat_unavailable"}`, so the
+ * transcript was never extracted and retention later deleted it.
+ *
+ * Protects: an unservable model leaves windowed and writeback files pending
+ * (no sidecar, no consumed turns) in the sweep and the compact harvest; a
+ * file a pre-#6786 build marked that way (with or without `.progress`) is
+ * extracted again with its source binding and retired turns kept, and its
+ * facts land; retention GC keeps such a file at the un-ingested ceiling in
+ * both orders (GC then sweep, sweep then GC); the corpus pass can be skipped.
+ *
+ * Imports only modules that predate #6786, so it runs against the old tree.
+ * Hermetic in-memory PGLite + chat-transport stub (sweep.test.ts harness).
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { CORPUS_INGESTED_SUFFIX, runMaintenanceSweep, type SweepReport } from '../src/core/sweep.ts';
+import { __setChatTransportForTests, configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';
+import { RECIPES } from '../src/core/ai/recipes/index.ts';
+import type { CapabilityReport } from '../src/core/capability.ts';
+import { toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';
+import { parseCorpusTurns } from '../src/core/context/corpus-turns.ts';
+import { corpusSpoolDir, ensureCorpusSpoolDir, gcCorpusTurnFiles, segmentFileName, writeSegment, appendSegmentLedger, wbFileName } from '../src/core/context/corpus-segments.ts';
+import { __drainCheckpointHarvestForTests, __resetCheckpointHarvestForTests, HARVEST_RECEIPT_SUFFIX, scheduleCheckpointHarvest } from '../src/core/context/checkpoint-harvest.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const KEYED: CapabilityReport = {
+ embeddings: { available: false },
+ extraction: { available: true, provider: 'anthropic' },
+ search: 'keyword-only',
+ mode: 'keyed',
+};
+const DAY = 86_400_000;
+const RETENTION = 30 * DAY;
+
+let engine: PGLiteEngine;
+let dir: string;
+let home: string;
+const tmpDirs: string[] = [];
+let inputs: string[];
+
+const authNames = [...new Set(Array.from(RECIPES.values()).flatMap((recipe) => recipe.auth_env?.required ?? []))];
+const noKeys = Object.fromEntries(authNames.map((name) => [name, undefined]));
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ for (const d of tmpDirs) rmSync(d, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM facts').catch(() => {});
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-6786-corpus-'));
+ home = mkdtempSync(join(tmpdir(), 'gbrain-6786-home-'));
+ tmpDirs.push(dir, home);
+ await engine.setConfig('dream.synthesize.session_corpus_dir', dir);
+ // Writeback turn files extract only while ambient writeback is on.
+ await engine.setConfig('memory.auto_writeback', 'salient');
+ inputs = [];
+ __resetCheckpointHarvestForTests();
+});
+
+afterEach(async () => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ await engine.unsetConfig('memory.auto_writeback');
+});
+
+/** The verify process: a keyed capability report, but no servable extraction model. */
+function unservable(): void {
+ __setChatTransportForTests(null);
+ configureGateway({ env: {} });
+}
+
+/** A working extractor: every window yields one fact naming its first turn marker. */
+function servable(): void {
+ __setChatTransportForTests(async (request): Promise<ChatResult> => {
+ const content = String(request.messages[0].content);
+ const text = content.slice(content.indexOf('<turn>\n') + '<turn>\n'.length, content.lastIndexOf('\n</turn>'));
+ inputs.push(text);
+ const marker = text.match(/\bT\d\d\b/)?.[0] ?? 'WB';
+ return {
+ text: JSON.stringify({ facts: [{ fact: `Keeps a written log of decision ${marker}`, kind: 'preference', entity: null, confidence: 0.9, notability: 'high' }] }),
+ blocks: [], stopReason: 'end',
+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:test-stub', providerId: 'anthropic',
+ };
+ });
+}
+
+const sweep = (extra: Partial<Parameters<typeof runMaintenanceSweep>[1]> = {}): Promise<SweepReport> =>
+ withEnv({ ...noKeys, GBRAIN_HOME: home }, () =>
+ runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED, budgetMs: 120_000, batchLimit: 20, ...extra }));
+
+const body = (tag: string, n = 5000): string => {
+ let s = `${tag} `;
+ while (s.length < n) s += `${tag.toLowerCase()} detail words\n`;
+ return s.slice(0, n);
+};
+const corpus = (count: number): string =>
+ toCorpusText(Array.from({ length: count }, (_, i) => ({ role: i % 2 === 0 ? 'user' as const : 'assistant' as const, text: body(`T${String(i).padStart(2, '0')}`) })));
+const markers = (texts: string[]): string[] => [...new Set(texts.flatMap((t) => t.match(/\bT\d\d\b/g) ?? []))].sort();
+const sidecar = (file: string): Record<string, unknown> => JSON.parse(readFileSync(file + CORPUS_INGESTED_SUFFIX, 'utf8'));
+const progress = (file: string): Record<string, any> => JSON.parse(readFileSync(file + '.progress', 'utf8'));
+const corpusFacts = async (): Promise<string[]> =>
+ (await engine.executeRaw<{ fact: string }>(`SELECT fact FROM facts WHERE source = 'sweep:corpus' ORDER BY fact`)).map((r) => r.fact);
+const skipped = (r: SweepReport, reason: string): number => r.skipped.find((s) => s.reason === reason)?.count ?? 0;
+
+function age(file: string, days: number): void {
+ const t = new Date(Date.now() - days * DAY);
+ utimesSync(file, t, t);
+}
+
+/**
+ * What a pre-#6786 sweep left behind for a windowed file: every turn recorded
+ * as done (one of them retired under writeback off), `finished` at the file's
+ * stat, `skipped_reason: chat_unavailable`, the source binding, and the
+ * zero-count `.ingested` sidecar.
+ */
+async function legacyUnavailable(file: string, opts: { progress: boolean; retire?: number }): Promise<{ retired: string | null }> {
+ const turns = parseCorpusTurns(readFileSync(file, 'utf8'));
+ const retired = opts.retire === undefined ? null : turns[opts.retire].sha256;
+ if (opts.progress) {
+ const st = statSync(file);
+ writeFileSync(file + '.progress', JSON.stringify({
+ version: 1, generation: 9,
+ turns: turns.map(({ start, end, sha256 }) => ({ start, end, sha256 })),
+ continuation: null, windows_done: turns.length,
+ finished: { size: st.size, mtime_ms: st.mtimeMs, ino: st.ino },
+ totals: { inserted: 0, duplicate: 0, superseded: 0 }, entity_slugs: [],
+ skipped_reason: 'chat_unavailable',
+ ...(retired ? { retired_turns: [retired] } : {}),
+ source: { id: 'default', incarnation: await sourceIncarnation() },
+ lease: null,
+ }) + '\n');
+ }
+ writeFileSync(file + CORPUS_INGESTED_SUFFIX,
+ JSON.stringify({ ingested_at: new Date().toISOString(), facts_inserted: 0, facts_duplicate: 0, skipped: 'chat_unavailable' }) + '\n');
+ return { retired };
+}
+
+async function sourceIncarnation(): Promise<string> {
+ const [row] = await engine.executeRaw<{ incarnation: string }>(`SELECT incarnation::text AS incarnation FROM sources WHERE id = 'default'`);
+ return row.incarnation;
+}
+
+describe('#6786: an unservable extraction model leaves corpus files pending', () => {
+ test('windowed and writeback files get no sidecar and no consumed turns; the next servable sweep extracts them', async () => {
+ const file = join(dir, 'pending-session.txt');
+ writeFileSync(file, corpus(3));
+ const spool = ensureCorpusSpoolDir(dir);
+ const wb = join(spool, wbFileName('sess-wb', 'a'.repeat(24), 'default'));
+ writeFileSync(wb, '[user]\nWB I keep a written log of every decision I make.\n');
+
+ unservable();
+ const r1 = await sweep();
+ expect(r1.corpusIngested).toBe(0);
+ expect(existsSync(file + CORPUS_INGESTED_SUFFIX)).toBe(false);
+ expect(existsSync(wb + CORPUS_INGESTED_SUFFIX)).toBe(false);
+ expect(skipped(r1, 'corpus_chat_unavailable')).toBeGreaterThan(0);
+ if (existsSync(file + '.progress')) {
+ expect(progress(file).turns).toEqual([]);
+ expect(progress(file).finished).toBeNull();
+ }
+
+ servable();
+ const r2 = await sweep();
+ expect(r2.corpusIngested).toBe(2);
+ expect(markers(inputs)).toEqual(['T00', 'T01', 'T02']);
+ expect(inputs.some((t) => t.includes('written log of every decision'))).toBe(true);
+ expect(sidecar(file).skipped).toBeUndefined();
+ expect(Number(sidecar(file).facts_inserted)).toBeGreaterThan(0);
+ expect((await corpusFacts()).length).toBeGreaterThanOrEqual(3);
+ });
+
+ test('the compact harvest writes no receipt and records no window under an unservable model', async () => {
+ await withEnv({ ...noKeys, GBRAIN_HOME: home }, async () => {
+ const w = writeSegment(dir, 'sess-harvest', corpus(2));
+ appendSegmentLedger(dir, 'sess-harvest', w.hash);
+ const name = segmentFileName('sess-harvest', w.hash);
+ const full = join(dir, name);
+ unservable();
+ expect(scheduleCheckpointHarvest({ engine, sourceId: 'default', sessionId: 'sess-harvest', corpusDir: dir, file: name, capabilities: KEYED }).status).toBe('scheduled');
+ await __drainCheckpointHarvestForTests();
+ expect(existsSync(full + CORPUS_INGESTED_SUFFIX)).toBe(false);
+ expect(existsSync(full + HARVEST_RECEIPT_SUFFIX)).toBe(false);
+ if (existsSync(full + '.progress')) expect(progress(full).turns).toEqual([]);
+ });
+ servable();
+ const r = await sweep();
+ expect(r.corpusIngested).toBe(1);
+ expect(markers(inputs)).toEqual(['T00', 'T01']);
+ });
+
+ test('corpus: false skips the corpus pass (bootstrap verify): no model call, no sidecar', async () => {
+ const file = join(dir, 'verify-pending.txt');
+ writeFileSync(file, corpus(1));
+ servable();
+ const r = await sweep({ corpus: false } as never);
+ expect(inputs).toEqual([]);
+ expect(r.corpusIngested).toBe(0);
+ expect(existsSync(file + CORPUS_INGESTED_SUFFIX)).toBe(false);
+ });
+});
+
+describe('#6786: files a pre-#6786 sweep marked chat_unavailable are extracted again', () => {
+ test('a consumed .progress is rewound: extraction runs, facts land, source binding and retired turns stay', async () => {
+ const file = join(dir, 'legacy-progress.txt');
+ writeFileSync(file, corpus(3));
+ const { retired } = await legacyUnavailable(file, { progress: true, retire: 1 });
+ const inc = await sourceIncarnation();
+
+ servable();
+ const r = await sweep();
+ expect(r.corpusIngested).toBe(1);
+ expect(markers(inputs)).toEqual(['T00', 'T02']);
+ const facts = await corpusFacts();
+ expect(facts.some((f) => f.includes('T00'))).toBe(true);
+ expect(facts.some((f) => f.includes('T02'))).toBe(true);
+ expect(facts.some((f) => f.includes('T01'))).toBe(false);
+ expect(sidecar(file).skipped).toBeUndefined();
+ expect(Number(sidecar(file).facts_inserted)).toBeGreaterThanOrEqual(2);
+ const p = progress(file);
+ expect(p.source).toEqual({ id: 'default', incarnation: inc });
+ expect(p.retired_turns).toEqual([retired]);
+ expect(p.skipped_reason).toBeUndefined();
+ expect(p.finished).not.toBeNull();
+
+ inputs = [];
+ const again = await sweep();
+ expect(inputs).toEqual([]);
+ expect(again.corpusIngested).toBe(0);
+ });
+
+ test('a pre-window sidecar (no .progress) is not adopted as done: every turn is extracted', async () => {
+ const file = join(dir, 'legacy-sidecar-only.txt');
+ writeFileSync(file, corpus(2));
+ age(file, 1);
+ await legacyUnavailable(file, { progress: false });
+ servable();
+ const r = await sweep();
+ expect(r.corpusIngested).toBe(1);
+ expect(markers(inputs)).toEqual(['T00', 'T01']);
+ expect((await corpusFacts()).length).toBeGreaterThanOrEqual(2);
+ });
+
+ test('a writeback turn marked chat_unavailable is extracted again', async () => {
+ const spool = ensureCorpusSpoolDir(dir);
+ const wb = join(spool, wbFileName('sess-wb-legacy', 'b'.repeat(24), 'default'));
+ writeFileSync(wb, '[user]\nWB I keep a written log of every decision I make.\n');
+ writeFileSync(wb + CORPUS_INGESTED_SUFFIX, JSON.stringify({ ingested_at: new Date().toISOString(), facts_inserted: 0, facts_duplicate: 0, skipped: 'chat_unavailable' }) + '\n');
+ servable();
+ const r = await sweep();
+ expect(r.corpusIngested).toBe(1);
+ expect(inputs.length).toBe(1);
+ expect(sidecar(wb).skipped).toBeUndefined();
+ });
+});
+
+describe('#6786: retention GC keeps a chat_unavailable file until it is extracted', () => {
+ test('GC then sweep: an aged chat_unavailable file survives GC, then its facts land', async () => {
+ const file = join(dir, 'aged-gc-first.txt');
+ writeFileSync(file, corpus(2));
+ age(file, 40);
+ await legacyUnavailable(file, { progress: true });
+ gcCorpusTurnFiles(dir, RETENTION);
+ expect(existsSync(file)).toBe(true);
+ // Its finished, extracted twin of the same age goes at retention.
+ const done = join(dir, 'aged-done.txt');
+ writeFileSync(done, corpus(1));
+ age(done, 40);
+ writeFileSync(done + CORPUS_INGESTED_SUFFIX, JSON.stringify({ ingested_at: new Date().toISOString(), facts_inserted: 1 }) + '\n');
+ gcCorpusTurnFiles(dir, RETENTION);
+ expect(existsSync(done)).toBe(false);
+ expect(existsSync(file)).toBe(true);
+
+ servable();
+ const r = await sweep();
+ expect(r.corpusIngested).toBe(1);
+ expect((await corpusFacts()).some((f) => f.includes('T01'))).toBe(true);
+ gcCorpusTurnFiles(dir, RETENTION);
+ expect(existsSync(file)).toBe(false);
+ });
+
+ test('sweep then GC: an unservable sweep and a partial sweep both leave the aged file at the un-ingested ceiling', async () => {
+ const file = join(dir, 'aged-sweep-first.txt');
+ writeFileSync(file, corpus(3));
+ age(file, 40);
+ await legacyUnavailable(file, { progress: true });
+
+ unservable();
+ await sweep();
+ gcCorpusTurnFiles(dir, RETENTION);
+ expect(existsSync(file)).toBe(true);
+
+ servable();
+ await withEnv({ GBRAIN_CORPUS_WINDOWS_PER_SWEEP: '1' }, async () => {
+ const partial = await sweep();
+ expect(partial.corpus_files).toEqual([{ file: 'aged-sweep-first.txt', windows_done: 1, windows_remaining: 2 }]);
+ });
+ gcCorpusTurnFiles(dir, RETENTION);
+ expect(existsSync(file)).toBe(true);
+
+ const r = await sweep();
+ expect(r.corpusIngested).toBe(1);
+ expect(markers(inputs)).toEqual(['T00', 'T01', 'T02']);
+ expect((await corpusFacts()).length).toBeGreaterThanOrEqual(3);
+ gcCorpusTurnFiles(dir, RETENTION);
+ expect(existsSync(file)).toBe(false);
+ });
+
+ test('past the un-ingested ceiling a chat_unavailable file is still deleted (the bound stands)', async () => {
+ const file = join(dir, 'aged-past-ceiling.txt');
+ writeFileSync(file, corpus(1));
+ age(file, 91);
+ await legacyUnavailable(file, { progress: true });
+ gcCorpusTurnFiles(dir, RETENTION);
+ expect(existsSync(file)).toBe(false);
+ expect(existsSync(corpusSpoolDir(dir))).toBe(false);
+ });
+});
diff --git a/test/sweep-corpus-failure-cap-6785.test.ts b/test/sweep-corpus-failure-cap-6785.test.ts
new file mode 100644
index 0000000000..fb20d06e12
--- /dev/null
+++ b/test/sweep-corpus-failure-cap-6785.test.ts
@@ -0,0 +1,342 @@
+/**
+ * #6785 — a corpus window that fails after its model call is not paid for
+ * forever.
+ *
+ * A claimed but not activated canonical worktree refused every fence write
+ * with writer_coordinator_required AFTER extraction. The window was never
+ * committed, the claim was released, and the serve drain paid for the same
+ * windows every 10 minutes for hours while discarding the report.
+ *
+ * Protects: the sweep and the compact harvest run the facts-absorb
+ * owner-readiness preflight (#5362) before any model call and name
+ * `gbrain sources writer status <id>`; a window that keeps failing after its
+ * model call is retried on the next sweep, then after 10, 20 and 40 minutes,
+ * then stopped at 5 attempts, whatever the error label and however the file
+ * grows; one extraction-config change re-arms it once; the operator retry
+ * (`gbrain sweep --retry-failed --apply`, named as doctor's paid fix)
+ * extracts it and its facts land; the HTTP drain logs skip reasons and
+ * thrown errors instead of discarding them.
+ *
+ * The preflight, drain and cost assertions import only modules that predate
+ * #6785 and fail on the old tree. Hermetic in-memory PGLite + transport stubs.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { armCorpusDrain, CORPUS_INGESTED_SUFFIX, runMaintenanceSweep, type SweepReport } from '../src/core/sweep.ts';
+import { __setChatTransportForTests, __setEmbedTransportForTests, configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';
+import type { CapabilityReport } from '../src/core/capability.ts';
+import { toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';
+import { appendSegmentLedger, ensureCorpusSpoolDir, segmentFileName, sessionCorpusFileName, writeSegment } from '../src/core/context/corpus-segments.ts';
+import { __drainCheckpointHarvestForTests, __resetCheckpointHarvestForTests, HARVEST_RECEIPT_SUFFIX, scheduleCheckpointHarvest } from '../src/core/context/checkpoint-harvest.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const KEYED: CapabilityReport = {
+ embeddings: { available: false },
+ extraction: { available: true, provider: 'anthropic' },
+ search: 'keyword-only',
+ mode: 'keyed',
+};
+const MIN = 60_000;
+const usage = { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 };
+const tmpDirs: string[] = [];
+
+afterAll(() => {
+ for (const d of tmpDirs) rmSync(d, { recursive: true, force: true });
+});
+
+const tmp = (prefix: string): string => {
+ const d = mkdtempSync(join(tmpdir(), prefix));
+ tmpDirs.push(d);
+ return d;
+};
+const turnsText = (count: number, from = 0): string =>
+ toCorpusText(Array.from({ length: count }, (_, i) => ({
+ role: (from + i) % 2 === 0 ? 'user' as const : 'assistant' as const,
+ text: `T${String(from + i).padStart(2, '0')} Alice Example prefers written status updates over meetings for the weekly review.`,
+ })));
+const skipped = (r: SweepReport, reason: string): number => r.skipped.find((s) => s.reason === reason)?.count ?? 0;
+const fact = (entity: string | null) => JSON.stringify({ facts: [{ fact: 'Prefers written status updates over meetings.', kind: 'preference', entity, confidence: 1, notability: 'high' }] });
+
+describe('#6785: a claimed, not activated worktree is held before any model call', () => {
+ let engine: PGLiteEngine;
+ let home: string;
+ let chatCalls = 0;
+ let onCall: (() => Promise<void>) | null = null;
+ const logs: string[] = [];
+
+ /** A source whose checkout holds one entity page the extracted fact is fenced onto. */
+ async function addCheckout(sourceId: string): Promise<string> {
+ const root = join(tmp(`gbrain-6785-${sourceId}-`), 'brain');
+ mkdirSync(join(root, 'people'), { recursive: true });
+ writeFileSync(join(root, 'people/alice-example.md'), '---\ntitle: Alice Example\ntype: person\n---\nAlice Example.\n');
+ if (sourceId === 'default') await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [root]);
+ else await engine.executeRaw('INSERT INTO sources(id, name, local_path) VALUES($1, $1, $2)', [sourceId, root]);
+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice Example.' }, { sourceId });
+ return root;
+ }
+
+ /** A fresh corpus dir holding one session file stamped for `sourceId`. */
+ async function sessionFile(sourceId: string, session: string): Promise<string> {
+ const dir = tmp('gbrain-6785-corpus-');
+ await engine.setConfig('dream.synthesize.session_corpus_dir', dir);
+ const file = join(ensureCorpusSpoolDir(dir), sessionCorpusFileName(session, sourceId));
+ writeFileSync(file, turnsText(2));
+ return file;
+ }
+
+ let defaultRoot: string;
+
+ beforeAll(async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,
+ env: { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' } });
+ __setChatTransportForTests(async (): Promise<ChatResult> => {
+ chatCalls++;
+ if (onCall) await onCall();
+ return { text: fact('people/alice-example'), blocks: [], stopReason: 'end', usage, model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' };
+ });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => Array(1536).fill(0.01)) })) as never);
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ home = tmp('gbrain-6785-home-');
+ await engine.setConfig('sync.write_through', 'true');
+ defaultRoot = await addCheckout('default');
+ // Claimed and never activated, before any test runs.
+ await claimWorktree(engine, 'claimed-example', await addCheckout('claimed-example'));
+ }, 120_000);
+
+ afterAll(async () => {
+ __setChatTransportForTests(null);
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+ });
+
+ const sweep = (sourceId: string): Promise<SweepReport> => withEnv({ GBRAIN_HOME: home }, () =>
+ runMaintenanceSweep(engine, { sourceId, capabilities: KEYED, budgetMs: 120_000, log: (m) => logs.push(m) }));
+
+ test('the claim lands mid-call: that one call is lost, and every later sweep holds the file without paying', async () => {
+ const file = await sessionFile('default', 'sess-mid-call');
+ // The writer is claimed while the first extraction is in flight, so the
+ // fence write after it is refused (the real failure path of #6785).
+ onCall = async () => {
+ onCall = null;
+ await claimWorktree(engine, 'default', defaultRoot);
+ };
+ const first = await sweep('default');
+ expect(chatCalls).toBeGreaterThan(0);
+ expect(skipped(first, 'corpus_file_error')).toBe(1);
+ const paid = chatCalls;
+
+ for (let i = 0; i < 3; i++) {
+ const r = await sweep('default');
+ expect(chatCalls).toBe(paid);
+ expect(skipped(r, 'writer_coordinator_required')).toBe(1);
+ }
+ expect(existsSync(file + CORPUS_INGESTED_SUFFIX)).toBe(false);
+ expect(logs.join('\n')).toContain('(writer_coordinator_required)');
+ expect(logs.join('\n')).toContain('gbrain sources writer status default');
+ });
+
+ test('the compact harvest holds a segment of a claimed source without paying', async () => {
+ const dir = tmp('gbrain-6785-harvest-');
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const w = writeSegment(dir, 'sess-claimed', turnsText(2, 10));
+ appendSegmentLedger(dir, 'sess-claimed', w.hash);
+ const name = segmentFileName('sess-claimed', w.hash);
+ __resetCheckpointHarvestForTests();
+ const before = chatCalls;
+ expect(scheduleCheckpointHarvest({ engine, sourceId: 'claimed-example', sessionId: 'sess-claimed', corpusDir: dir, file: name, capabilities: KEYED }).status).toBe('scheduled');
+ await __drainCheckpointHarvestForTests();
+ expect(chatCalls).toBe(before);
+ expect(existsSync(join(dir, name) + HARVEST_RECEIPT_SUFFIX)).toBe(false);
+ expect(existsSync(join(dir, name) + CORPUS_INGESTED_SUFFIX)).toBe(false);
+ });
+ });
+
+ test('the HTTP drain logs the skip reasons and the writer hint once, and a thrown tick says why', async () => {
+ await sessionFile('claimed-example', 'sess-drain');
+ const lines: string[] = [];
+ const drain = armCorpusDrain(engine, { sourceId: 'claimed-example', env: {}, setIntervalFn: () => 0, clearIntervalFn: () => {}, log: (m: string) => lines.push(m) } as never)!;
+ const before = chatCalls;
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ await drain.tick();
+ await drain.tick();
+ });
+ drain.cancel();
+ expect(chatCalls).toBe(before);
+ const text = lines.join('\n');
+ expect(text).toContain('writer_coordinator_required');
+ expect(text).toContain('gbrain sources writer status claimed-example');
+ expect(lines.filter((l) => l.includes('gbrain sources writer status claimed-example')).length).toBe(1);
+
+ const failing: string[] = [];
+ const broken = armCorpusDrain(engine, { env: {}, setIntervalFn: () => 0, clearIntervalFn: () => {},
+ sweep: async () => { throw new Error('drain fixture failure'); }, log: (m: string) => failing.push(m) } as never)!;
+ await withEnv({ GBRAIN_HOME: home }, () => broken.tick());
+ broken.cancel();
+ expect(failing.join('\n')).toContain('drain fixture failure');
+ });
+});
+
+describe('#6785: a window that keeps failing after its model call is capped', () => {
+ let engine: PGLiteEngine;
+ let dir: string;
+ let home: string;
+ let chatCalls = 0;
+ let failing = true;
+ const logs: string[] = [];
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ home = tmp('gbrain-6785-cap-home-');
+ }, 120_000);
+
+ beforeEach(async () => {
+ dir = tmp('gbrain-6785-cap-');
+ await engine.setConfig('dream.synthesize.session_corpus_dir', dir);
+ failing = true;
+ __setChatTransportForTests(async (): Promise<ChatResult> => {
+ chatCalls++;
+ if (failing) throw new Error('fixture failure after the model call');
+ return { text: fact(null), blocks: [], stopReason: 'end', usage, model: 'anthropic:test-stub', providerId: 'anthropic' };
+ });
+ });
+
+ afterEach(() => {
+ __setChatTransportForTests(null);
+ });
+
+ afterAll(async () => {
+ resetGateway();
+ await engine.disconnect();
+ });
+
+ const at = async (nowMs: number): Promise<{ paid: boolean; report: SweepReport }> => {
+ const before = chatCalls;
+ const report = await withEnv({ GBRAIN_HOME: home }, () =>
+ runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED, budgetMs: 120_000, now: () => nowMs, log: (m) => logs.push(m) }));
+ return { paid: chatCalls > before, report };
+ };
+
+ /** Five failed attempts on the schedule: now, the next sweep, +10, +20, +40 minutes. */
+ async function capped(file: string, t0: number): Promise<void> {
+ writeFileSync(file, turnsText(2));
+ const attempts = [];
+ for (const m of [0, 0, 11, 32, 73]) attempts.push((await at(t0 + m * MIN)).paid);
+ expect(attempts).toEqual([true, true, true, true, true]);
+ expect(JSON.parse(readFileSync(file + '.failures.json', 'utf8')).count).toBe(5);
+ }
+
+ test('retried on the next sweep, then after 10, 20 and 40 minutes, then stopped; tail growth does not reset it', async () => {
+ const file = join(dir, 'failing-session.txt');
+ writeFileSync(file, turnsText(2));
+ const t0 = Date.UTC(2026, 9, 15, 12);
+ const attempts: boolean[] = [];
+ attempts.push((await at(t0)).paid); // 1
+ attempts.push((await at(t0)).paid); // 2: the next sweep retries at once
+ const waiting = await at(t0 + 1 * MIN); // backoff
+ attempts.push(waiting.paid);
+ expect(skipped(waiting.report, 'corpus_window_backoff')).toBe(1);
+ appendFileSync(file, `\n\n${turnsText(1, 2)}`); // the session grew
+ attempts.push((await at(t0 + 11 * MIN)).paid); // 3
+ attempts.push((await at(t0 + 12 * MIN)).paid); // backoff (20 minutes)
+ attempts.push((await at(t0 + 32 * MIN)).paid); // 4
+ attempts.push((await at(t0 + 73 * MIN)).paid); // 5
+ expect(attempts).toEqual([true, true, false, true, false, true, true]);
+
+ for (const later of [t0 + 200 * MIN, t0 + 2 * 1440 * MIN]) {
+ const r = await at(later);
+ expect(r.paid).toBe(false);
+ expect(skipped(r.report, 'corpus_window_dead_lettered')).toBe(1);
+ }
+ expect(existsSync(file + CORPUS_INGESTED_SUFFIX)).toBe(false);
+ expect(logs.join('\n')).toContain('gbrain sweep --retry-failed');
+ const record = JSON.parse(readFileSync(file + '.failures.json', 'utf8'));
+ expect(record.count).toBe(5);
+ expect(record.last_code).toBe('provider_error');
+ expect(JSON.stringify(record)).not.toContain('fixture failure after the model call');
+ });
+
+ test('one extraction-config change re-arms the capped window once; a second change does not', async () => {
+ const file = join(dir, 'failing-session.txt');
+ await capped(file, Date.UTC(2026, 9, 15, 12));
+ expect((await at(Date.UTC(2026, 9, 16, 12))).paid).toBe(false);
+ const t1 = Date.UTC(2026, 9, 20, 12);
+ await engine.setConfig('facts.extraction_model', 'anthropic:claude-haiku-4-5');
+ try {
+ const rearmed = [(await at(t1)).paid, (await at(t1)).paid, (await at(t1 + 11 * MIN)).paid, (await at(t1 + 32 * MIN)).paid, (await at(t1 + 73 * MIN)).paid];
+ expect(rearmed).toEqual([true, true, true, true, true]);
+ expect((await at(t1 + 300 * MIN)).paid).toBe(false);
+ await engine.setConfig('facts.extraction_model', 'anthropic:claude-sonnet-4-6');
+ const second = await at(t1 + 400 * MIN);
+ expect(second.paid).toBe(false);
+ expect(skipped(second.report, 'corpus_window_dead_lettered')).toBe(1);
+ expect(JSON.parse(readFileSync(file + '.failures.json', 'utf8')).rearmed).toBe(true);
+ } finally {
+ await engine.unsetConfig('facts.extraction_model');
+ }
+ });
+
+ test('doctor names the paid retry; the operator retry previews, then extracts the window and its facts land', async () => {
+ const file = join(dir, 'failing-session.txt');
+ await capped(file, Date.UTC(2026, 9, 15, 12));
+ const { buildMemoryWritebackCheck } = await import('../src/commands/doctor/checks/memory-writeback.ts');
+ const check = await withEnv({ GBRAIN_HOME: home }, () => buildMemoryWritebackCheck(engine));
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('gbrain sweep --retry-failed --apply');
+ const fix = (check as { fix?: { argv: string[]; consent: string[] } }).fix;
+ expect(fix?.argv).toEqual(['gbrain', 'sweep', '--retry-failed', '--apply']);
+ expect(fix?.consent).toEqual(['paid']);
+
+ const { runSweep } = await import('../src/commands/sweep.ts');
+ const out: string[] = [];
+ const log = console.log;
+ console.log = (...a: unknown[]) => { out.push(a.join(' ')); };
+ try {
+ await runSweep(engine, ['--retry-failed', '--json']);
+ expect(existsSync(file + '.failures.json')).toBe(true);
+ await runSweep(engine, ['--retry-failed', '--apply', '--json']);
+ } finally {
+ console.log = log;
+ }
+ const preview = JSON.parse(out[0]);
+ expect(preview.applied).toBe(false);
+ expect(preview.files).toEqual([expect.objectContaining({ file: 'failing-session.txt', attempts: 5, stopped: true })]);
+ expect(JSON.parse(out[1]).applied).toBe(true);
+ expect(existsSync(file + '.failures.json')).toBe(false);
+
+ failing = false;
+ const r = await at(Date.UTC(2026, 9, 25, 12));
+ expect(r.paid).toBe(true);
+ expect(r.report.corpusIngested).toBe(1);
+ expect(existsSync(file + CORPUS_INGESTED_SUFFIX)).toBe(true);
+ const facts = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts WHERE source = 'sweep:corpus'`);
+ expect(facts[0].n).toBeGreaterThan(0);
+ });
+
+ test('the cap is keyed to the window and the source incarnation, never to the error label', async () => {
+ const { corpusFailureGate, recordCorpusFailure } = await import('../src/core/context/corpus-windows.ts');
+ const full = join(dir, 'labels.txt');
+ let rec = await recordCorpusFailure(full, null, 'k@0', 'inc-a', 'f1', 1, Object.assign(new Error('a'), { code: 'writer_coordinator_required' }));
+ rec = await recordCorpusFailure(full, rec, 'k@0', 'inc-a', 'f1', 2, Object.assign(new Error('b'), { reason: 'provider_error' }));
+ rec = await recordCorpusFailure(full, rec, 'k@0', 'inc-a', 'f1', 3, new TypeError('c'));
+ expect([rec.count, rec.last_code]).toEqual([3, 'TypeError']);
+ expect((await recordCorpusFailure(full, rec, 'k@9', 'inc-a', 'f1', 4, new Error('d'))).count).toBe(1);
+ const record = { version: 1 as const, key: 'abc@0', source_incarnation: 'inc-a', count: 5, first_at: 0, last_at: 0, last_code: 'x', fingerprint: 'f1', rearmed: false };
+ expect(corpusFailureGate(record, 'abc@0', 'inc-a', 'f1', 1e12)).toBe('dead_lettered');
+ expect(corpusFailureGate(record, 'abc@0', 'inc-b', 'f1', 1e12)).toBe('run');
+ expect(corpusFailureGate(record, 'def@0', 'inc-a', 'f1', 1e12)).toBe('run');
+ expect(corpusFailureGate(record, 'abc@0', 'inc-a', 'f2', 1e12)).toBe('run');
+ expect(corpusFailureGate({ ...record, rearmed: true }, 'abc@0', 'inc-a', 'f2', 1e12)).toBe('dead_lettered');
+ expect(corpusFailureGate({ ...record, fingerprint: null }, 'abc@0', 'inc-a', 'f2', 1e12)).toBe('dead_lettered');
+ });
+});