Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(atoms): retry a failed managed atom batch automatically, hold it after 3 failures (#6325)
time-attacka2649d6f4345
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex b7c0846629..c664842f1a 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -16,4 +16,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; a budget stop that leaves stale chunks is never silent: `src/core/embed-budget-stop.ts` records `reason: 'time_budget'`, `remaining_stale` and `resume_command`, `runEmbed` prints the verdict on stdout and the CLI exits 11 (`BUDGET_STOP_EXIT_CODE`); an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). In `--stale`, a page whose guarded projection snapshot is unavailable when its turn comes (edited, tagged or unsealed after the readiness gate) counts its chunks as failures and is named in one end-of-run batch-summary sample (the first five slugs plus a count of the rest); a page whose source was archived mid-run is left to the archived-work report so it is counted once. Pinned by `test/embed-stale-unavailable-snapshot.serial.test.ts`. Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from `resolveEmbedConcurrency` in `src/core/embed-concurrency.ts` (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered). A chunkless page whose projection install loses to another installer (the resident rebuild) re-reads through `retryProjectionConflict` and embeds the sealed chunks it finds; a conflict that outlasts the retries is recorded as a `[page_projection_conflict]` failure sample with the envelope's next step (`test/embedding-recovery.serial.test.ts`). `--all` passes the sliding pool an `onError` handler: an error that escapes `embedOnePage` (its snapshot read runs before the page's own try) counts that page once on `result.failures` with an `Error embedding <slug>` stderr line, unless the run is already aborting when the error arrives (shutdown, not a failure); `test/embed-partial-failure-3037.serial.test.ts`. #6223: pages still blocked after bounded projection recovery no longer end `--stale` early; healthy chunks embed, the blocked pages' chunks count as failures, and one sample names them (not the mid-run "changed" summary) with `gbrain embed --stale --images` / `gbrain sync --full` for image and media pages.- `src/commands/doctor/checks/search-eval.ts` — search, model, and AI-config health checks. `checkSearchMode` (`search_mode`) reports the resolved mode and its `search.*` overrides; when the only override is an explicit `search.reranker.model` row equal to the mode bundle's own default (a row an init may have written on Voyage installs) it is called redundant with the precise `gbrain config unset search.reranker.model` — never a `--reset`, which would also wipe every other tuned search knob.+- `src/commands/doctor/checks/atom-holds.ts` — `extract_atoms_held_failed` (#6325, BRAIN, registered before `fence_integrity`). Lists `listHeldManagedAtoms` (`persistence/atom-maintenance.ts`): managed atom pages and transcripts held after `MAX_DETERMINISTIC_FAILURES` failed extractions of their current content (code `held_failed`) that no later run completed, each with its last request id, failure, `receipt_command` and `retry_command`. Warns with a paid `fix` (the reviewed `gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'` retry of the first item). Local doctor only; `run_doctor` does not include it. Tests: `test/managed-atoms-retry.test.ts`.- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike; a warn reads `readFenceAutoRepair` (details `auto_repair`): while a maintenance run is active and `fences.repair.enabled` is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's `then` is the apply. Model-tier fences say why they wait (`fences.repair.llm` off with the command that turns it on, or today's budget spent with the cap command), else the caps. `fenceIntegrityCheck(engine, sourceIds?)` is the `WAVE_CHECKS` entry (scoped for a remote caller). Location only. #6278: the check also counts `unrenderable_legacy_facts`: the active `row_num IS NULL` fact rows the fence step leaves unadopted because the fence codec would change their text (or their page already carries the claim), planned read-only per source within the census time budget (`planUnfencedFacts` + `auditUnadoptableFacts`) and listed by page, fact id and reason class, never the claim text. They stay active and searchable, so the finding says nothing is lost, never suggests `forget_fact`, and when it is the only finding its fix carries no command (`next: report`) with the doctor re-count as verify; an incomplete scan asks for a rerun. Test: `test/doctor-fence-integrity.test.ts`.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 75e28e05dd..38686bf42d 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/extract-atoms-drain.ts` — pure single-hold bounded drain for the silent lens-phase backlog. `runExtractAtomsDrain(deps, opts)` over injected deps (`withLock`, `runBatch`, `countRemaining`, `now`, optional `onBatch`) loops bounded batches under ONE lock hold, rediscovering eligibility each batch (idempotent NOT-EXISTS-on-`source_hash`; no cross-window cursor), until the backlog is empty or the window ends. Two stop signals: HARD (job `signal` + the lock's lease-loss signal + `deadlineAtMs`) reaches the chat call, the pacing pause and every backlog count; SOFT (hard + the window timer) is checked only between batches and items, so the item in flight finishes. Counts are cancellable and bounded (`countTimeoutMs`, capped by the remaining deadline). `stopped` is a `DrainStop` (`drained|window|deadline|lock_lost|aborted|no_progress|max_batches|provider_failure`); a hard stop skips `onBatch` and the recount and reports the last count as `remaining`, and the lease loss `withRefreshingLock` rethrows becomes `lock_lost` with the partial counters. Backs `gbrain dream --phase extract_atoms --drain` under the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent tick defers with `cycle_already_running`). `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?, signal?, deadlineAtMs?})` owns the lock+batch+count wiring for all three callers — `dream --drain`, the `extract-atoms-drain` Minion handler, autopilot auto-drain. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'`; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates. One `runExtractAtomsDrainForSource` call is one drain attempt: its batches share one `BudgetTracker` (the per-run `cycle.extract_atoms.budget_usd` cap is the attempt's cap) and one `MaintenanceWriteWait` (`persistence/maintenance-wait.ts`, bounded by `deadlineAtMs`). `structuralAtomRefusal` maps an `owner_unavailable`/`permission_denied` refusal from the atom session preflight to `STRUCTURAL_REFUSAL_PREFIX` text; the `extract-atoms-drain` Minion handler (`src/core/minions/handlers/extract-atoms-drain.ts`) throws it as `UnrecoverableError`, so the job dead-letters once with no model call and the auto-drain cap does not count it. `last_error` and the typed failure records pass through `sanitizeFailureText` (secret/DSN redaction, bounded). `formatDrainProviderFailure(result, {final?})` renders the handler's `provider_failure` throw; the handler throws `UnrecoverableError` on `deadline` or any failure at/past `deadlineAtMs`, the job's abort reason on `aborted`, and a retryable error on `lock_lost`. Tests: `test/extract-atoms-drain*.test.ts`.-- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Transcript input is paste-stripped before the cut (#5812); discovery skips self-captures (#5820). Discovery and the backlog count append `connectorAtomExclusionSql` (`connector-atoms.ts`), so connector `email`/`meeting` pages stay out only when `cycle.extract_atoms.connector_pages` is false. A drain attempt passes `opts.attempt` (`budgetTracker`, `writeWait`) so its batches share one budget and one maintenance publish wait. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. A page-derived atom upserts at its locator-folded slug, else a compatible legacy title-only slug; when both miss, the source page's live bound atoms are loaded once per page per run and exactly one JS-lowercased title match is adopted (a case-only title change never mints a duplicate; zero or several matches mint the new slug). Response parsing lives in `extract-atoms-parse.ts`. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. After an unmanaged item completes, `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce. Hard `opts.signal` (chat call, pacing, checks before each item and commit) leaves no strike, receipt or rollup; soft `opts.stopSignal` stops before the next item.+- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Transcript input is paste-stripped before the cut (#5812); discovery skips self-captures (#5820). Discovery and the backlog count append `connectorAtomExclusionSql` (`connector-atoms.ts`), so connector `email`/`meeting` pages stay out only when `cycle.extract_atoms.connector_pages` is false. A drain attempt passes `opts.attempt` (`budgetTracker`, `writeWait`) so its batches share one budget and one maintenance publish wait. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. A failed managed batch is retried by the next run instead (#6325, `resumeManagedAtoms` in `persistence/atom-maintenance.ts`); an origin held after `MAX_DETERMINISTIC_FAILURES` (now defined in `extract-atoms-page-state.ts`, re-exported here) is skipped with no model call and counted in `details.held_failed`, never in `failures`. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. A page-derived atom upserts at its locator-folded slug, else a compatible legacy title-only slug; when both miss, the source page's live bound atoms are loaded once per page per run and exactly one JS-lowercased title match is adopted (a case-only title change never mints a duplicate; zero or several matches mint the new slug). Response parsing lives in `extract-atoms-parse.ts`. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. After an unmanaged item completes, `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce. Hard `opts.signal` (chat call, pacing, checks before each item and commit) leaves no strike, receipt or rollup; soft `opts.stopSignal` stops before the next item.Managed completion admits revision-pinned `managed_atom_delete` children alongside replacement pages, removes canonical files through the page deletion path, and commits its checkpoint only after every publication and retirement commits.Both paths prevent LLM-chosen titles that drift between extractions from piling up.Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (keyed `(source_id, file_path, content_hash)`, 16-char hash prefix, so an edit is a new row): `recordItemFailureCount` counts a transcript's malformed output or prompt-level provider block (`providerContentBlockReason`; never feeds the outage halt) toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (as pages do), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex cf40cdac99..4f7b837a32 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -16,7 +16,7 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast- `src/core/persistence/onboarding.ts` + `legacy-locks.ts` + `physical-root-recovery.ts` — read-only source onboarding states; exact same-host dead-lock cleanup under explicit activation opt-in; and state-bound same-owner root repair using a durable manifest and token-verified temporary stamp. `physical-root.ts` `restampPhysicalRoot` handles a filesystem device id that changed while the owner token, brain, worktree, root, inode and a non-zero birth time still match (macOS can renumber `st_dev` across reboots): under the caller's outside-root native lock, one transaction verifies owner host, brain and host binding and rewrites the recorded self-transfer copies and retained topology staging identities (each only while it still names the old device); after commit the stamp and the reservation's initial device are rewritten and the event is logged, so an interruption between the two leaves a device-only change the next locked acquisition finishes. Ownership markers inside a retained topology clone stage are not re-stamped; an interrupted clone recovery that spans a device renumbering still needs source recovery. `assertPhysicalRoot` stays read-only; zero birth time or any other difference keeps the refusal. `--self-transfer` prepare/accept requires separate fresh reviewed state, preserves original reservation owner evidence and refuses uncertain records. Tests: `test/persistence-onboarding.test.ts`, `test/persistence-admin-recovery.test.ts`, `test/persistence-container-preflight.test.ts`.-- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. A failed atom batch's resume refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify.+- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`.- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.Atom completion admits replacement and revision-pinned stale-atom deletion children together.Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex ca5d2252f8..b4e7579ef0 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -918,7 +918,7 @@ More: [docs/guides/move-to-postgres.md#graduated-datastore](../../docs/guides/mo| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| The accepted atom extraction failed (malformed output, or a response stopped before the end); a new attempt needs approval. | A failed managed atom batch is recorded as a failure receipt instead of being retried automatically, so the same input is not paid for every cycle. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |+| The accepted atom extraction failed (malformed output, or a response stopped before the end); a new attempt needs approval. | The drain retries a failed managed atom batch on its own up to 3 times per content (then holds it, code held_failed); this code reports a failed explicit retry, or a failure the drain cannot attribute to a checkpoint, so the same input is not paid for again without approval. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |### extractor_identity_mismatch@@ -1334,6 +1334,14 @@ More: [docs/guides/bootstrap.md#harness_hook_duplicates](../../docs/guides/bootsMore: [docs/guides/bootstrap.md#harness_hook_unowned](../../docs/guides/bootstrap.md#harness_hook_unowned)+### held_failed++<a id="held_failed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A managed atom origin (a page or transcript) failed atom extraction 3 times on the same content, so the drain stopped retrying it; doctor `extract_atoms_held_failed` lists it with its last request id. | Every automatic attempt is a paid model call. After MAX_DETERMINISTIC_FAILURES completed failures of one content the origin leaves the atom backlog instead of being paid for every cycle; editing the content starts a new count, and an explicit retry runs it again. | A required capability is not available on this brain. Run `gbrain doctor --json` to see what is missing. Run: gbrain doctor --only extract_atoms_held_failed --json | agent | `gbrain doctor --json` | 1 | no |+### held_out_overlaps_benchmark<a id="held_out_overlaps_benchmark"></a>diff --git a/src/commands/doctor/checks/atom-holds.ts b/src/commands/doctor/checks/atom-holds.tsnew file mode 100644index 0000000000..fec8d4ab73--- /dev/null+++ b/src/commands/doctor/checks/atom-holds.ts@@ -0,0 +1,42 @@+/**+ * extract_atoms_held_failed (#6325): managed atom origins the drain stopped+ * retrying after MAX_DETERMINISTIC_FAILURES failed extractions of the same+ * content (code `held_failed`). A held origin leaves the atom backlog, so this+ * is the surface that keeps it from being skipped silently: each row names its+ * last request id and the reviewed retry command. Reads the database only.+ */+import type { Check } from '../../doctor.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { listHeldManagedAtoms } from '../../../core/persistence/atom-maintenance.ts';+import { shellQuote } from '../../../core/agent-output.ts';+import { checkError, doctorVerify } from '../check-fix.ts';++const retryArgv = (sourceId: string, requestId: string): string[] =>+ ['gbrain', 'jobs', 'submit', 'extract-atoms-drain', '--params', JSON.stringify({ sourceId, retryRequestId: requestId })];++async function runAtomHeldFailedCheck(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ try {+ const held = await listHeldManagedAtoms(connectedEngine(ctx));+ const items = held.map(item => ({ ...item, receipt_command: `gbrain write-request -- ${item.request_id}`,+ retry_command: shellQuote(retryArgv(item.source_id, item.request_id)) }));+ const details = { held: items.length, items, code: 'held_failed' };+ if (!items.length) {+ checks.push({ name: 'extract_atoms_held_failed', status: 'ok', message: 'No managed atom page or transcript is held after repeated extraction failures.', details });+ return checks;+ }+ const first = items[0]!;+ checks.push({ name: 'extract_atoms_held_failed', status: 'warn', details,+ message: `${items.length} managed atom origin(s) held after ${first.attempts} failed extraction attempts on the same content (held_failed): `+ + `${items.slice(0, 5).map(item => `${item.source_id}:${item.locator} (request ${item.request_id}: ${item.failure})`).join('; ')}${items.length > 5 ? `; and ${items.length - 5} more` : ''}. `+ + 'They are out of the atom backlog until their content changes or an explicit retry runs.',+ fix: { argv: retryArgv(first.source_id, first.request_id), consent: ['paid'], actor: 'agent', requires_exclusive: false,+ why: `Queues one reviewed paid retry of the held atom batch ${first.request_id} (${first.source_id}:${first.locator}); read its receipt first with gbrain write-request -- ${first.request_id}. Repeat per held item in details.items.`,+ verify: doctorVerify('extract_atoms_held_failed') } });+ } catch (error) {+ checks.push(checkError('extract_atoms_held_failed', 'list held managed atom origins', error, { details: { health: 'unknown' } }));+ }+ return checks;+}++export const atomHeldFailedEntry: DoctorEntry = { name: 'extract_atoms_held_failed', emits: ['extract_atoms_held_failed'], run: runAtomHeldFailedCheck };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 49d1241b5c..5e11eab6bb 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -106,6 +106,7 @@ import { chatFallbackChainEntry } from './checks/chat-fallback.ts';import { behaviorChangesEntry } from './checks/behavior-changes.ts';import { fenceIntegrityEntry } from './checks/fence-integrity.ts';import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';+import { atomHeldFailedEntry } from './checks/atom-holds.ts';import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';import type { Check } from '../doctor.ts';import { infoCheck } from './check-fix.ts';@@ -188,6 +189,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [coreMemoryEntry,managedSyncMovementEntry,persistenceConsumersEntry,+ atomHeldFailedEntry,fenceIntegrityEntry,searchModeEntry,];diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex cc7e173470..0a54256cbf 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -375,6 +375,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.151.0', text: '`delta` and `context_pack` called without `include_private`, and the per-turn context block that harness hooks inject, now apply to their facts the same page-visibility rule they already apply to their pages. With `include_private` from the local CLI, `delta` and `context_pack` output is unchanged.' },// Fix wave 13 PR3 (GBRA-57). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.152.0', text: 'The dream cycle now reads a schema pack set with `gbrain config set schema_pack` (or `schema_pack.source.<id>`) when it decides whether to run extract_atoms and synthesize_concepts, as `gbrain schema active` already did. A paid phase that only such a database-config pack declares, and that did not run before, is skipped with `consent_required` until you run `gbrain config set cycle.extract_atoms.enabled true` (or `cycle.synthesize_concepts.enabled true`); doctor `extract_atoms_backlog` names the same command.' },+ { since: '0.60.152.0', text: 'On a managed brain, a page or transcript whose atom extraction failed (malformed or cut-off model output) is now retried by the next drain or cycle, inside its per-run budget, up to 3 attempts per content; it was replayed as a failure with no model call and could stop the drain with `provider_failure`. After the third failure it is held (`held_failed`): out of the atom backlog until its content changes, and doctor `extract_atoms_held_failed` lists it with the paid retry command.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/extract-atoms-page-state.ts b/src/core/cycle/extract-atoms-page-state.tsindex 9bbc88af9c..acb86f3f5e 100644--- a/src/core/cycle/extract-atoms-page-state.ts+++ b/src/core/cycle/extract-atoms-page-state.ts@@ -4,6 +4,14 @@ import { stableJson } from '../persistence/digest.ts';import type { BrainEngine } from '../engine.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';+/**+ * gbrain#4148: consecutive same-content failures of a content-deterministic+ * class (malformed model output or provider content block) before the page is tombstoned so the+ * backlog floor can clear. A content edit resets the streak. #6325: a managed+ * page or transcript settles held_failed at the same bound.+ */+export const MAX_DETERMINISTIC_FAILURES = 3;+export interface AtomPageIdentity {pageId: number;sourceIncarnation: string;diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex cf60eca019..f0c55192ea 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -92,7 +92,7 @@ import { effectiveVisibility } from '../search/private-visibility.ts';import { OperationError } from '../ops/contract.ts';import type { WriteReceipt } from '../persistence/types.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';-import { AtomPageStateError, completeAtomReceipts, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';+import { AtomPageStateError, completeAtomReceipts, MAX_DETERMINISTIC_FAILURES, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import { deriveTrust, lowerDerivedPage } from '../trust/taint.ts';import { derivedGateInput } from '../trust/derived-gate.ts';@@ -108,12 +108,7 @@ const DEFAULT_BUDGET_USD = 0.3;export const DEFAULT_EXTRACT_MAX_INPUT_CHARS = 50_000;export const DEFAULT_EXTRACT_MAX_OUTPUT_TOKENS = 4096;-/**- * gbrain#4148: consecutive same-content failures of a content-deterministic- * class (malformed model output or provider content block) before the page is tombstoned so the- * backlog floor can clear. A content edit resets the streak.- */-export const MAX_DETERMINISTIC_FAILURES = 3;+export { MAX_DETERMINISTIC_FAILURES };/*** Transient provider/infra failure shapes — retryable, never counted.@@ -1000,6 +995,7 @@ export async function runPhaseExtractAtoms(// say are "retryable, never counted" — see that regex's doc comment.let hardFailureCount = 0;let writesPending = 0; // #5601: accepted atom batches still publishing (progress, not failures)+ let heldFailed = 0;async function stampAtomsScanHash(item: AtomPageInput): Promise<void> {await writeAtomPageState(engine, sourceId, item, 'complete');@@ -1114,10 +1110,10 @@ export async function runPhaseExtractAtoms(const visibility = origin?.visibility ?? effectiveVisibility(item.kind === 'transcript' ? { kind: 'transcript' } // #5525: { kind: 'page', page: await engine.getPage(item.slug, { sourceId }) });throwIfAborted(opts.signal, 'extract_atoms');- if (!opts.dryRun && managed && origin && await resumeManagedAtoms(engine, managed, origin)) {- duplicatesSkipped++;- continue;- }+ const resumed = !opts.dryRun && managed && origin ? await resumeManagedAtoms(engine, managed, origin) : 'run';+ if (resumed === 'done') { duplicatesSkipped++; continue; }+ if (resumed === 'held') { heldFailed++; continue; } // #6325: settled after repeated failures; doctor lists it+const result = await chat({model: extractModel,...atomsPrompt(dateGrounding, originLabel, promptContent),@@ -1457,6 +1453,7 @@ export async function runPhaseExtractAtoms(pages_skipped_budget: pagesSkipped,duplicates_skipped: duplicatesSkipped,write_pending: writesPending,+ held_failed: heldFailed,failures,...(managed ? { write_requests: writeRequests } : {}),...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex e0bb1c687a..d32f16db29 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -114,6 +114,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['entity_link_coverage','eval_drift','extract_atoms_backlog',+ // #6325: managed atom origins held after repeated extraction failures.+ 'extract_atoms_held_failed','extract_health','facts_embedding_width_consistency','facts_extraction_health',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 971ee9a630..b1a5235edc 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -172,7 +172,7 @@ export const CODES = {engine_graduated: { class: 'caller', summary: "A client opened a PGLite brain that moved to Postgres; its old path holds a tombstone.", docs: 'docs/guides/move-to-postgres.md#graduated-datastore' },eval_suite_unwired: { class: 'caller', summary: "`gbrain eval run-all` was asked for a suite it does not run in-process (longmemeval or replay); nothing ran.", why: "run-all runs only wired suites (brainbench). Recording a skipped run and exiting 0 would read as a completed sweep with no numbers behind it.", suggestion: 'Run each requested suite with its own command (`gbrain eval longmemeval <dataset.jsonl> --mode <mode> --record`, `gbrain eval replay --mode <mode>`), once per mode, or drop it from --suites.' },export_limit: { class: 'caller', summary: "This migration is bounded to 5,000 active pages per source; split or use a reviewed bulk export." },- extraction_failed: { class: 'server', summary: "The accepted atom extraction failed (malformed output, or a response stopped before the end); a new attempt needs approval.", why: "A failed managed atom batch is recorded as a failure receipt instead of being retried automatically, so the same input is not paid for every cycle." },+ extraction_failed: { class: 'server', summary: "The accepted atom extraction failed (malformed output, or a response stopped before the end); a new attempt needs approval.", why: "The drain retries a failed managed atom batch on its own up to 3 times per content (then holds it, code held_failed); this code reports a failed explicit retry, or a failure the drain cannot attribute to a checkpoint, so the same input is not paid for again without approval." },extractor_identity_mismatch: { class: 'server', summary: "The approved extractor differs from the installed extractor; this receipt cannot resume or admit another revision." },fact_already_expired: { class: 'caller', summary: "The fact had already expired before this write." },fence_unrenderable: { class: 'server', summary: "A legacy fact row was not adopted into its page's facts fence because the fence codec reads the rendered row back as something other than the stored fact.", why: "The fence trims a claim, folds CRLF to LF, reads `~~x~~` as a struck row and `<br>` as a line break; a claim the codec would change by more than whitespace cannot be written into the fence without changing what it says, so the row stays a legacy row (active and searchable, nothing is lost) and is counted by doctor fence_integrity as unrenderable_legacy_facts. The same code names a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input.", docs: 'docs/guides/write-refusals.md#fence_unrenderable', suggestion: 'Nothing to fix in the page: the rows stay active and searchable. Report the page slug and the reason class with the gbrain version; do not forget or expire a row to clear this count.', fix: { argv: ['gbrain', 'doctor', '--only', 'fence_integrity', '--json'], consent: [], actor: 'agent', why: 'Lists the pages whose legacy fact rows cannot be adopted into their fence and why (by fact id and reason class, never the claim text), read-only.', requires_exclusive: false } },@@ -217,6 +217,7 @@ export const CODES = {host_identity_mismatch: { class: 'host_only', summary: "This process's `host.json` identity differs from the identity that owns the binding although both resolve on this machine, so writes that need the owner read it as another host.", why: "Host identity is a file under the persistence home: a job worker or container launched with a different `HOME` or `GBRAIN_HOME` mints a new `host.json` and sees the binding as another host's (`owner_unavailable`, `host_mismatch`), so its maintenance writes never reach the owner. The check names both files and the environment each was minted under (`minted_under`, `unknown` for a file minted before it was recorded); re-deriving the identity would re-own every existing binding, so the fix is the environment, never the file.", docs: 'docs/guides/troubleshooting.md#host-identity-mismatch', suggestion: 'Set GBRAIN_HOME on the supervisor of the process to the owner\'s home (the value the check prints; config appends .gbrain itself) and restart it; never edit or delete a host.json.', fix: { argv: ['gbrain', 'doctor', '--only', 'host_identity_mismatch', '--json'], consent: [], actor: 'host_admin', why: 'Read-only: names both host.json paths, the HOME and GBRAIN_HOME each was minted under and the GBRAIN_HOME value to set.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'host_identity_mismatch', '--json'] } } },harness_hook_duplicates: { class: 'caller', summary: "A harness hook carrier wires one Claude Code event more than once with this install's own entries (marked or not), so the hook fires twice per event.", why: "Claude Code can drop the `_gbrain` marker when it rewrites settings.json; installs before wave 11 then appended a second set on every re-run.", docs: 'docs/guides/bootstrap.md#harness_hook_duplicates', fix: { argv: ['gbrain', 'doctor', '--only', 'bootstrap_harness_health', '--json'], consent: [], actor: 'agent', why: "Names the carrier, the duplicated events and the re-run (with the install's own flags) that converges them, read-only.", requires_exclusive: false } },harness_hook_unowned: { class: 'caller', summary: "A hook entry looks like gbrain's harness hook but is not this install's exact command, so gbrain left it in place.", why: "An unmarked entry is deleted only when its command is exactly what this install (or its receipt) wrote; an edited command or another install's launcher is never removed, and removal is not reported complete while it remains.", docs: 'docs/guides/bootstrap.md#harness_hook_unowned', fix: { argv: ['gbrain', 'bootstrap', 'harness', '--status'], consent: [], actor: 'agent', why: 'Shows each hook carrier with the events holding entries that are not this install\'s, read-only.', requires_exclusive: false } },+ held_failed: { class: 'unavailable', summary: "A managed atom origin (a page or transcript) failed atom extraction 3 times on the same content, so the drain stopped retrying it; doctor `extract_atoms_held_failed` lists it with its last request id.", why: "Every automatic attempt is a paid model call. After MAX_DETERMINISTIC_FAILURES completed failures of one content the origin leaves the atom backlog instead of being paid for every cycle; editing the content starts a new count, and an explicit retry runs it again.", fix: { argv: ['gbrain', 'doctor', '--only', 'extract_atoms_held_failed', '--json'], consent: [], actor: 'agent', why: 'Lists the held atom origins with their last request id, failure and retry command, read-only.', requires_exclusive: false } },held_out_overlaps_benchmark: { class: 'caller', summary: "Held out overlaps benchmark." },held_out_required_for_bundled: { class: 'caller', summary: "Held out required for bundled." },idempotency_conflict: { class: 'caller', summary: "The request_id already belongs to a different accepted operation." },diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.tsindex cb7239a87f..1bab21c16e 100644--- a/src/core/persistence/atom-maintenance.ts+++ b/src/core/persistence/atom-maintenance.ts@@ -19,7 +19,7 @@ import { MaintenanceWriteWait } from './maintenance-wait.ts';import type { PreparedMutation } from './coordinator.ts';import type { WriteAuthority, WriteRequest } from './model.ts';import type { WriteReceipt } from './types.ts';-import { writeAtomPageState } from '../cycle/extract-atoms-page-state.ts';+import { MAX_DETERMINISTIC_FAILURES, writeAtomPageState } from '../cycle/extract-atoms-page-state.ts';import { effectiveVisibility } from '../search/private-visibility.ts';import { declareDerivation, deriveTrust, lowerToDerivedTier, recordTaintEdges } from '../trust/taint.ts';@@ -41,8 +41,15 @@ export interface ManagedAtomSession {config: GBrainConfig;/** #5854: the publish wait of the job this session runs in (a drain attempt shares one across its batches). */wait: MaintenanceWriteWait;- retry?: { runKey: string; checkpointKey: string; expectedCheckpoint: unknown; rows: WriteRequest[]; origin: AtomOrigin };+ retry?: AtomClaim & { checkpointKey: string; rows: WriteRequest[]; origin: AtomOrigin };+ /** #6325: the automatic attempt each failed drain key resumes under, claimed against that key's failed checkpoint. */+ attempts?: Map<string, AtomClaim>;}+/** The run key a batch is admitted under and, for a retry, the checkpoint it advances (compare-and-set). */+interface AtomClaim { runKey: string; checkpointKey?: string; expectedCheckpoint?: unknown }+/** One `managed-atoms` checkpoint row. `attempts` counts completed failures of its content; `held` marks the bound. */+interface AtomCheckpoint { requestId?: string; failure?: string; attempts?: number; held?: boolean }+export type AtomResume = 'run' | 'done' | 'held';export interface AtomIntent extends Record<string, unknown> {kind: 'managed_atom_page' | 'managed_atom_delete' | 'managed_atom_complete';runKey: string;@@ -246,13 +253,18 @@ export function atomRetryInputKey(session: ManagedAtomSession, origin: AtomOrigireturn digest([digest(atomInput(session, origin)), origin.textHash]);}-function runKey(session: ManagedAtomSession, origin: AtomOrigin): string {+function atomClaim(session: ManagedAtomSession, origin: AtomOrigin): AtomClaim {if (session.retry) {if (atomRetryInputKey(session, session.retry.origin) !== atomRetryInputKey(session, origin)) throw opError('source_changed', 'The atom retry input no longer matches its accepted source snapshot.',`${origin.kind === 'page' ? `Page ${origin.locator}` : 'The transcript'} in source ${session.sourceId} changed after the reviewed atom batch was accepted, so the retry cannot replay it. Nothing was retried; the regular drain extracts the current content as a new run.`,{ fix: drainFix(session.sourceId) });- return session.retry.runKey;+ return session.retry;}+ const key = drainKey(session, origin);+ return session.attempts?.get(key) ?? { runKey: key };+}++function drainKey(session: ManagedAtomSession, origin: AtomOrigin): string {// A database-only connector run is its own run: once an owner claims the source, the owner's// run extracts again instead of replaying the batch the claim refused (claiming keeps the incarnation).const key = atomInputKey(session, origin);@@ -294,7 +306,7 @@ function malformedAtomReceipt(row: WriteRequest): never {const params = JSON.stringify({ sourceId: row.source_id, retryRequestId: row.request_id });const error = new OperationError('extraction_failed', `The accepted atom extraction failed${typeof failure === 'string' && failure ? ` (${failure})` : ''}; a new attempt needs approval.`,`Approve one new attempt with gbrain jobs submit extract-atoms-drain --params '${params}'.`);- error.why = 'A failed managed atom batch keeps its failure receipt instead of retrying on its own, so the same input is not paid for every cycle; the earlier atoms of the page stay as they were.';+ error.why = 'This failed managed atom batch is not retried on its own (an explicit retry failed, or the drain has no checkpoint to count it against), so the same input is not paid for again without approval; the earlier atoms of the page stay as they were.';error.fix = { argv: ['gbrain', 'jobs', 'submit', 'extract-atoms-drain', '--params', params], consent: ['paid'], actor: 'agent', requires_exclusive: false,why: 'Runs one new paid extraction attempt for this batch; ask the user before spending.',verify: { argv: ['gbrain', 'write-request', '--', row.request_id] } };@@ -303,30 +315,63 @@ function malformedAtomReceipt(row: WriteRequest): never {throw error;}-export async function resumeManagedAtoms(engine: BrainEngine, session: ManagedAtomSession, origin: AtomOrigin): Promise<boolean> {- const key = runKey(session, origin);- const [checkpoint] = await engine.executeRaw<{ completed_keys: Array<{ failure?: string; requestId?: string }> }>(+async function readAtomCheckpoint(engine: BrainEngine, key: string): Promise<AtomCheckpoint[] | null> {+ const [checkpoint] = await engine.executeRaw<{ completed_keys: AtomCheckpoint[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-atoms' AND fingerprint=$1", [key]);- if (checkpoint) {- if (!checkpoint.completed_keys[0]?.failure) return true;- const requestId = checkpoint.completed_keys[0]?.requestId;- if (requestId) {- const failed = await getWriteRequest(engine, session.authority.principal, requestId);+ return checkpoint?.completed_keys ?? null;+}++/**+ * Whether an origin's atoms are done, held, or need a model run, after waiting out any accepted batch.+ * #6325: the drain does not replay a failed batch's receipt. It resumes the next automatic attempt, whose+ * run key is fixed by the failed checkpoint (one stable id per failure, so a crashed attempt resumes and two+ * runs admit the same requests); its completion advances the failed checkpoint by compare-and-set. After+ * MAX_DETERMINISTIC_FAILURES completed failures of one content the checkpoint is `held`, and only an+ * explicit retry runs it again.+ */+export async function resumeManagedAtoms(engine: BrainEngine, session: ManagedAtomSession, origin: AtomOrigin): Promise<AtomResume> {+ if (session.retry) {+ const key = atomClaim(session, origin).runKey;+ const checkpoint = (await readAtomCheckpoint(engine, key))?.[0];+ if (checkpoint && !checkpoint.failure) return 'done';+ if (checkpoint?.requestId) {+ const failed = await getWriteRequest(engine, session.authority.principal, checkpoint.requestId);if (failed) { await authorizeStoredRequest(engine, failed); malformedAtomReceipt(failed); }}+ const resumed = await resumeAtomBatch(engine, session, key);+ return typeof resumed === 'string' ? resumed : malformedAtomReceipt(resumed);+ }+ const key = drainKey(session, origin);+ let failed: { row: WriteRequest; checkpoint: string } | null = null;+ for (;;) {+ const checkpoint = await readAtomCheckpoint(engine, key);+ const state = JSON.stringify(checkpoint);+ // A batch that completed failed without moving the checkpoint (it was purged) is reported, not looped on.+ if (failed && failed.checkpoint === state) malformedAtomReceipt(failed.row);+ const head = checkpoint?.[0];+ if (checkpoint && !head?.failure) return 'done';+ if (head?.held) return 'held';+ if (checkpoint) (session.attempts ??= new Map()).set(key, { runKey: digest([key, head?.requestId ?? null, 'automatic']), checkpointKey: key, expectedCheckpoint: checkpoint });+ const resumed = await resumeAtomBatch(engine, session, atomClaim(session, origin).runKey);+ if (typeof resumed === 'string') return resumed;+ failed = { row: resumed, checkpoint: state };}+}++/** Waits out the batch accepted under `key`: 'run' when there is none, 'done' when it completed, or its failed completion row. */+async function resumeAtomBatch(engine: BrainEngine, session: ManagedAtomSession, key: string): Promise<'run' | 'done' | WriteRequest> {const rows = await atomBatchRows(engine, session, key);- if (!rows.length) return false;+ if (!rows.length) return 'run';for (const row of rows) {await authorizeStoredRequest(engine, row);const completed = session.wait.observe(await waitForWrite(engine, row, session.config, session.wait.ms()));writeResponse(completed);- if (completed.outcome?.failure) malformedAtomReceipt(completed);+ if (completed.outcome?.failure) return completed;}if (!rows.some(row => row.request_id === atomRequestId(key, '__managed_atom_complete__'))) throw opError('storage_error', 'The accepted atom batch has no completion receipt.',`Source ${session.sourceId}'s atom pages were accepted but the batch's completion was never journaled, so its outcome is unconfirmed. Inspect the accepted request ${rows[0].request_id} and the owner before resubmitting anything.`,{ fix: receiptFix(rows[0].request_id) });- return true;+ return 'done';}export interface ManagedAtomRetirement {@@ -338,7 +383,9 @@ export interface ManagedAtomRetirement {export async function publishManagedAtoms(engine: BrainEngine, session: ManagedAtomSession, origin: AtomOrigin,atoms: Array<{ slug: string; content: string; links: LinkBatchInput[]; expectedTarget?: { pageId: number | null; revision: string | null } }>,failure?: string, reviewedRetirements?: ManagedAtomRetirement[]): Promise<WriteReceipt[]> {- const key = runKey(session, origin);+ const claim = atomClaim(session, origin);+ const key = claim.runKey;+ const advance = claim.checkpointKey ? { checkpointKey: claim.checkpointKey, expectedCheckpoint: claim.expectedCheckpoint ?? null } : {};const inputs: Array<{ slug: string; pageId: number | null; intent: AtomIntent }> = [];for (const atom of atoms) {await authorizeWrite(engine, session.authority, 'put_page', atom.slug);@@ -356,7 +403,7 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA{ fix: pageFix(session.sourceId, atom.slug) });}inputs.push({ slug: atom.slug, pageId: target.pageId, intent: { kind: 'managed_atom_page', runKey: key, origin,- ...(session.retry ? { checkpointKey: session.retry.checkpointKey, expectedCheckpoint: session.retry.expectedCheckpoint } : {}),+ ...advance,...(target.revision ? { expected_revision: target.revision } : {}), content: atom.content, links: atom.links } as AtomIntent });}const originKey = origin.kind === 'page' ? 'source_slug' : 'source_path';@@ -373,16 +420,14 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedAfor (const retirement of retirements) {await authorizeWrite(engine, session.authority, 'delete_page', retirement.slug);inputs.push({ slug: retirement.slug, pageId: retirement.pageId, intent: {- kind: 'managed_atom_delete', runKey: key, origin, expected_revision: retirement.revision,- ...(session.retry ? { checkpointKey: session.retry.checkpointKey, expectedCheckpoint: session.retry.expectedCheckpoint } : {}),+ kind: 'managed_atom_delete', runKey: key, origin, expected_revision: retirement.revision, ...advance,} as AtomIntent });}const rows = await engine.transaction(async tx => {const children: string[] = [];const accepted: WriteRequest[] = [];for (const input of [...inputs, { slug: '__managed_atom_complete__', pageId: null,- intent: { kind: 'managed_atom_complete', runKey: key, origin, children, ...(failure ? { failure } : {}),- ...(session.retry ? { checkpointKey: session.retry.checkpointKey, expectedCheckpoint: session.retry.expectedCheckpoint } : {}) } as AtomIntent }]) {+ intent: { kind: 'managed_atom_complete', runKey: key, origin, children, ...(failure ? { failure } : {}), ...advance } as AtomIntent }]) {const requestId = atomRequestId(key, input.slug);const row = await admitWriteInTransaction(tx, { principal: session.authority.principal, authority: session.authority,operation: 'submit_job', sourceId: session.sourceId, sourceIncarnation: session.incarnation,@@ -485,8 +530,12 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: WritecontentHash: p.origin.contentHash, identity: { pageId: p.origin.pageId!, sourceIncarnation: row.source_incarnation,revision: p.origin.revision! } }, p.failure ? 'failure' : 'complete');}+ // #6325: one strike per completed failure of this content, counted on the checkpoint it advances.+ const prior = Array.isArray(p.expectedCheckpoint) ? p.expectedCheckpoint[0] as AtomCheckpoint | undefined : undefined;+ const attempts = (prior?.failure ? Number(prior.attempts ?? 1) : 0) + 1;const checkpoint = JSON.stringify([{ sourceId: row.source_id, incarnation: row.source_incarnation, requestId: row.request_id,- kind: p.origin.kind, locator: p.origin.locator, pageId: p.origin.pageId, contentHash: p.origin.contentHash, ...(p.failure ? { failure: p.failure } : {}) }]);+ kind: p.origin.kind, locator: p.origin.locator, pageId: p.origin.pageId, contentHash: p.origin.contentHash,+ ...(p.failure ? { failure: p.failure, attempts, ...(attempts >= MAX_DETERMINISTIC_FAILURES ? { held: true } : {}) } : {}) }]);await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-atoms',$1,$2::text::jsonb)ON CONFLICT(op,fingerprint) DO NOTHING`, [p.runKey, checkpoint]);if (p.checkpointKey) {@@ -494,8 +543,8 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: WriteON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()WHERE op_checkpoints.completed_keys=$3::text::jsonb RETURNING fingerprint`,[p.checkpointKey, checkpoint, p.expectedCheckpoint === null ? null : JSON.stringify(p.expectedCheckpoint)]);- if (!advanced.length) throw opError('revision_conflict', 'The reviewed atom retry checkpoint changed.',- `Another atom run completed source ${row.source_id}'s reviewed checkpoint after retry ${row.request_id} was accepted, so the retry was not recorded. Read the retry receipt; the later run's atoms stand.`,+ if (!advanced.length) throw opError('revision_conflict', 'The atom retry checkpoint changed.',+ `Another atom run completed source ${row.source_id}'s atom checkpoint after retry ${row.request_id} was accepted, so the retry was not recorded. Read the retry receipt; the later run's atoms stand.`,{ fix: receiptFix(row.request_id) });}return { status: p.failure ? 'failed' : 'completed',@@ -522,14 +571,56 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write} };}-/** The completed, failure-free `managed-atoms` checkpoint `ac` for one page at its current content hash. */-export function managedAtomCompletedSql(page: { sourceId: string; slug: string; pageId: string; contentHash: string }): string {+/** A `managed-atoms` checkpoint `ac` for one page at its current content hash, completed or failed. */+function managedAtomIdentitySql(page: { sourceId: string; slug: string; pageId: string; contentHash: string }): string {return `ac.op='managed-atoms' AND ac.completed_keys->0->>'sourceId'=${page.sourceId}AND ac.completed_keys->0->>'incarnation'=(SELECT incarnation::text FROM sources WHERE id=${page.sourceId})AND ac.completed_keys->0->>'kind'='page' AND ac.completed_keys->0->>'locator'=${page.slug}- AND ac.completed_keys->0->>'pageId'=${page.pageId}::text AND ac.completed_keys->0->>'contentHash'=${page.contentHash}+ AND ac.completed_keys->0->>'pageId'=${page.pageId}::text AND ac.completed_keys->0->>'contentHash'=${page.contentHash}`;+}++/** The completed, failure-free `managed-atoms` checkpoint `ac` for one page at its current content hash. */+export function managedAtomCompletedSql(page: { sourceId: string; slug: string; pageId: string; contentHash: string }): string {+ return `${managedAtomIdentitySql(page)}AND ac.completed_keys->0->>'failure' IS NULL`;}+/** #6325: discovery and the backlog skip a page whose current content completed or is held after repeated failures. */export const MANAGED_ATOM_DISCOVERY_SQL = `AND NOT EXISTS (SELECT 1 FROM op_checkpoints ac- WHERE ${managedAtomCompletedSql({ sourceId: 'p.source_id', slug: 'p.slug', pageId: 'p.id', contentHash: 'p.content_hash' })})`;+ WHERE ${managedAtomIdentitySql({ sourceId: 'p.source_id', slug: 'p.slug', pageId: 'p.id', contentHash: 'p.content_hash' })}+ AND (ac.completed_keys->0->>'failure' IS NULL OR ac.completed_keys->0->>'held'='true'))`;++export interface HeldManagedAtom {+ source_id: string;+ kind: 'page' | 'transcript';+ locator: string;+ request_id: string;+ failure: string;+ attempts: number;+ held_at: string;+}++/**+ * #6325: managed atom origins held after MAX_DETERMINISTIC_FAILURES failed extractions of their current+ * content, in the source's current incarnation, that no later run completed. A page whose content+ * changed since is back in the backlog and not listed.+ */+export async function listHeldManagedAtoms(engine: BrainEngine, sourceIds?: string[]): Promise<HeldManagedAtom[]> {+ const rows = await engine.executeRaw<HeldManagedAtom & { attempts: string | number; held_at: string | Date }>(+ `SELECT DISTINCT ON (h.completed_keys->0->>'requestId')+ h.completed_keys->0->>'sourceId' AS source_id, h.completed_keys->0->>'kind' AS kind,+ h.completed_keys->0->>'locator' AS locator, h.completed_keys->0->>'requestId' AS request_id,+ h.completed_keys->0->>'failure' AS failure, h.completed_keys->0->>'attempts' AS attempts, h.updated_at AS held_at+ FROM op_checkpoints h JOIN sources s ON s.id=h.completed_keys->0->>'sourceId' AND s.incarnation::text=h.completed_keys->0->>'incarnation'+ WHERE h.op='managed-atoms' AND h.completed_keys->0->>'held'='true'+ AND ($1::text[] IS NULL OR s.id=ANY($1::text[]))+ AND (h.completed_keys->0->>'kind'<>'page' OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id=s.id+ AND p.id::text=h.completed_keys->0->>'pageId' AND p.content_hash=h.completed_keys->0->>'contentHash' AND p.deleted_at IS NULL))+ AND NOT EXISTS (SELECT 1 FROM op_checkpoints ac WHERE ac.op='managed-atoms' AND ac.completed_keys->0->>'failure' IS NULL+ AND ac.completed_keys->0->>'sourceId'=s.id AND ac.completed_keys->0->>'incarnation'=s.incarnation::text+ AND ac.completed_keys->0->>'kind'=h.completed_keys->0->>'kind' AND ac.completed_keys->0->>'locator'=h.completed_keys->0->>'locator'+ AND ac.completed_keys->0->>'contentHash'=h.completed_keys->0->>'contentHash')+ ORDER BY h.completed_keys->0->>'requestId', h.updated_at`, [sourceIds ?? null]);+ return rows.map(row => ({ ...row, attempts: Number(row.attempts), held_at: new Date(row.held_at).toISOString() }))+ .sort((a, b) => a.source_id.localeCompare(b.source_id) || a.locator.localeCompare(b.locator));+}diff --git a/src/core/persistence/atom-retry.ts b/src/core/persistence/atom-retry.tsindex 008993ee52..142bdf3fbc 100644--- a/src/core/persistence/atom-retry.ts+++ b/src/core/persistence/atom-retry.ts@@ -34,7 +34,7 @@ export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: strinif (atomRetryInputKey(session, current) !== atomRetryInputKey(session, origin)) throw opError('source_changed', 'The original atom input changed; this retry cannot reuse it.',`The ${origin.kind} that atom request ${requestId} extracted from in source ${sourceId} has changed since, so its retained batch no longer applies; nothing was started. Run a fresh atom drain, which extracts from the current content.`,{ fix: drainFix(sourceId) });- if (await resumeManagedAtoms(engine, session, current)) return { status: 'completed', replayed: true, model_rerun: false };+ if (await resumeManagedAtoms(engine, session, current) === 'done') return { status: 'completed', replayed: true, model_rerun: false };const checkpoint = retry.expectedCheckpoint as Array<{ failure?: string }> | null;if (checkpoint && !checkpoint[0]?.failure) return { status: 'completed', replayed: true, model_rerun: false };const saved = retry.rows.filter(row => row.intent?.kind === 'managed_atom_page');diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 9b011dac58..686dd56498 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -171,6 +171,7 @@" [OK] two_consumers_on_host: PGLite admits one process; no consumer heartbeat rows are kept."," [OK] consumers_without_heartbeat: PGLite admits one process; no consumer heartbeat rows are kept."," [OK] host_identity_mismatch: This process's host identity (<home>/.gbrain/persistence/host.json) owns every binding this filesystem holds.",+ " [OK] extract_atoms_held_failed: No managed atom page or transcript is held after repeated extraction failures."," [OK] fence_integrity: No malformed facts or takes fence is held, stored or waiting in a checkout (2 source(s) scanned)."," [OK] search_mode: Mode: conservative (no per-key overrides — mode bundle is canonical)."," [OK] hidden_by_search_policy: No pages hidden by search-exclude policy.",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 94e5d98902..ff76b95188 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -2073,6 +2073,17 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "brain",+ "details": {+ "code": "held_failed",+ "held": 0,+ "items": []+ },+ "message": "No managed atom page or transcript is held after repeated extraction failures.",+ "name": "extract_atoms_held_failed",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 12f1707f74..e93d0c5bba 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -2178,6 +2178,17 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "brain",+ "details": {+ "code": "held_failed",+ "held": 0,+ "items": []+ },+ "message": "No managed atom page or transcript is held after repeated extraction failures.",+ "name": "extract_atoms_held_failed",+ "status": "ok"+ },{"category": "brain","details": {@@ -5172,6 +5183,17 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "brain",+ "details": {+ "code": "held_failed",+ "held": 0,+ "items": []+ },+ "message": "No managed atom page or transcript is held after repeated extraction failures.",+ "name": "extract_atoms_held_failed",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex 623276f439..e93afd8a93 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -2169,6 +2169,17 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "brain",+ "details": {+ "code": "held_failed",+ "held": 0,+ "items": []+ },+ "message": "No managed atom page or transcript is held after repeated extraction failures.",+ "name": "extract_atoms_held_failed",+ "status": "ok"+ },{"category": "brain","details": {@@ -5152,6 +5163,17 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "brain",+ "details": {+ "code": "held_failed",+ "held": 0,+ "items": []+ },+ "message": "No managed atom page or transcript is held after repeated extraction failures.",+ "name": "extract_atoms_held_failed",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 82af928fec..644d5ac12d 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1886,6 +1886,17 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "brain",+ "details": {+ "code": "held_failed",+ "held": 0,+ "items": []+ },+ "message": "No managed atom page or transcript is held after repeated extraction failures.",+ "name": "extract_atoms_held_failed",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex ea15f2363b..8f52dad40c 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1958,6 +1958,17 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "brain",+ "details": {+ "code": "held_failed",+ "held": 0,+ "items": []+ },+ "message": "No managed atom page or transcript is held after repeated extraction failures.",+ "name": "extract_atoms_held_failed",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 1ba78e6cd8..b1547495fe 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1949,6 +1949,17 @@"name": "host_identity_mismatch","status": "ok"},+ {+ "category": "brain",+ "details": {+ "code": "held_failed",+ "held": 0,+ "items": []+ },+ "message": "No managed atom page or transcript is held after repeated extraction failures.",+ "name": "extract_atoms_held_failed",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 3adaf68f23..6ccef833bf 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -733,6 +733,10 @@"category": "ops","name": "host_identity_mismatch"},+ {+ "category": "brain",+ "name": "extract_atoms_held_failed"+ },{"category": "brain","name": "fence_integrity"diff --git a/test/helpers/managed-atom-compaction.ts b/test/helpers/managed-atom-compaction.tsindex 53e3324328..02611f6ce5 100644--- a/test/helpers/managed-atom-compaction.ts+++ b/test/helpers/managed-atom-compaction.ts@@ -102,12 +102,14 @@ export async function exerciseAtomCompaction(engine: BrainEngine, scenario: type__setChatTransportForTests(providerFree);if (action === 'resume') {const replay = await runPhaseExtractAtoms(engine, { ...opts, _chat: providerFree });- expect(calls).toBe(1);+ // #6325: a failed batch is retried automatically whether or not its receipt was compacted.+ expect(calls).toBe(scenario === 'malformed' ? 2 : 1);expect(replay.status).toBe(scenario === 'success' ? 'ok' : 'warn');if (scenario === 'success') expect(replay.details?.duplicates_skipped).toBe(1);const session = (await managedAtomSession(engine, sourceId))!;const origin = await readAtomOrigin(engine, session, { kind: 'page', slug: page.slug, content: page.compiled_truth, contentHash: page.content_hash! });- if (scenario === 'success') expect(await resumeManagedAtoms(engine, session, origin)).toBe(true);+ if (scenario === 'success') expect(await resumeManagedAtoms(engine, session, origin)).toBe('done');+ else if (scenario === 'malformed') expect(await resumeManagedAtoms(engine, session, origin)).toBe('run');else {let error: unknown;try { await resumeManagedAtoms(engine, session, origin); } catch (caught) { error = caught; }@@ -130,7 +132,7 @@ export async function exerciseAtomCompaction(engine: BrainEngine, scenario: type}}await disposePersistenceConsumer(engine);- expect(calls).toBe(1);+ expect(calls).toBe(action === 'resume' && scenario === 'malformed' ? 2 : 1);expect(await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [sourceId])).toEqual(retained);expect(await engine.executeRaw('SELECT * FROM pages WHERE source_id=$1 ORDER BY id', [sourceId])).toEqual(pagesBefore);expect(await engine.executeRaw("SELECT * FROM op_checkpoints WHERE op='managed-atoms' AND completed_keys->0->>'sourceId'=$1 ORDER BY fingerprint", [sourceId])).toEqual(checkpointsBefore);diff --git a/test/helpers/managed-atoms-contract.ts b/test/helpers/managed-atoms-contract.tsindex f39bebd1fa..a4c7c49b45 100644--- a/test/helpers/managed-atoms-contract.ts+++ b/test/helpers/managed-atoms-contract.ts@@ -242,7 +242,8 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):}await disposePersistenceConsumer(engine);const replay = await runPhaseExtractAtoms(engine, opts);- expect(calls).toBe(1);+ // #6325: a malformed batch is retried automatically (one strike per completed failure).+ expect(calls).toBe(scenario === 'malformed' ? 2 : 1);expect(replay.status).toBe(scenario === 'malformed' ? 'warn' : 'ok');const atoms = await engine.executeRaw<{ slug: string; visibility: string }>("SELECT slug,frontmatter->>'visibility' AS visibility FROM pages WHERE source_id=$1 AND type='atom'", [sourceId]);expect(atoms).toHaveLength(scenario === 'zero_yield' || scenario === 'malformed' ? 0 : 1);@@ -261,12 +262,19 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):if (scenario !== 'malformed' && !transcript) expect(await countExtractAtomsBacklog(engine, sourceId)).toBe(0);expect((await engine.getPage(page.slug, { sourceId }))?.frontmatter).not.toHaveProperty('atoms_scan_hash');if (scenario === 'zero_yield' || scenario === 'malformed') {+ // #6325: the third malformed attempt holds the page; a held page is neither re-run nor re-struck.+ if (scenario === 'malformed') {+ await disposePersistenceConsumer(engine);+ await runPhaseExtractAtoms(engine, opts);+ expect(calls).toBe(3);+ expect(await countExtractAtomsBacklog(engine, sourceId)).toBe(0);+ }const state = await readState();await disposePersistenceConsumer(engine);await runPhaseExtractAtoms(engine, opts);- expect(calls).toBe(1);+ expect(calls).toBe(scenario === 'malformed' ? 3 : 1);expect(await readState()).toEqual(state);- expect(state).toEqual([{ content_hash: page.content_hash!, fail_count: scenario === 'malformed' ? 1 : 0, tombstoned: scenario === 'zero_yield' }]);+ expect(state).toEqual([{ content_hash: page.content_hash!, fail_count: scenario === 'malformed' ? 3 : 0, tombstoned: scenario === 'zero_yield' }]);}});} finally { restoreWait(); await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); __setChatTransportForTests(null); rmSync(home, { recursive: true, force: true }); }diff --git a/test/managed-atoms-retry.test.ts b/test/managed-atoms-retry.test.tsnew file mode 100644index 0000000000..060ac237c7--- /dev/null+++ b/test/managed-atoms-retry.test.ts@@ -0,0 +1,214 @@+/**+ * #6325: a failed managed atom batch is retried automatically, a bounded+ * number of times per content identity, inside the run budget. A strike lands+ * once per newly completed failure; after MAX_DETERMINISTIC_FAILURES the page+ * (or transcript) settles held_failed: out of discovery and the backlog, never+ * replayed as a failure, listed by doctor. A content change starts over.+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { __setChatTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import type { ChatResult } from '../src/core/ai/gateway.ts';+import { countExtractAtomsBacklog, discoverExtractablePages, MAX_DETERMINISTIC_FAILURES, runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';+import { runExtractAtomsDrainForSource } from '../src/core/cycle/extract-atoms-drain.ts';+import { disposePersistenceConsumer, stopPersistenceConsumer } from '../src/core/persistence/service.ts';+import { sha256 } from '../src/core/persistence/digest.ts';+import { retryManagedAtomBatch } from '../src/core/persistence/atom-retry.ts';+import { atomHeldFailedEntry } from '../src/commands/doctor/checks/atom-holds.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { Check } from '../src/commands/doctor.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+beforeEach(async () => { await stopPersistenceConsumer(engine); await resetPgliteState(engine); });+afterAll(async () => { __setChatTransportForTests(null); await engine.disconnect(); resetGateway(); });++const VALID = JSON.stringify([{ title: 'Measured progress', atom_type: 'insight', body: 'Measure progress against clear exit criteria.' }]);++function fixture() {+ const replies: string[] = [];+ let calls = 0;+ const chat = async (): Promise<ChatResult> => {+ calls++;+ return { text: replies.shift() ?? 'not valid output', blocks: [], stopReason: 'end',+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' };+ };+ return { replies, chat, calls: () => calls };+}++async function managed<T>(work: (home: string) => Promise<T>): Promise<T> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-atom-retry-'));+ try {+ return await withEnv({ GBRAIN_HOME: home }, () => work(home));+ } finally {+ __setChatTransportForTests(null);+ await stopPersistenceConsumer(engine);+ await setManaged(false);+ rmSync(home, { recursive: true, force: true });+ }+}++const setManaged = (on: boolean) => engine.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [on]);+const writePage = async (text: string) => {+ await setManaged(false);+ const page = await engine.putPage('notes/example', { type: 'note', title: 'Example',+ compiled_truth: `${text} `.repeat(40) }, { sourceId: 'default' });+ await setManaged(true);+ return page;+};++const checkpoints = () => engine.executeRaw<{ attempts: string | null; held: string | null; failure: string | null; request_id: string }>(+ `SELECT completed_keys->0->>'attempts' AS attempts, completed_keys->0->>'held' AS held, completed_keys->0->>'failure' AS failure,+ completed_keys->0->>'requestId' AS request_id+ FROM op_checkpoints WHERE op='managed-atoms' AND fingerprint NOT IN (+ SELECT DISTINCT intent->>'runKey' FROM persistence_requests WHERE intent->>'checkpointKey' IS NOT NULL)`);++const doctorHeld = async () => (await atomHeldFailedEntry.run({ engine } as unknown as DoctorContext) as Check[])[0]!;++const atomCount = async () => (await engine.executeRaw("SELECT id FROM pages WHERE type='atom' AND deleted_at IS NULL")).length;++test('a malformed reply, then a valid one: the next run retries on its own and extracts', async () => {+ await managed(async () => {+ const page = await writePage('A careful project record.');+ const f = fixture();+ const extract = () => runPhaseExtractAtoms(engine, { _transcripts: [],+ _pages: [{ slug: page.slug, content: page.compiled_truth, contentHash: page.content_hash! }], _chat: f.chat });+ expect((await extract()).status).toBe('warn');+ expect(f.calls()).toBe(1);+ await disposePersistenceConsumer(engine);+ f.replies.push(VALID);+ const retried = await extract();+ expect(f.calls()).toBe(2);+ expect(retried.status).toBe('ok');+ expect(retried.details?.failures).toEqual([]);+ expect(await atomCount()).toBe(1);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(0);+ await disposePersistenceConsumer(engine);+ await extract();+ expect(f.calls()).toBe(2);+ });+}, 60_000);++test('three malformed replies settle the page held_failed: out of the backlog, never replayed or re-struck', async () => {+ await managed(async () => {+ const page = await writePage('A careful project record.');+ const f = fixture();+ const extract = () => runPhaseExtractAtoms(engine, { _transcripts: [],+ _pages: [{ slug: page.slug, content: page.compiled_truth, contentHash: page.content_hash! }], _chat: f.chat });+ for (let attempt = 1; attempt <= MAX_DETERMINISTIC_FAILURES; attempt++) {+ const run = await extract();+ expect(f.calls()).toBe(attempt);+ expect(run.details?.malformed_outputs).toBe(1);+ const [checkpoint] = await checkpoints();+ expect(Number(checkpoint.attempts)).toBe(attempt);+ expect(checkpoint.held === 'true').toBe(attempt === MAX_DETERMINISTIC_FAILURES);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(attempt === MAX_DETERMINISTIC_FAILURES ? 0 : 1);+ await disposePersistenceConsumer(engine);+ }+ expect(await discoverExtractablePages(engine, 'default')).toEqual([]);+ const held = await extract();+ expect(f.calls()).toBe(MAX_DETERMINISTIC_FAILURES);+ expect(held.details?.failures).toEqual([]);+ expect(held.details?.held_failed).toBe(1);+ expect(await checkpoints()).toHaveLength(1);+ expect(Number((await checkpoints())[0].attempts)).toBe(MAX_DETERMINISTIC_FAILURES);+ expect(await engine.executeRaw('SELECT fail_count FROM extract_atoms_page_state WHERE page_id=$1', [page.id]))+ .toEqual([{ fail_count: MAX_DETERMINISTIC_FAILURES }]);+ expect(await atomCount()).toBe(0);+ const doctor = await doctorHeld();+ expect(categorizeCheck(doctor.name)).toBeTruthy();+ expect(doctor.status).toBe('warn');+ expect(doctor.message).toContain('held_failed');+ expect(doctor.details?.items).toEqual([expect.objectContaining({ source_id: 'default', kind: 'page', locator: page.slug,+ request_id: (await checkpoints())[0].request_id, attempts: MAX_DETERMINISTIC_FAILURES })]);+ expect(doctor.fix).toMatchObject({ consent: ['paid'], argv: ['gbrain', 'jobs', 'submit', 'extract-atoms-drain', '--params',+ JSON.stringify({ sourceId: 'default', retryRequestId: (await checkpoints())[0].request_id })] });++ // A content change is a new identity: discovery offers it and the count starts over.+ await disposePersistenceConsumer(engine);+ await writePage('A rewritten project record.');+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);+ const [changed] = await discoverExtractablePages(engine, 'default');+ f.replies.push(VALID);+ expect((await runPhaseExtractAtoms(engine, { _transcripts: [], _pages: [{ slug: changed.slug, content: changed.content, contentHash: changed.contentHash }], _chat: f.chat })).status).toBe('ok');+ expect(f.calls()).toBe(MAX_DETERMINISTIC_FAILURES + 1);+ expect(await atomCount()).toBe(1);+ expect((await doctorHeld()).status).toBe('ok');+ });+}, 90_000);++test('an explicit retry still runs a held page and clears it from doctor', async () => {+ await managed(async () => {+ const page = await writePage('A careful project record.');+ const f = fixture();+ const extract = () => runPhaseExtractAtoms(engine, { _transcripts: [],+ _pages: [{ slug: page.slug, content: page.compiled_truth, contentHash: page.content_hash! }], _chat: f.chat });+ for (let attempt = 1; attempt <= MAX_DETERMINISTIC_FAILURES; attempt++) { await extract(); await disposePersistenceConsumer(engine); }+ const held = await doctorHeld();+ expect(held.status).toBe('warn');+ const requestId = (held.details?.items as Array<{ request_id: string }>)[0].request_id;+ f.replies.push(VALID);+ __setChatTransportForTests(f.chat);+ expect(await retryManagedAtomBatch(engine, 'default', requestId, 'job:61')).toMatchObject({ model_rerun: true });+ expect(f.calls()).toBe(MAX_DETERMINISTIC_FAILURES + 1);+ expect(await atomCount()).toBe(1);+ await disposePersistenceConsumer(engine);+ expect((await doctorHeld()).status).toBe('ok');+ await extract();+ expect(f.calls()).toBe(MAX_DETERMINISTIC_FAILURES + 1);+ });+}, 90_000);++test('a transcript origin is bounded the same way', async () => {+ await managed(async (home) => {+ const file = join(home, 'session.txt');+ const text = 'A careful session transcript about measured progress. '.repeat(40);+ writeFileSync(file, text);+ await setManaged(true);+ const f = fixture();+ const extract = () => runPhaseExtractAtoms(engine, { _pages: [], _transcripts: [{ filePath: file, content: text, contentHash: sha256(text) }], _chat: f.chat });+ for (let attempt = 1; attempt <= MAX_DETERMINISTIC_FAILURES; attempt++) {+ await extract();+ expect(f.calls()).toBe(attempt);+ await disposePersistenceConsumer(engine);+ }+ const held = await extract();+ expect(f.calls()).toBe(MAX_DETERMINISTIC_FAILURES);+ expect(held.details?.failures).toEqual([]);+ expect(held.details?.held_failed).toBe(1);+ });+}, 90_000);++test('a drain over a failed page retries it instead of stopping provider_failure on the replay', async () => {+ await managed(async () => {+ await writePage('A careful project record.');+ await engine.setConfig('models.dream.extract_atoms', 'anthropic:claude-haiku-4-5');+ const f = fixture();+ __setChatTransportForTests(f.chat);+ await withEnv({ ANTHROPIC_API_KEY: 'sk-test-atom-retry' }, async () => {+ const first = await runExtractAtomsDrainForSource(engine, { sourceId: 'default', windowSeconds: 120, maxBatches: 1 });+ expect(f.calls()).toBe(1);+ expect(first.failure_count).toBe(1);+ await disposePersistenceConsumer(engine);+ f.replies.push(VALID);+ const second = await runExtractAtomsDrainForSource(engine, { sourceId: 'default', windowSeconds: 120, maxBatches: 3 });+ expect(f.calls()).toBe(2);+ expect(second.status).toBe('ok');+ expect(second.stopped).toBe('drained');+ expect(second.extracted).toBe(1);+ expect(second.remaining).toBe(0);+ });+ });+}, 60_000);diff --git a/test/managed-atoms-stop-reason.test.ts b/test/managed-atoms-stop-reason.test.tsindex fd49700571..16bc64ae3b 100644--- a/test/managed-atoms-stop-reason.test.ts+++ b/test/managed-atoms-stop-reason.test.ts@@ -1,9 +1,9 @@/*** #6260 on a managed brain: a clipped atoms response (stopReason length,* refusal or content_filter) is a failure receipt. It never publishes atoms,- * never retires the page's earlier atoms, and the next run asks for an- * approved retry instead of paying again; the approved retry with a complete- * answer extracts.+ * never retires the page's earlier atoms, and the next run retries it+ * automatically (#6325, bounded at MAX_DETERMINISTIC_FAILURES); an explicit+ * retry with a complete answer extracts.*/import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';import { mkdtempSync, rmSync } from 'node:fs';@@ -38,7 +38,7 @@ async function liveAtoms(): Promise<string[]> {}for (const stop of ['length', 'refusal', 'content_filter'] as const) {- test(`managed ${stop}: failure receipt, prior atoms kept, next run asks for an approved retry`, async () => {+ test(`managed ${stop}: failure receipt, prior atoms kept, next run retries automatically`, async () => {const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-atom-stop-'));try {await withEnv({ GBRAIN_HOME: home }, async () => {@@ -76,9 +76,8 @@ for (const stop of ['length', 'refusal', 'content_filter'] as const) {await disposePersistenceConsumer(engine);const again = await extract();- expect(calls).toBe(2);+ expect(calls).toBe(3);expect(JSON.stringify(again.details?.failures)).toContain(`stopReason=${stop}`);- expect(JSON.stringify(again.details?.failures)).toContain('a new attempt needs approval');expect(await liveAtoms()).toEqual(prior);await disposePersistenceConsumer(engine);@@ -91,7 +90,7 @@ for (const stop of ['length', 'refusal', 'content_filter'] as const) {updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {}, isActive: async () => true, readInbox: async () => [] };const retried = await worker.getHandler('extract-atoms-drain')!(job) as Record<string, unknown>;expect(retried.model_rerun).toBe(true);- expect(calls).toBe(3);+ expect(calls).toBe(4);const after = await liveAtoms();expect(after).toHaveLength(1);expect(after[0]).toContain('hire-slowly');