Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(atoms): keep the retiring extraction's batch resumable; give stale-atoms retirements attempt-aware request ids
garrytan294533b8d306
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 6a35e461bd..12f3fa4f05 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -15,7 +15,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `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 and local synthesize/patterns/consolidation.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) 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.+ Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.Derived atom pages may regenerate or retire when their canonical file is already absent, while ordinary page writes retain missing-file refusal.Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. `submitMaintenanceIntent` admits a maintenance request with its own intent kind keyed by the intent; `prepareMaintenanceMutation` also handles `managed_maintenance_phantom_merge` and `managed_maintenance_phantom_delete` (both delegated to `cycle/phantom-redirect-managed.ts`). `publishMaintenancePage` accepts an optional `eventProjection` (Life Chronicle): the event page and its depth-page timeline row commit in the same publication with the depth page key locked. Remote maintenance remains refused.- `src/core/persistence/derived-facts.ts` — database-only fact rows derived from page text (fence reconcile, conversation facts): `managedDerivedFactsPreflight` (managed check, accepting persistence, local writer, active source; before provider spend), `withDerivedFactsWrite` (one transaction holding the coordinator source capability and the page keys, like derived links), `writeDerivedFacts` (that on a managed brain, the caller's own engine call otherwise) and `replaceDerivedFactsForPage` (inside that transaction: the caller's current-page recheck, then the page's prior rows for one writer prefix are deleted and the replacement batch inserted, so a failed or raced extraction keeps the prior batch; `test/managed-facts-writers.test.ts`). No persistence request is admitted per row. Tests: `test/managed-extract-atoms.test.ts`, `test/managed-facts-backstop.test.ts`, `test/managed-maintenance.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex d3ed1fc40d..6c13f8b18d 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. `safeChunkUpgradeAdvisory` formats a pending-count line (the post-upgrade recovery banner reports `safe_index_pending` instead). `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use; a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Only explicit-only kinds accept `--expect <hash>` and `--include-ambiguous`, passed to `plan` as `RepairPlanOptions`; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired` or `changed_since_preview`. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`.+- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. `safeChunkUpgradeAdvisory` formats a pending-count line (the post-upgrade recovery banner reports `safe_index_pending` instead). `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use; a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Only explicit-only kinds accept `--expect <hash>` and `--include-ambiguous`, passed to `plan` as `RepairPlanOptions`; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`.- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.tsindex cab9f4bebe..ae0719dda9 100644--- a/src/core/persistence/atom-maintenance.ts+++ b/src/core/persistence/atom-maintenance.ts@@ -120,7 +120,7 @@ export async function readAtomOrigin(engine: BrainEngine, session: ManagedAtomSeif (!snapshot || snapshot.sourceIncarnation !== session.incarnation || snapshot.page.content_hash !== item.contentHash || snapshot.page.compiled_truth !== item.content) {throw new OperationError('revision_conflict', 'The atom input changed before extraction.');}- const generation = await atomGeneration(engine, snapshot.page.id);+ const generation = await atomGeneration(engine, snapshot.page.id, item.contentHash);return { kind: item.kind, locator: item.slug, contentHash: item.contentHash, textHash: sha256(item.content), pageId: snapshot.page.id,revision: snapshot.revision, visibility: effectiveVisibility({ kind: 'page', page: snapshot.page }), ...(generation > 0 ? { generation } : {}) };}@@ -128,21 +128,30 @@ export async function readAtomOrigin(engine: BrainEngine, session: ManagedAtomSeexport const ATOM_GENERATION_OP = 'managed-atoms-generation';export const ATOM_RETIRED_BY_REEXTRACT = 'managed-reextract';-async function atomGeneration(engine: BrainEngine, pageId: number): Promise<number> {- const [row] = await engine.executeRaw<{ generation: string | null }>(- `SELECT completed_keys->0->>'generation' AS generation FROM op_checkpoints WHERE op='${ATOM_GENERATION_OP}' AND fingerprint=$1`, [String(pageId)]);- return Number(row?.generation ?? 0);+/**+ * The generation a page's content keys on: the content a retirement kept (the extraction that retired) keeps+ * the generation its accepted batch already used, so that batch stays resumable; every other content moves on.+ */+async function atomGeneration(engine: BrainEngine, pageId: number, contentHash: string): Promise<number> {+ const [row] = await engine.executeRaw<{ generation: string | null; keep: string | null; keep_generation: string | null }>(+ `SELECT completed_keys->0->>'generation' AS generation, completed_keys->0->>'keep' AS keep, completed_keys->0->>'keep_generation' AS keep_generation+ FROM op_checkpoints WHERE op='${ATOM_GENERATION_OP}' AND fingerprint=$1`, [String(pageId)]);+ if (!row) return 0;+ return Number((row.keep !== null && row.keep === contentHash ? row.keep_generation : row.generation) ?? 0);}/*** Retiring an origin page's atoms invalidates its earlier completed extractions: the generation- * changes the run key, so a retained receipt is not replayed, and discovery offers the page again.- * State for `keepContentHash` (the extraction completing in this transaction) is kept.+ * changes the run key of every other content, so a retained receipt is not replayed, and discovery+ * offers the page again. `keepContentHash` (the extraction that retired) keeps its key and its state.*/export async function bumpAtomGeneration(tx: BrainEngine, sourceId: string, incarnation: string, pageId: number, keepContentHash: string | null): Promise<void> {- await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('${ATOM_GENERATION_OP}',$1,'[{"generation":1}]'::jsonb)+ const kept = keepContentHash === null ? null : await atomGeneration(tx, pageId, keepContentHash);+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)+ VALUES('${ATOM_GENERATION_OP}',$1,jsonb_build_array(jsonb_build_object('generation',1,'keep',$2::text,'keep_generation',$3::integer)))ON CONFLICT(op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=jsonb_build_array(jsonb_build_object('generation',- COALESCE((op_checkpoints.completed_keys->0->>'generation')::integer,0)+1))`, [String(pageId)]);+ COALESCE((op_checkpoints.completed_keys->0->>'generation')::integer,0)+1,'keep',$2::text,'keep_generation',$3::integer))`,+ [String(pageId), keepContentHash, kept]);await tx.executeRaw('DELETE FROM extract_atoms_page_state WHERE source_incarnation=$1::uuid AND page_id=$2 AND content_hash IS DISTINCT FROM $3::text',[incarnation, pageId, keepContentHash]);await tx.executeRaw(`DELETE FROM op_checkpoints WHERE op='managed-atoms' AND completed_keys->0->>'sourceId'=$1diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 29e8a40eeb..b93318cc85 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -118,8 +118,8 @@ export async function publishMaintenancePage(engine: BrainEngine, authority: Mai/** A maintenance request with its own intent kind, keyed by the intent (a retry replays its receipt). */export async function submitMaintenanceIntent(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,- intent: Record<string, unknown> & { kind: string; expected_revision: string | null }): Promise<Record<string, unknown>> {- return submitMaintenance(engine, authority, slug, intent, maintenanceRequestId({ authority: authority.writer, slug, intent }));+ intent: Record<string, unknown> & { kind: string; expected_revision: string | null }, requestId?: string): Promise<Record<string, unknown>> {+ return submitMaintenance(engine, authority, slug, intent, requestId ?? maintenanceRequestId({ authority: authority.writer, slug, intent }));}export async function stampMaintenancePage(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,diff --git a/src/core/repair/stale-atoms.ts b/src/core/repair/stale-atoms.tsindex daa56f3c3e..a108a58652 100644--- a/src/core/repair/stale-atoms.ts+++ b/src/core/repair/stale-atoms.ts@@ -26,14 +26,14 @@ import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import type { PreparedMutation } from '../persistence/coordinator.ts';import type { WriteRequest } from '../persistence/model.ts';-import { OperationError } from '../ops/contract.ts';+import { OperationError, type OperationContext } from '../ops/contract.ts';import { authorizeWrite } from '../persistence/authority.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { preparePageMutation } from '../persistence/page-prepare.ts';import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';import { bumpAtomGeneration, managedAtomCompletedSql } from '../persistence/atom-maintenance.ts';import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';-import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';export const STALE_ATOMS_RETIRED_BY = 'stale-atoms';export const STALE_ATOMS_INTENT = 'managed_maintenance_retire_stale_atoms';@@ -152,21 +152,24 @@ export const staleAtomsRepair: RepairHandler = {},async apply(ctx, entry): Promise<RepairItemOutcome> {const { atom, hash, last } = entry as StaleAtomItem;- const outcome = await retireStaleAtom(ctx.engine, atom);+ const outcome = await retireStaleAtom(ctx, atom);if (last) await clearApprovedSet(ctx.engine, { command: 'stale-atoms', hash });return outcome;},};-async function retireStaleAtom(engine: BrainEngine, atom: StaleAtom): Promise<RepairItemOutcome> {+async function retireStaleAtom(ctx: OperationContext, atom: StaleAtom): Promise<RepairItemOutcome> {+ const engine = ctx.engine;const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });if (!sameAtom((await staleAtoms(engine, [atom.source_id], atom.id))[0], atom)) return changed('the atom or its source page changed');if (await managedPersistenceEnabled(engine)) {const authority = (await maintenancePreflight(engine, atom.source_id))!;try {- await submitMaintenanceIntent(engine, authority, atom.slug, { kind: STALE_ATOMS_INTENT, expected_revision: atom.revision, atom });+ await submitMaintenanceIntent(engine, authority, atom.slug, { kind: STALE_ATOMS_INTENT, expected_revision: atom.revision, atom },+ await repairRequestId(ctx, 'stale-atoms', atom, atom.revision));} catch (error) {if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) return changed(error.message);+ if (error instanceof OperationError && error.code === 'source_changed') return { applied: false, outcome: 'file_conflict', reason: error.message };throw error;}return { applied: true, outcome: 'retired' };diff --git a/test/helpers/managed-atoms-contract.ts b/test/helpers/managed-atoms-contract.tsindex 05d0a4fc41..f204661c52 100644--- a/test/helpers/managed-atoms-contract.ts+++ b/test/helpers/managed-atoms-contract.ts@@ -443,6 +443,8 @@ export async function exerciseManagedAtomRetirement(engine: BrainEngine, scenariexpect((await atom('patience-compounds'))?.deleted).toBe(true);rmSync(join(root, `${queued.slug}.md`));await disposePersistenceConsumer(engine);+ await extract();+ expect(calls).toBe(3);await edit(bodies[1], ['Patience compounds', 'Queue patiently', 'Hire slowly']);expect((await discoverExtractablePages(engine, sourceId)).map(item => item.slug)).toEqual([slug]);expect((await extract()).status).toBe('ok');diff --git a/test/repair-stale-atoms.test.ts b/test/repair-stale-atoms.test.tsindex 7491243a61..dff4af5c43 100644--- a/test/repair-stale-atoms.test.ts+++ b/test/repair-stale-atoms.test.ts@@ -255,6 +255,29 @@ for (const kind of testBackends()) {}}, 60_000);+ test('managed: an atom whose file holds an uncoordinated edit reports file_conflict, and a fresh apply retires it once the file is fixed', async () => {+ const sourceId = `stale-f-${randomUUID().slice(0, 8)}`;+ const f = await managedFixture(sourceId);+ try {+ expect((await f.extract()).status).toBe('ok');+ await f.unmanaged(() => engine.softDeletePage(f.slug, { sourceId }));+ const [first] = await f.atoms();+ writeFileSync(join(f.root, `${first.slug}.md`), 'Uncoordinated operator content.');+ const preview = await repair(['--source', sourceId]);+ const blocked = await repair(['--source', sourceId, '--apply', '--expect', hashOf(preview)]);+ expect(blocked.results[0].outcomes).toEqual({ file_conflict: 1, retired: 1 });+ expect((await atom(sourceId, first.slug)).deleted).toBe(false);+ rmSync(join(f.root, `${first.slug}.md`));+ const again = await repair(['--source', sourceId]);+ expect(again.results[0].listing!.map(entry => entry.item)).toEqual([`${sourceId}:${first.slug}`]);+ expect((await repair(['--source', sourceId, '--apply', '--expect', hashOf(again)])).results[0].outcomes).toEqual({ retired: 1 });+ expect((await atom(sourceId, first.slug))).toMatchObject({ deleted: true, frontmatter: { retired_by: 'stale-atoms' } });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ }, 60_000);+test('managed: atoms of an edited page are stale only once its current text completed an extraction', async () => {const sourceId = `stale-c-${randomUUID().slice(0, 8)}`;const f = await managedFixture(sourceId);