Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(atoms): mark retirements, restore retired slugs, regenerate after retirement (#5770)

garrytan6d250e714ced
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index ed591c8044..18df314b08 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -15,6 +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. A completion that retired atoms bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the run key only above 0) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints, so an A→B→A edit re-extracts instead of replaying a retained receipt.
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/runtime.md b/docs/architecture/key-files/runtime.md
index 9e274b3918..932ccab6ee 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.
-- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten.
+- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten.
- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`).
diff --git a/src/core/op-checkpoint.ts b/src/core/op-checkpoint.ts
index 9ef9c491d4..3e75f3d0bd 100644
--- a/src/core/op-checkpoint.ts
+++ b/src/core/op-checkpoint.ts
@@ -498,7 +498,7 @@ export async function purgeStaleCheckpoints(
`WITH deleted AS (
DELETE FROM op_checkpoints
WHERE updated_at < now() - ($1 || ' days')::interval
- AND op NOT IN ('managed-atoms','managed-connector','managed-connector-retry','managed-connector-state','managed-connector-migration')
+ AND op NOT IN ('managed-atoms','managed-atoms-generation','managed-connector','managed-connector-retry','managed-connector-state','managed-connector-migration')
AND NOT (op='managed-sync' AND (COALESCE(completed_keys->0->>'done','false')<>'true' OR EXISTS (
SELECT 1 FROM op_checkpoints f WHERE f.op='managed-sync-failure' AND f.fingerprint=op_checkpoints.fingerprint)))
AND op<>'managed-sync-failure'
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index d5000445a1..33ad970a99 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -26,6 +26,7 @@ export interface AtomOrigin {
pageId: number | null;
revision: string | null;
visibility: 'private' | 'world';
+ generation?: number;
}
export interface ManagedAtomSession {
sourceId: string;
@@ -119,8 +120,34 @@ export async function readAtomOrigin(engine: BrainEngine, session: ManagedAtomSe
if (!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);
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 }) };
+ revision: snapshot.revision, visibility: effectiveVisibility({ kind: 'page', page: snapshot.page }), ...(generation > 0 ? { generation } : {}) };
+}
+
+export 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);
+}
+
+/**
+ * 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.
+ */
+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)
+ 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)]);
+ 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'=$1
+ AND completed_keys->0->>'kind'='page' AND completed_keys->0->>'pageId'=$2 AND completed_keys->0->>'contentHash' IS DISTINCT FROM $3::text`,
+ [sourceId, String(pageId), keepContentHash]);
}
/**
@@ -129,7 +156,8 @@ export async function readAtomOrigin(engine: BrainEngine, session: ManagedAtomSe
* the drain and for an explicit retry (#5699).
*/
function atomInputKey(session: ManagedAtomSession, origin: AtomOrigin): string {
- return digest(['managed-atoms-v1', session.incarnation, origin.kind, origin.locator, origin.pageId, origin.contentHash]);
+ return digest(['managed-atoms-v1', session.incarnation, origin.kind, origin.locator, origin.pageId, origin.contentHash,
+ ...(origin.generation ? [origin.generation] : [])]);
}
/** The retry check adds the extracted text's hash: a transcript retry reads the current file under the retained content hash. */
@@ -218,7 +246,7 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA
for (const atom of atoms) {
await authorizeWrite(engine, session.authority, 'put_page', atom.slug);
const snapshot = await engine.readPageSnapshot(atom.slug, { sourceId: session.sourceId, includeDeleted: true });
- if (snapshot && (snapshot.page.deleted_at || snapshot.page.type !== 'atom' ||
+ if (snapshot && ((snapshot.page.deleted_at && !snapshot.page.frontmatter.retired_by) || snapshot.page.type !== 'atom' ||
(origin.kind === 'page' ? snapshot.page.frontmatter.source_slug !== origin.locator : snapshot.page.frontmatter.source_path !== origin.locator))) {
throw new OperationError('page_identity_changed', 'The atom target belongs to another origin or was removed.');
}
@@ -304,7 +332,14 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
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 }) };
+ }, apply: async tx => {
+ const result = await prepared.apply(tx);
+ if (!prepared.noop) {
+ await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
+ WHERE id=$3 AND source_id=$4 AND deleted_at IS NOT NULL`, [ATOM_RETIRED_BY_REEXTRACT, new Date().toISOString(), row.page_id, row.source_id]);
+ }
+ return { ...result, 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',
@@ -340,9 +375,13 @@ 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.');
}
+ const retired = committed.filter(child => child.kind === 'managed_atom_delete').length;
+ if (retired && p.origin.kind === 'page' && p.origin.pageId !== null) {
+ await bumpAtomGeneration(tx, row.source_id, row.source_incarnation, p.origin.pageId, p.origin.contentHash);
+ }
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,
+ retired,
...(p.failure ? { failure: p.failure } : {}) };
} };
}
diff --git a/test/e2e/managed-extract-atoms.test.ts b/test/e2e/managed-extract-atoms.test.ts
index 82e8c446ce..667d5a004f 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, exerciseManagedAtomReconciliation } from '../helpers/managed-atoms-contract.ts';
+import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManagedAtomBatch, atomAuthorityCases, exerciseManagedAtomAuthority, exerciseManagedAtomReconciliation, atomRetirementCases, exerciseManagedAtomRetirement } from '../helpers/managed-atoms-contract.ts';
(process.env.DATABASE_URL ? describe : describe.skip)('managed atom PostgreSQL caller parity', () => {
let fixture: Awaited<ReturnType<typeof isolatedPersistencePostgres>>;
@@ -14,4 +14,5 @@ import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManage
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);
+ for (const scenario of atomRetirementCases) test(`retirement ${scenario}`, () => exerciseManagedAtomRetirement(fixture.engine, scenario), 60_000);
});
diff --git a/test/helpers/managed-atoms-contract.ts b/test/helpers/managed-atoms-contract.ts
index c91d21ed75..5ba19d2674 100644
--- a/test/helpers/managed-atoms-contract.ts
+++ b/test/helpers/managed-atoms-contract.ts
@@ -14,7 +14,7 @@ import { retryManagedAtomBatch } from '../../src/core/persistence/atom-retry.ts'
import type { WriteRequest } from '../../src/core/persistence/model.ts';
import { withSubmissionAuthority } from '../../src/core/minions/submission-authority.ts';
import { serializePageToMarkdown } from '../../src/core/markdown.ts';
-import { sha256 } from '../../src/core/persistence/digest.ts';
+import { digest, sha256 } from '../../src/core/persistence/digest.ts';
import { purgeStaleCheckpoints } from '../../src/core/op-checkpoint.ts';
import { __setChatTransportForTests } from '../../src/core/ai/gateway.ts';
import { MinionWorker } from '../../src/core/minions/worker.ts';
@@ -294,6 +294,135 @@ export async function exerciseManagedAtomReconciliation(engine: BrainEngine): Pr
}
}
+export const atomRetirementCases = ['marker_and_republish', 'edit_back', 'user_deleted', 'prefix_pin', 'generation_key_and_purge'] as const;
+
+/** #5770 / ENG-O7: retirement markers, republication of retired slugs, the regeneration generation and its purge exclusion. */
+export async function exerciseManagedAtomRetirement(engine: BrainEngine, scenario: typeof atomRetirementCases[number]): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-atom-retire-'));
+ const root = join(home, 'repo');
+ const sourceId = `atom-retire-${scenario.replaceAll('_', '-')}`;
+ const slug = 'notes/example';
+ const bodies = ['A careful project record at revision one. ', 'A careful project record at revision two. ', 'A careful project record at revision three. ']
+ .map(line => line.repeat(40));
+ const unmanaged = async <T>(fn: () => Promise<T>): Promise<T> => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try { return await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+ };
+ const atomsOf = async () => engine.executeRaw<{ slug: string; deleted: boolean; frontmatter: Record<string, unknown> }>(
+ `SELECT slug, deleted_at IS NOT NULL AS deleted, frontmatter FROM pages WHERE source_id=$1 AND type='atom' ORDER BY slug`, [sourceId]);
+ const atom = async (title: string) => (await atomsOf()).find(row => row.slug.includes(`/${title}-`));
+ try {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ const writeSource = async (body: string) => {
+ const written = await engine.putPage(slug, { type: 'source', title: 'Example', compiled_truth: body }, { sourceId });
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(written, []));
+ return written;
+ };
+ let page = await writeSource(bodies[0]);
+ 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 });
+ const edit = async (body: string, next: string[]) => { page = await unmanaged(() => writeSource(body)); titles = next; };
+ expect((await extract()).status).toBe('ok');
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ const generation = async () => (await engine.executeRaw<{ generation: string }>(
+ "SELECT completed_keys->0->>'generation' AS generation FROM op_checkpoints WHERE op='managed-atoms-generation' AND fingerprint=$1", [String(page.id)]))[0]?.generation;
+
+ if (scenario === 'marker_and_republish') {
+ await edit(bodies[1], ['Patience compounds over years', 'Hire slowly']);
+ expect((await extract()).status).toBe('ok');
+ const retired = (await atom('patience-compounds'))!;
+ expect(retired.deleted).toBe(true);
+ expect(retired.frontmatter.retired_by).toBe('managed-reextract');
+ expect(Number.isNaN(Date.parse(String(retired.frontmatter.retired_at)))).toBe(false);
+ expect(existsSync(join(root, `${retired.slug}.md`))).toBe(false);
+ await edit(bodies[2], ['Patience compounds', 'Hire slowly']);
+ expect((await extract()).status).toBe('ok');
+ const restored = (await atom('patience-compounds'))!;
+ expect(restored.slug).toBe(retired.slug);
+ expect(restored.deleted).toBe(false);
+ expect(restored.frontmatter).not.toHaveProperty('retired_by');
+ expect(existsSync(join(root, `${restored.slug}.md`))).toBe(true);
+ expect((await atom('patience-compounds-over-years'))?.deleted).toBe(true);
+ expect(calls).toBe(3);
+ }
+
+ if (scenario === 'edit_back') {
+ const first = (await atom('patience-compounds'))!;
+ await edit(bodies[1], ['Patience compounds over years', 'Hire slowly']);
+ expect((await extract()).status).toBe('ok');
+ expect((await atom('patience-compounds'))?.deleted).toBe(true);
+ expect(await generation()).toBe('1');
+ await edit(bodies[0], ['Patience compounds', 'Hire slowly']);
+ expect((await discoverExtractablePages(engine, sourceId)).map(item => item.slug)).toEqual([slug]);
+ expect((await extract()).status).toBe('ok');
+ expect(calls).toBe(3);
+ const back = (await atom('patience-compounds'))!;
+ expect(back).toMatchObject({ slug: first.slug, deleted: false });
+ expect((await atom('patience-compounds-over-years'))?.deleted).toBe(true);
+ expect(await discoverExtractablePages(engine, sourceId)).toEqual([]);
+ }
+
+ if (scenario === 'user_deleted') {
+ const removed = (await atom('patience-compounds'))!;
+ await unmanaged(() => engine.softDeletePage(removed.slug, { sourceId }));
+ await edit(bodies[1], ['Patience compounds', 'Hire slowly']);
+ expect((await extract()).status).not.toBe('ok');
+ const after = (await atom('patience-compounds'))!;
+ expect(after.deleted).toBe(true);
+ expect(after.frontmatter).not.toHaveProperty('retired_by');
+ }
+
+ if (scenario === 'prefix_pin') {
+ const next = await unmanaged(async () => {
+ const written = await writeSource(bodies[1]);
+ for (const [name, hash] of [['legacy-prefix', written.content_hash!.slice(0, 16)], ['legacy-full', written.content_hash!]] as const) {
+ await engine.putPage(`atoms/2026-01-01/${name}`, { type: 'atom', title: name, compiled_truth: `Legacy atom ${name}.`,
+ frontmatter: { source_slug: slug, source_hash: hash } }, { sourceId });
+ }
+ return written;
+ });
+ page = next;
+ titles = ['Patience compounds', 'Hire slowly'];
+ expect((await extract()).status).toBe('ok');
+ expect((await atomsOf()).find(row => row.slug.endsWith('/legacy-prefix'))?.deleted).toBe(false);
+ expect((await atomsOf()).find(row => row.slug.endsWith('/legacy-full'))?.deleted).toBe(true);
+ }
+
+ if (scenario === 'generation_key_and_purge') {
+ const legacyKey = digest(['managed-atoms-v1', incarnation, 'page', slug, page.id, page.content_hash]);
+ expect((await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-atoms' AND fingerprint=$1", [legacyKey]))).toHaveLength(1);
+ expect(await generation()).toBeUndefined();
+ await edit(bodies[1], ['Patience compounds over years', 'Hire slowly']);
+ expect((await extract()).status).toBe('ok');
+ expect(await generation()).toBe('1');
+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now() - interval '30 days' WHERE op IN ('managed-atoms-generation','managed-atoms')");
+ await purgeStaleCheckpoints(engine, 7);
+ expect(await generation()).toBe('1');
+ }
+ });
+ } 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> {
diff --git a/test/managed-extract-atoms.test.ts b/test/managed-extract-atoms.test.ts
index f79772faaa..e0b74a4d88 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, exerciseManagedAtomReconciliation } from './helpers/managed-atoms-contract.ts';
+import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManagedAtomBatch, atomAuthorityCases, exerciseManagedAtomAuthority, exerciseManagedAtomReconciliation, atomRetirementCases, exerciseManagedAtomRetirement } from './helpers/managed-atoms-contract.ts';
let engine: PGLiteEngine;
beforeAll(async () => {
@@ -54,3 +54,4 @@ test('managed public atom extraction publishes searchable atoms and replays with
}, 60_000);
test('managed extraction retires stale atom pages and files after a source edit', () => exerciseManagedAtomReconciliation(engine), 60_000);
+for (const scenario of atomRetirementCases) test(`managed atom retirement ${scenario}`, () => exerciseManagedAtomRetirement(engine, scenario), 60_000);