Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): retire stale managed atoms

cmontemuinob38e89ecd4d8
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index ad43417579..d9cd78cfb0 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -19,7 +19,10 @@ 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 continuous lock hold, **rediscovering eligibility each batch** (idempotent NOT-EXISTS-on-`source_hash`, so content mutated by a concurrent process simply doesn't match — no cross-window stale cursor), until the backlog is empty OR the time window elapses. Returns `{phase, status, extracted, skipped, remaining, batches, stopped}`. Backs `gbrain dream --phase extract_atoms --drain`. Takes the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent autopilot tick genuinely defers with `cycle_already_running`); NO release/reacquire-between-windows primitive. The shared wiring helper `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?})` owns the lock+batch+count+defer wiring (dynamic imports of db-lock/cycle/extract-atoms keep the pure loop cheap to unit-test) and is the ONE drain path for three callers — `gbrain dream --drain` (which calls it), the `extract-atoms-drain` Minion handler, and autopilot auto-drain — so lock id / window / defer-on-busy can't drift. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'` extraction; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates to the caller (each reports the busy case its own way). Pinned by `test/extract-atoms-drain.test.ts`. The summary's `last_error` always passes through `sanitizeFailureText` (secret/DSN redaction, whitespace collapse, bounded): typed failure records use the source/reason caps, and the count-only `firstError` compatibility path is sanitized to the combined bound, so a provider payload cannot ride either path into `--json` output. `formatDrainProviderFailure(result)` renders the Minion handler's `provider_failure` throw (batches/remaining + `last_error`), so the dead-lettered job's `error_text` names the cause.
-- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. 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. 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, so LLM-chosen titles that drift between extractions don't pile 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 (migration `extract_atoms_transcript_state_table`; keyed `(source_id, file_path, content_hash)` with the 16-char hash prefix, so an edit is a new row and re-eligibilizes): `recordItemFailureCount` counts a transcript's malformed output toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (the same zero-yield policy as pages), 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.
+- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. 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. 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.
+ 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 (migration `extract_atoms_transcript_state_table`; keyed `(source_id, file_path, content_hash)` with the 16-char hash prefix, so an edit is a new row and re-eligibilizes): `recordItemFailureCount` counts a transcript's malformed output toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (the same zero-yield policy as pages), 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.
- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. Tests: `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index d55c4f9453..ed591c8044 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -13,8 +13,11 @@ The page operations that submit through this layer are in [Core Services (2/3)](
- `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,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. 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`.
+- `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.
+ 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`.
- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. A new fence row whose number belongs to a database-only take refuses with `take_row_collision`. `compileCanonicalProjections` is the validation-only entry. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres).
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index a289eb7554..d5000445a1 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -36,7 +36,7 @@ export interface ManagedAtomSession {
retry?: { runKey: string; checkpointKey: string; expectedCheckpoint: unknown; rows: WriteRequest[]; origin: AtomOrigin };
}
export interface AtomIntent extends Record<string, unknown> {
- kind: 'managed_atom_page' | 'managed_atom_complete';
+ kind: 'managed_atom_page' | 'managed_atom_delete' | 'managed_atom_complete';
runKey: string;
origin: AtomOrigin;
expected_revision?: string;
@@ -65,6 +65,7 @@ export async function managedAtomSession(engine: BrainEngine, sourceId: string,
throw new OperationError('permission_denied', 'Atom maintenance requires a source-wide grant.');
}
await authorizeWrite(engine, authority, 'put_page', 'atoms/preflight');
+ await authorizeWrite(engine, authority, 'delete_page', 'atoms/preflight');
const binding = await getWorktreeBinding(engine, sourceId);
const root = source.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);
const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');
@@ -203,8 +204,15 @@ export async function resumeManagedAtoms(engine: BrainEngine, session: ManagedAt
return true;
}
+export interface ManagedAtomRetirement {
+ slug: string;
+ pageId: number;
+ revision: string;
+}
+
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): Promise<WriteReceipt[]> {
+ 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 inputs: Array<{ slug: string; pageId: number | null; intent: AtomIntent }> = [];
for (const atom of atoms) {
@@ -222,6 +230,23 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA
...(session.retry ? { checkpointKey: session.retry.checkpointKey, expectedCheckpoint: session.retry.expectedCheckpoint } : {}),
...(target.revision ? { expected_revision: target.revision } : {}), content: atom.content, links: atom.links } as AtomIntent });
}
+ const originKey = origin.kind === 'page' ? 'source_slug' : 'source_path';
+ const retirements = failure ? [] : reviewedRetirements ?? await engine.executeRaw<ManagedAtomRetirement>(
+ `SELECT slug,id AS "pageId",knowledge_revision::text AS revision FROM pages
+ WHERE source_id=$1 AND type='atom' AND deleted_at IS NULL
+ AND frontmatter->>'${originKey}'=$2
+ AND COALESCE(frontmatter->>'source_hash','')<>$3
+ AND NULLIF(frontmatter->>'imported_from','') IS NULL
+ AND NOT (slug=ANY($4::text[]))`,
+ [session.sourceId, origin.locator, origin.contentHash.slice(0, 16), atoms.map(atom => atom.slug)],
+ );
+ for (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 } : {}),
+ } as AtomIntent });
+ }
const rows = await engine.transaction(async tx => {
const children: string[] = [];
const accepted: WriteRequest[] = [];
@@ -234,7 +259,7 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA
worktreeId: session.binding?.worktree_id, topologyGeneration: session.binding?.topology_generation,
slug: input.slug, pageId: input.pageId, requestId, callerIntent: input.intent, intent: input.intent });
accepted.push(row);
- if (input.intent.kind === 'managed_atom_page') children.push(row.id);
+ if (input.intent.kind !== 'managed_atom_complete') children.push(row.id);
}
return accepted;
});
@@ -256,7 +281,7 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA
export async function prepareManagedAtomMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
const p = row.intent as AtomIntent | null;
- if (!p || !['managed_atom_page', 'managed_atom_complete'].includes(p.kind) || !p.origin || row.authority.remote) {
+ if (!p || !['managed_atom_page', 'managed_atom_delete', 'managed_atom_complete'].includes(p.kind) || !p.origin || row.authority.remote) {
throw new OperationError('permission_denied', 'Unsupported atom maintenance intent.');
}
const validate = async (tx: BrainEngine) => {
@@ -272,18 +297,30 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
};
await validate(engine);
const additionalPageKeys = p.origin.kind === 'page' ? [{ sourceId: row.source_id, slug: p.origin.locator }] : [];
+ if (p.kind === 'managed_atom_delete') {
+ await authorizeWrite(engine, row.authority, 'delete_page', row.slug);
+ const prepared = await preparePageMutation(engine, { ...row, operation: 'delete_page' }, config, undefined, undefined, { allowMissingFile: true });
+ return { ...prepared, additionalPageKeys, validate: async tx => {
+ await validate(tx);
+ await authorizeWrite(tx, row.authority, 'delete_page', row.slug);
+ await prepared.validate?.(tx);
+ }, apply: async tx => ({ ...await prepared.apply(tx), atom_run_key: p.runKey, atom_kind: p.kind }) };
+ }
if (p.kind === 'managed_atom_complete') {
const targets = await engine.executeRaw<{ slug: string }>('SELECT slug FROM persistence_requests WHERE id=ANY($1::uuid[]) AND source_incarnation=$2::uuid',
[p.children ?? [], row.source_incarnation]);
additionalPageKeys.push(...targets.map(target => ({ sourceId: row.source_id, slug: target.slug })));
return { observedRevision: null, noop: true, additionalPageKeys, validate, apply: async tx => {
const children = p.children ?? [];
- const committed = await tx.executeRaw<{ id: string }>(`SELECT r.id FROM persistence_requests r
- JOIN pages atom ON atom.source_id=r.source_id AND atom.slug=r.slug
- AND atom.knowledge_revision::text=r.outcome->>'revision' AND atom.deleted_at IS NULL AND atom.type='atom'
+ const committed = await tx.executeRaw<{ id: string; kind: AtomIntent['kind'] }>(`SELECT r.id,
+ COALESCE(r.intent->>'kind',r.outcome->>'atom_kind') AS kind FROM persistence_requests r
+ JOIN pages atom ON atom.source_id=r.source_id AND atom.slug=r.slug AND atom.type='atom'
WHERE r.id=ANY($1::uuid[]) AND r.source_incarnation=$2::uuid
AND r.state='committed' AND COALESCE(r.intent->>'runKey',r.outcome->>'atom_run_key')=$3
- AND COALESCE(r.intent->>'kind',r.outcome->>'atom_kind')='managed_atom_page'`, [children, row.source_incarnation, p.runKey]);
+ AND ((COALESCE(r.intent->>'kind',r.outcome->>'atom_kind')='managed_atom_page'
+ AND atom.knowledge_revision::text=r.outcome->>'revision' AND atom.deleted_at IS NULL)
+ OR (COALESCE(r.intent->>'kind',r.outcome->>'atom_kind')='managed_atom_delete'
+ AND atom.id=r.page_id AND atom.deleted_at IS NOT NULL))`, [children, row.source_incarnation, p.runKey]);
if (committed.length !== children.length) throw new OperationError('revision_conflict', 'The atom batch is not fully committed.');
if (p.origin.kind === 'page') {
const snapshot = await tx.readPageSnapshot(p.origin.locator, { sourceId: row.source_id });
@@ -303,11 +340,14 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
[p.checkpointKey, checkpoint, p.expectedCheckpoint === null ? null : JSON.stringify(p.expectedCheckpoint)]);
if (!advanced.length) throw new OperationError('revision_conflict', 'The reviewed atom retry checkpoint changed.');
}
- return { status: p.failure ? 'failed' : 'completed', atoms: children.length, ...(p.failure ? { failure: p.failure } : {}) };
+ return { status: p.failure ? 'failed' : 'completed',
+ atoms: committed.filter(child => child.kind === 'managed_atom_page').length,
+ retired: committed.filter(child => child.kind === 'managed_atom_delete').length,
+ ...(p.failure ? { failure: p.failure } : {}) };
} };
}
await authorizeWrite(engine, row.authority, 'put_page', row.slug);
- const prepared = await preparePageMutation(engine, { ...row, operation: 'put_page' }, config);
+ const prepared = await preparePageMutation(engine, { ...row, operation: 'put_page' }, config, undefined, undefined, { allowMissingFile: true });
return { ...prepared, additionalPageKeys, validate: async tx => { await validate(tx); await authorizeWrite(tx, row.authority, 'put_page', row.slug); await prepared.validate?.(tx); }, apply: async tx => {
const result = await prepared.apply(tx);
if (p.links?.length) await tx.addLinksBatch(p.links, { auditSite: 'cycle.extract_atoms.provenance' });
diff --git a/src/core/persistence/atom-retry.ts b/src/core/persistence/atom-retry.ts
index cab63de8f0..4cb5bb8950 100644
--- a/src/core/persistence/atom-retry.ts
+++ b/src/core/persistence/atom-retry.ts
@@ -1,7 +1,7 @@
import { readFileSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
-import { atomRetryInputKey, managedAtomSession, publishManagedAtoms, readAtomOrigin, resumeManagedAtoms, type AtomIntent } from './atom-maintenance.ts';
+import { atomRetryInputKey, managedAtomSession, publishManagedAtoms, readAtomOrigin, resumeManagedAtoms, type AtomIntent, type ManagedAtomRetirement } from './atom-maintenance.ts';
import { isWriteReceipt } from './types.ts';
export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: string, requestId: string, retryId: string): Promise<Record<string, unknown>> {
@@ -23,7 +23,8 @@ export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: strin
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');
- if (saved.length) {
+ const deleted = retry.rows.filter(row => row.intent?.kind === 'managed_atom_delete');
+ if (saved.length || deleted.length) {
const atoms: Parameters<typeof publishManagedAtoms>[3] = [];
for (const row of saved) {
const p = row.intent as AtomIntent;
@@ -37,7 +38,17 @@ export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: strin
if (typeof p.content !== 'string') throw new OperationError('storage_error', 'The retained atom publication content is unavailable.');
atoms.push({ slug: row.slug, content: p.content, links: p.links ?? [], expectedTarget: { pageId, revision } });
}
- const receipts = await publishManagedAtoms(engine, session, current, atoms);
+ const retirements: ManagedAtomRetirement[] = [];
+ for (const row of deleted) {
+ const p = row.intent as AtomIntent;
+ const target = await engine.readPageSnapshot(row.slug, { sourceId, includeDeleted: true });
+ if (typeof p.expected_revision !== 'string' || row.page_id === null || !target ||
+ target.page.id !== row.page_id || target.revision !== p.expected_revision || Boolean(target.page.deleted_at) !== (row.state === 'committed')) {
+ throw new OperationError('page_identity_changed', 'An atom retirement target changed independently of the failed publication.');
+ }
+ retirements.push({ slug: row.slug, pageId: row.page_id, revision: p.expected_revision });
+ }
+ const receipts = await publishManagedAtoms(engine, session, current, atoms, undefined, retirements);
return { status: 'completed', model_rerun: false, write_requests: receipts };
}
if (!retry.rows.some(row => row.outcome?.failure)) throw new OperationError('invalid_params', 'This failed batch has no malformed extraction to retry.');
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index d0d2c20ada..95cbedb24e 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -141,7 +141,8 @@ async function pageDatabaseOnlyPublication(engine: SqlEngine, row: WriteRequest,
/** Providers and parsing run before the OS lock and before any publication transaction. */
export async function preparePageMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig,
- preparedIntent?: { content: string; expectedRevision: string; tags?: string[] }, signal?: AbortSignal): Promise<PreparedMutation> {
+ preparedIntent?: { content: string; expectedRevision: string; tags?: string[] }, signal?: AbortSignal,
+ options: { allowMissingFile?: boolean } = {}): Promise<PreparedMutation> {
signal?.throwIfAborted();
if (!row.intent) throw new OperationError('storage_error', 'A pending write lost its normalized intent.');
await assertKnowledgePublicationAllowed(engine, row);
@@ -168,7 +169,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
// Tombstones still own their recorded artifact. Purge always attempts its
// removal before the guarded hard-delete and receipt commit; failure rolls
// back to the prior row, and replay survives the eventual absence of that row.
- const file = await prepareFileTarget(engine, row, snapshot, null, undefined, { allowMissing: purge });
+ const file = await prepareFileTarget(engine, row, snapshot, null, undefined, { allowMissing: purge || options.allowMissingFile });
return { observedRevision, noop, file, ...await pageDatabaseOnlyPublication(engine, row, file), apply: async tx => {
if (purge) {
await tx.deletePage(row.slug, source);
@@ -278,7 +279,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
? await prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id) : undefined;
const capture = row.operation === 'capture' && typeof p.capture_path === 'string' && typeof p.capture_file_hash === 'string'
? { path: p.capture_path, hash: p.capture_file_hash } : undefined;
- const file = await prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture });
+ const file = await prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile });
const mintMode = file && !snapshot?.page.source_path ? await scannerSlugRootMode(engine, row.source_id, file.root) : undefined;
const sourcePath = file && mintMode ? scannerSourcePath(file.root, file.path, mintMode) : undefined;
// An inferred mode is pinned with the first origin it mints, so later pages cannot flip the inference (#5610).
diff --git a/test/e2e/managed-extract-atoms.test.ts b/test/e2e/managed-extract-atoms.test.ts
index 7ee891dcd7..82e8c446ce 100644
--- a/test/e2e/managed-extract-atoms.test.ts
+++ b/test/e2e/managed-extract-atoms.test.ts
@@ -1,7 +1,7 @@
import { afterAll, beforeAll, describe, test } from 'bun:test';
import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
-import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManagedAtomBatch, atomAuthorityCases, exerciseManagedAtomAuthority } from '../helpers/managed-atoms-contract.ts';
+import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManagedAtomBatch, atomAuthorityCases, exerciseManagedAtomAuthority, exerciseManagedAtomReconciliation } from '../helpers/managed-atoms-contract.ts';
(process.env.DATABASE_URL ? describe : describe.skip)('managed atom PostgreSQL caller parity', () => {
let fixture: Awaited<ReturnType<typeof isolatedPersistencePostgres>>;
@@ -13,4 +13,5 @@ import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManage
for (const scenario of atomContractCases) test(scenario, () => exerciseManagedAtoms(fixture.engine, scenario), 60_000);
for (const scenario of atomBatchCases) test(`batch ${scenario}`, () => exerciseManagedAtomBatch(fixture.engine, scenario), 60_000);
for (const scenario of atomAuthorityCases) test(`authority ${scenario} rejects normal and dry runs before providers`, () => exerciseManagedAtomAuthority(fixture.engine, scenario), 60_000);
+ test('reconciles stale atom pages and files', () => exerciseManagedAtomReconciliation(fixture.engine), 60_000);
});
diff --git a/test/helpers/managed-atoms-contract.ts b/test/helpers/managed-atoms-contract.ts
index c3b2c0b3eb..c91d21ed75 100644
--- a/test/helpers/managed-atoms-contract.ts
+++ b/test/helpers/managed-atoms-contract.ts
@@ -1,5 +1,5 @@
import { expect } from 'bun:test';
-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../../src/core/engine.ts';
@@ -224,6 +224,76 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):
} finally { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); __setChatTransportForTests(null); rmSync(home, { recursive: true, force: true }); }
}
+export async function exerciseManagedAtomReconciliation(engine: BrainEngine): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-atom-reconcile-'));
+ const root = join(home, 'repo');
+ const sourceId = 'managed-atom-reconcile';
+ const slug = 'notes/example';
+ try {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ const writeSource = async (revision: number) => {
+ const page = await engine.putPage(slug, { type: 'source', title: 'Example', compiled_truth: `A careful project record at revision ${revision}. `.repeat(40) }, { sourceId });
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(page, []));
+ return page;
+ };
+ let page = await writeSource(1);
+ await registerLocalWriter(engine, 'cli');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ let titles = ['Patience compounds', 'Hire slowly'];
+ let calls = 0;
+ const chat = async (): Promise<ChatResult> => {
+ calls++;
+ return {
+ text: JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: `Body for ${title}.` }))),
+ 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',
+ };
+ };
+ const extract = () => runPhaseExtractAtoms(engine, { sourceId, _transcripts: [],
+ _pages: [{ slug, content: page.compiled_truth, contentHash: page.content_hash! }], _chat: chat });
+ expect((await extract()).status).toBe('ok');
+ const first = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id=$1 AND type='atom' AND deleted_at IS NULL ORDER BY slug", [sourceId]);
+ expect(first).toHaveLength(2);
+ const retired = first.find(atom => atom.slug.includes('/patience-compounds-'))!;
+ for (const atom of first) {
+ const path = join(root, `${atom.slug}.md`);
+ expect(existsSync(path)).toBe(true);
+ rmSync(path);
+ }
+ writeFileSync(join(root, `${retired.slug}.md`), 'Uncoordinated operator content.');
+
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ page = await writeSource(2);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ titles = ['Patience compounds over years', 'Hire slowly'];
+ const failed = await extract();
+ expect(failed.status).toBe('warn');
+ expect(calls).toBe(2);
+ const completion = (failed.details?.write_requests as Array<{ request_id: string }>).at(-1)!;
+ rmSync(join(root, `${retired.slug}.md`));
+ await disposePersistenceConsumer(engine);
+ expect(await retryManagedAtomBatch(engine, sourceId, completion.request_id, 'reviewed-retirement')).toMatchObject({ status: 'completed', model_rerun: false });
+ expect(calls).toBe(2);
+
+ const second = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id=$1 AND type='atom' AND deleted_at IS NULL ORDER BY slug", [sourceId]);
+ expect(second).toHaveLength(2);
+ for (const atom of second) expect(existsSync(join(root, `${atom.slug}.md`))).toBe(true);
+ expect(second.map(atom => atom.slug)).not.toContain(retired.slug);
+ expect(existsSync(join(root, `${retired.slug}.md`))).toBe(false);
+ expect((await engine.getPage(retired.slug, { sourceId, includeDeleted: true }))?.deleted_at).not.toBeNull();
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(home, { recursive: true, force: true });
+ }
+}
+
export const atomBatchCases = ['partial_publication', 'missing_after_provenance', 'changed_after_provenance', 'completion_rollback'] as const;
export async function exerciseManagedAtomBatch(engine: BrainEngine, scenario: typeof atomBatchCases[number]): Promise<void> {
@@ -360,7 +430,7 @@ export async function exerciseManagedAtomBatch(engine: BrainEngine, scenario: ty
}
}
-export const atomAuthorityCases = ['remote_job', 'stdio', 'missing_source', 'archived_source', 'missing_owner', 'inactive_owner', 'foreign_owner', 'revoked_writer', 'source_grant', 'read_only_grant', 'operation_grant', 'slug_grant'] as const;
+export const atomAuthorityCases = ['remote_job', 'stdio', 'missing_source', 'archived_source', 'missing_owner', 'inactive_owner', 'foreign_owner', 'revoked_writer', 'source_grant', 'read_only_grant', 'operation_grant', 'delete_operation_grant', 'slug_grant'] as const;
export async function exerciseManagedAtomAuthority(engine: BrainEngine, scenario: typeof atomAuthorityCases[number]): Promise<void> {
const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-atom-authority-'));
@@ -372,7 +442,7 @@ export async function exerciseManagedAtomAuthority(engine: BrainEngine, scenario
await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
await engine.putPage('notes/example', { type: 'source', title: 'Example', compiled_truth: 'A project record. '.repeat(40) }, { sourceId });
const page = (await engine.getPage('notes/example', { sourceId }))!;
- const grant: LocalGrant = { sourceIds: scenario === 'source_grant' ? ['another-source'] : ['*'], operations: scenario === 'operation_grant' ? ['submit_job'] : null,
+ const grant: LocalGrant = { sourceIds: scenario === 'source_grant' ? ['another-source'] : ['*'], operations: scenario === 'operation_grant' ? ['submit_job'] : scenario === 'delete_operation_grant' ? ['submit_job', 'put_page'] : null,
scopes: scenario === 'read_only_grant' ? ['read'] : ['read', 'write'], slugPrefixes: scenario === 'slug_grant' ? ['atoms/'] : null };
const registration = await registerLocalWriter(engine, scenario === 'stdio' ? 'stdio' : 'cli', grant);
if (scenario.endsWith('_owner')) {
diff --git a/test/managed-extract-atoms.test.ts b/test/managed-extract-atoms.test.ts
index fdfa7f1e8d..f79772faaa 100644
--- a/test/managed-extract-atoms.test.ts
+++ b/test/managed-extract-atoms.test.ts
@@ -9,7 +9,7 @@ import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';
import { stopPersistenceConsumer } from '../src/core/persistence/service.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { withEnv } from './helpers/with-env.ts';
-import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManagedAtomBatch, atomAuthorityCases, exerciseManagedAtomAuthority } from './helpers/managed-atoms-contract.ts';
+import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManagedAtomBatch, atomAuthorityCases, exerciseManagedAtomAuthority, exerciseManagedAtomReconciliation } from './helpers/managed-atoms-contract.ts';
let engine: PGLiteEngine;
beforeAll(async () => {
@@ -52,3 +52,5 @@ test('managed public atom extraction publishes searchable atoms and replays with
});
} finally { await stopPersistenceConsumer(engine); rmSync(home, { recursive: true, force: true }); }
}, 60_000);
+
+test('managed extraction retires stale atom pages and files after a source edit', () => exerciseManagedAtomReconciliation(engine), 60_000);