Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-161 PR 1a (wip): g1 generation and atom probes
garrytan3dd30336d8c7
diff --git a/src/core/generations/publish.ts b/src/core/generations/publish.tsindex aae0bda9b4..03314adb18 100644--- a/src/core/generations/publish.ts+++ b/src/core/generations/publish.ts@@ -85,13 +85,13 @@ export async function activateGeneration(tx: BrainEngine, key: GenerationKey, liif (live) await tx.executeRaw(`UPDATE derived_generations SET state='superseded', updated_at=now() WHERE id=$1 AND state='live'`, [live.id]);const [created] = await tx.executeRaw<{ id: number }>(`INSERT INTO derived_generations (source_id, kind, owner_key, generation, state, run_id, operation_id, input_pin, input_size, completeness, item_set_hash, restore_of)- VALUES ($1,$2,$3,$4,'live',$5,$6,$7,$8,$9::jsonb,$10,$11) RETURNING id`,+ VALUES ($1,$2,$3,$4,'live',$5,$6,$7,$8,$9::text::jsonb,$10,$11) RETURNING id`,[key.sourceId, key.kind, key.ownerKey, generation, row.runId ?? null, row.operationId, row.input?.pin ?? null, row.input?.size ?? null,JSON.stringify(row.completeness), row.setHash, row.restoreOf ?? null]);const id = Number(created!.id);if (live) await tx.executeRaw('UPDATE derived_generations SET superseded_by=$1 WHERE id=$2', [id, live.id]);for (const item of items) {- await tx.executeRaw(`INSERT INTO derived_generation_items (generation_id, item_key, identity_hash, action, preimage, preimage_bytes) VALUES ($1,$2,$3,$4,$5::jsonb,$6)`,+ await tx.executeRaw(`INSERT INTO derived_generation_items (generation_id, item_key, identity_hash, action, preimage, preimage_bytes) VALUES ($1,$2,$3,$4,$5::text::jsonb,$6)`,[id, item.key, item.identityHash, item.action, item.preimage?.json ? JSON.stringify(item.preimage.json) : null, item.preimage?.bytes ?? null]);}await tx.executeRaw(`DELETE FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held'`, [key.sourceId, key.kind, key.ownerKey]);@@ -124,7 +124,7 @@ async function recordHeld(tx: BrainEngine, key: GenerationKey, config: Generatioawait tx.executeRaw(`INSERT INTO derived_generations (source_id, kind, owner_key, generation, state, run_id, operation_id, hold_id, input_pin, input_size, item_set_hash,held_reason, held_context, proposal, proposal_bytes, attempts)- VALUES ($1,$2,$3,0,'held',$4,$5,$6,$7,$8,$9,$10,$11::jsonb,$12::jsonb,$13,1)`,+ VALUES ($1,$2,$3,0,'held',$4,$5,$6,$7,$8,$9,$10,$11::text::jsonb,$12::text::jsonb,$13,1)`,[key.sourceId, key.kind, key.ownerKey, request.runId ?? null, `held:${holdId}`, holdId, request.input?.pin ?? null, request.input?.size ?? null, setHash,reason, JSON.stringify({ ...context, partial: request.partial === true }), bytes <= HELD_PROPOSAL_MAX_BYTES ? JSON.stringify(proposal) : null, bytes]);return { state: 'held', reason, holdId, context };diff --git a/src/core/generations/repair.ts b/src/core/generations/repair.tsindex 2b0adf7dba..c554f62ee0 100644--- a/src/core/generations/repair.ts+++ b/src/core/generations/repair.ts@@ -178,6 +178,7 @@ type Approved = Entry & { selection: GenerationsSelection; sources: string[] };export const generationsRepair: RepairHandler = {kind: 'generations',+ publication: 'projection',embeds: true,outcomeItemsLimit: 1000,async plan(engine, scope, after, opts): Promise<RepairPlan> {diff --git a/test/helpers/synthetic-generation.ts b/test/helpers/synthetic-generation.tsnew file mode 100644index 0000000000..55d68ea7dc--- /dev/null+++ b/test/helpers/synthetic-generation.ts@@ -0,0 +1,47 @@+/**+ * GBRA-161: a synthetic generation kind for the primitive's tests. Its items are pages carrying+ * `synthetic_owner: <owner key>`; its input is whatever the test last set for the key (`setSyntheticInput`), so a test+ * can move the input under a producer. Retirements carry the extract-atoms stamp, so the derived purge hold applies.+ */+import type { BrainEngine } from '../../src/core/engine.ts';+import type { GenerationAdapter, GenerationKey, InputState, ProposedItem } from '../../src/core/generations/contract.ts';+import { registerGenerationAdapter } from '../../src/core/generations/adapters/index.ts';+import { importPageItem, markdownItem, pageItemRow, pageVersionEvidence, preimageIdentity, preimageMarkdown, readPageRows } from '../../src/core/generations/adapters/page.ts';+import { retireDerivedPagesInTransaction } from '../../src/core/persistence/derived-retirement-hold.ts';+import { serializeMarkdown } from '../../src/core/markdown.ts';++export const SYNTHETIC_KIND = 'synthetic';+const inputs = new Map<string, InputState>();++export function setSyntheticInput(key: GenerationKey, input: InputState | null): void {+ if (input) inputs.set(`${key.sourceId}:${key.ownerKey}`, input); else inputs.delete(`${key.sourceId}:${key.ownerKey}`);+}++export const syntheticAdapter: GenerationAdapter<undefined> = {+ kind: SYNTHETIC_KIND,+ retiredBy: 'extract-atoms',+ modelProduced: true,+ lockKeys: (key, itemKeys) => itemKeys.map(slug => ({ sourceId: key.sourceId, slug })),+ readInput: async (_engine, key) => inputs.get(`${key.sourceId}:${key.ownerKey}`) ?? null,+ async readItems(engine, key, itemKeys) {+ const rows = await readPageRows(engine, key.sourceId, `p.slug = ANY($2::text[]) OR (p.deleted_at IS NULL AND p.frontmatter->>'synthetic_owner' = $3)`, [[...itemKeys], key.ownerKey]);+ return new Map(rows.map(row => [row.slug, pageItemRow(row, row.frontmatter?.synthetic_owner === key.ownerKey)]));+ },+ legacyEvidence: (engine, key, rows) => pageVersionEvidence(engine, key.sourceId, rows, "v.frontmatter->>'synthetic_producer' = 'synthetic'"),+ async publishItems(tx, key, items) { for (const item of items) await importPageItem(tx, key.sourceId, item.key, item.content); },+ retireItems: (tx, key, itemKeys, retiredBy) => retireDerivedPagesInTransaction(tx, key.sourceId, itemKeys, retiredBy),+ restoreItem: (tx, key, itemKey, preimage) => importPageItem(tx, key.sourceId, itemKey, preimageMarkdown(preimage)),+ preimageIdentity,+};+registerGenerationAdapter(syntheticAdapter as GenerationAdapter<unknown>);++/** One proposed synthetic item: a note page owned by `ownerKey` with this body. */+export function syntheticItem(ownerKey: string, slug: string, body: string): ProposedItem {+ return markdownItem(slug, serializeMarkdown({ synthetic_owner: ownerKey, synthetic_producer: 'synthetic' }, body, '', { type: 'note', title: slug.split('/').pop()!, tags: [] }));+}++export const syntheticKey = (sourceId: string, ownerKey: string): GenerationKey => ({ kind: SYNTHETIC_KIND, sourceId, ownerKey });++export async function liveSlugs(engine: BrainEngine, ownerKey: string): Promise<string[]> {+ return (await engine.executeRaw<{ slug: string }>(`SELECT slug FROM pages WHERE deleted_at IS NULL AND frontmatter->>'synthetic_owner' = $1 ORDER BY slug`, [ownerKey])).map(row => row.slug);+}diff --git a/test/pathological/g1-atom-generations.test.ts b/test/pathological/g1-atom-generations.test.tsnew file mode 100644index 0000000000..44c574fb3a--- /dev/null+++ b/test/pathological/g1-atom-generations.test.ts@@ -0,0 +1,105 @@+/**+ * GBRA-161 PR 1a: unmanaged extract_atoms publishes each item's atoms as one generation.+ *+ * Protects: (a) a failed publication (here the provenance edges) writes no atom at all, provisional or final, and the+ * retry publishes the atoms, their edges and the completion stamp together; (b) a re-extraction that keeps one of four+ * atoms is held `shrunk` and the four stay live (pre-fix: three were retired on a model's say-so); (c) an atom naming+ * the origin with no retained extractor evidence (a hand-written or hand-edited one) is protected, not retired.+ * Fails when: the atom loop writes outside the generation transaction, or retirement ignores the floor or ownership.+ * Seams: the extract_atoms phase's `_pages` / `_transcripts` / `_chat` inputs (no paid call). PGLite always,+ * Postgres when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';+import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { pathologicalArms } from './harness.ts';++const chat = (titles: string[]) => async (_o: ChatOpts): Promise<ChatResult> => {+ const text = JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: `${title} body.` })));+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 } };+};++async function withBrain(databaseUrl: string | undefined, run: (engine: BrainEngine) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-g1a-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ await run(engine);+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++const FILE = '/fake/2026-09-07-meeting.txt';+const extractTranscript = (engine: BrainEngine, titles: string[], hash: string) => runPhaseExtractAtoms(engine, {+ _transcripts: [{ filePath: FILE, content: `content ${hash}`, contentHash: hash }], _pages: [], _chat: chat(titles) });+const liveAtoms = async (engine: BrainEngine) => (await engine.executeRaw<{ slug: string }>(+ "SELECT slug FROM pages WHERE type='atom' AND deleted_at IS NULL ORDER BY slug")).map(row => row.slug);++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`GBRA-161 unmanaged atoms publish as one generation (${backend})`, () => {+ test('a failed provenance write leaves no atom row; the retry publishes atoms, edges and completion together', async () => {+ await withBrain(databaseUrl, async engine => {+ const source = 'meetings/2026-09-07-source-a';+ const content = 'A source page with two careful claims about shipping.';+ await engine.putPage(source, { type: 'meeting', title: 'Source A', compiled_truth: content, timeline: '' });+ const [stored] = await engine.executeRaw<{ content_hash: string }>('SELECT content_hash FROM pages WHERE slug=$1', [source]);+ const pages = [{ slug: source, content, contentHash: stored!.content_hash }];+ const links = engine.addLinksBatch;+ engine.addLinksBatch = async function (this: BrainEngine, ...args: Parameters<typeof links>) {+ throw new Error('synthetic provenance failure');+ };+ try {+ const failed = await runPhaseExtractAtoms(engine, { _transcripts: [], _pages: pages, _chat: chat(['Ship smaller', 'Measure first']) });+ expect(failed.status).toBe('warn');+ } finally { engine.addLinksBatch = links; }+ expect(await engine.executeRaw("SELECT slug FROM pages WHERE type='atom'")).toEqual([]);+ const retry = await runPhaseExtractAtoms(engine, { _transcripts: [], _pages: pages, _chat: chat(['Ship smaller', 'Measure first']) });+ expect(retry.status).toBe('ok');+ const hashes = await engine.executeRaw<{ hash: string }>("SELECT frontmatter->>'source_hash' AS hash FROM pages WHERE type='atom' AND deleted_at IS NULL");+ expect(hashes.map(row => row.hash)).toEqual([stored!.content_hash.slice(0, 16), stored!.content_hash.slice(0, 16)]);+ expect((await engine.getLinks(source)).filter(link => link.link_source === 'atom-provenance')).toHaveLength(2);+ });+ }, 120_000);++ test('a re-extraction that keeps one of four atoms is held shrunk and the four stay live', async () => {+ await withBrain(databaseUrl, async engine => {+ await extractTranscript(engine, ['Ship smaller', 'Measure first', 'Hire slowly', 'Write it down'], 'a'.repeat(64));+ const before = await liveAtoms(engine);+ expect(before).toHaveLength(4);+ const lines: string[] = [];+ const log = console.error;+ console.error = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };+ try { await extractTranscript(engine, ['Ship smaller'], 'b'.repeat(64)); } finally { console.error = log; }+ expect(await liveAtoms(engine)).toEqual(before);+ expect(lines.some(line => line.includes('result held (shrunk)') && line.includes('gbrain repair generations --kind atom --mode release-held'))).toBe(true);+ const [held] = await engine.executeRaw<{ held_reason: string }>("SELECT held_reason FROM derived_generations WHERE state='held'");+ expect(held?.held_reason).toBe('shrunk');+ });+ }, 120_000);++ test('an atom naming the origin without retained extractor evidence is protected, not retired', async () => {+ await withBrain(databaseUrl, async engine => {+ const hand = 'atoms/2026-09-07/hand-written-example';+ await engine.putPage(hand, { type: 'atom', title: 'Hand written', compiled_truth: 'A claim the user wrote by hand.', timeline: '',+ frontmatter: { source_path: FILE, source_hash: 'earlier000000000', atom_type: 'insight' } });+ await extractTranscript(engine, ['Ship smaller'], 'c'.repeat(64));+ const live = await liveAtoms(engine);+ expect(live).toContain(hand);+ expect(live).toHaveLength(2);+ });+ }, 120_000);+ });+}diff --git a/test/pathological/g1-generations.test.ts b/test/pathological/g1-generations.test.tsnew file mode 100644index 0000000000..12a0d831bb--- /dev/null+++ b/test/pathological/g1-generations.test.ts@@ -0,0 +1,229 @@+/**+ * GBRA-161 PR 1a: the generation primitive and `gbrain repair generations`.+ *+ * Protects: a derived result replaces the live generation only whole and only when it may: a complete successor retires+ * what it dropped (versioned, stamped, preimage on the ledger) in the transaction that activates it; a shrink below the+ * floor, an empty result without proof, an oversize result and a stale or moved producer are held or fenced with nothing+ * retired; an identical replay is a no-op; an unrecorded row naming the key is retired only on retained producer+ * evidence; restore republishes the replaced generation and refuses an item edited since; release-held publishes a held+ * result once and refuses one that lacks proof; purge scrubs ledger copies; every printed preview command parses.+ * Fails when: any retirement happens outside a complete activation, or the repair writes more or other than its preview.+ * Seams: a synthetic page kind (test/helpers/synthetic-generation.ts) whose input the test sets. PGLite always, Postgres+ * when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { OperationError } from '../../src/core/ops/contract.ts';+import { publishGeneration, heldForInput } from '../../src/core/generations/publish.ts';+import { originGone } from '../../src/core/generations/proofs.ts';+import { generationsPreviewArgv, type GenerationsSelection } from '../../src/core/generations/repair.ts';+import { resolveRepairScope, type RepairResult } from '../../src/core/repair/core.ts';+import { repairPreviewCommand, repairRunner } from '../../src/core/repair/registry.ts';+import { parseRepairArgs } from '../../src/commands/repair.ts';+import { generationHeldCheck, generationRetirementsCheck } from '../../src/commands/doctor/checks/generations.ts';+import { managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { liveSlugs, setSyntheticInput, syntheticAdapter, syntheticItem, syntheticKey } from '../helpers/synthetic-generation.ts';+import { pathologicalArms } from './harness.ts';++const OWNER = 'owner:notes/source-a';+const key = syntheticKey('default', OWNER);+const slug = (name: string) => `derived/${name}`;+const items = (spec: Record<string, string>) => Object.entries(spec).map(([name, body]) => syntheticItem(OWNER, slug(name), body));+const input = (pin: string, size = 100) => ({ pin, size });++async function withBrain(databaseUrl: string | undefined, run: (engine: BrainEngine) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-g1-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ await run(engine);+ } finally { await close(); setSyntheticInput(key, null); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++async function publish(engine: BrainEngine, spec: Record<string, string>, pin: string, extra: Partial<Parameters<typeof publishGeneration>[2]> = {}) {+ setSyntheticInput(key, input(pin));+ return publishGeneration(engine, syntheticAdapter, { key, items: items(spec), input: input(pin), ...extra });+}++const FOUR = { a: 'Alpha claim.', b: 'Beta claim.', c: 'Gamma claim.', d: 'Delta claim.' };++async function repair(engine: BrainEngine, selection: GenerationsSelection, expect?: string): Promise<RepairResult> {+ const scope = await resolveRepairScope(engine, 'default');+ const quiet = { info: () => {}, warn: () => {}, error: () => {} };+ return (await repairRunner(engine, { apply: expect !== undefined, noEmbed: true, logger: quiet })).run('generations', scope,+ { explicit: true, sourceFlag: 'default', generations: selection, ...(expect ? { expect } : {}) });+}++const retiredBy = async (engine: BrainEngine, name: string) => (await engine.executeRaw<{ deleted: boolean; retired_by: string | null }>(+ "SELECT deleted_at IS NOT NULL AS deleted, frontmatter->>'retired_by' AS retired_by FROM pages WHERE slug=$1", [slug(name)]))[0];+const body = async (engine: BrainEngine, name: string) => (await engine.executeRaw<{ compiled_truth: string }>('SELECT compiled_truth FROM pages WHERE slug=$1', [slug(name)]))[0]?.compiled_truth;++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`GBRA-161 generation primitive (${backend})`, () => {+ test('a complete successor retires what it dropped, versioned and stamped, with its preimage on the ledger', async () => {+ await withBrain(databaseUrl, async engine => {+ const first = await publish(engine, FOUR, 'pin-1');+ expect(first).toMatchObject({ state: 'published', generation: 1 });+ const second = await publish(engine, { a: 'Alpha claim.', b: 'Beta claim.', c: 'Gamma claim.' }, 'pin-2');+ expect(second).toMatchObject({ state: 'published', generation: 2, retired: [slug('d')] });+ expect(await liveSlugs(engine, OWNER)).toEqual([slug('a'), slug('b'), slug('c')]);+ expect(await retiredBy(engine, 'd')).toEqual({ deleted: true, retired_by: 'extract-atoms' });+ const [ledger] = await engine.executeRaw<{ action: string; has_preimage: boolean }>(`SELECT i.action, i.preimage IS NOT NULL AS has_preimage+ FROM derived_generation_items i JOIN derived_generations g ON g.id=i.generation_id WHERE g.state='live' AND i.item_key=$1`, [slug('d')]);+ expect(ledger).toEqual({ action: 'retired', has_preimage: true });+ expect((await generationRetirementsCheck(engine, ['default'])).details).toMatchObject({ items: 1, keys: 1 });+ });+ }, 120_000);++ test('a shrink below the floor is held with nothing retired, and the same input is not recomputed', async () => {+ await withBrain(databaseUrl, async engine => {+ await publish(engine, FOUR, 'pin-1');+ const held = await publish(engine, { a: 'Alpha claim.' }, 'pin-2');+ expect(held).toMatchObject({ state: 'held', reason: 'shrunk' });+ expect(await liveSlugs(engine, OWNER)).toEqual([slug('a'), slug('b'), slug('c'), slug('d')]);+ expect(await heldForInput(engine, key, 'pin-2')).toBe(true);+ const check = await generationHeldCheck(engine, ['default']);+ expect(check.status).toBe('warn');+ expect(check.fix?.argv).toEqual(generationsPreviewArgv({ kind: 'synthetic', sourceId: 'default' }, 'release-held'));+ });+ }, 120_000);++ test('an empty result retires nothing without proof; originGone retires the generation once the input is gone', async () => {+ await withBrain(databaseUrl, async engine => {+ await publish(engine, { a: 'Alpha claim.' }, 'pin-1');+ expect(await publish(engine, {}, 'pin-2')).toMatchObject({ state: 'held', reason: 'no_proof' });+ expect(await liveSlugs(engine, OWNER)).toEqual([slug('a')]);+ setSyntheticInput(key, null);+ const gone = await publishGeneration(engine, syntheticAdapter, { key, items: [], proof: originGone() });+ expect(gone).toMatchObject({ state: 'published', retired: [slug('a')] });+ expect(await liveSlugs(engine, OWNER)).toEqual([]);+ });+ }, 120_000);++ test('a result past generations.max_items is held oversize', async () => {+ await withBrain(databaseUrl, async engine => {+ await engine.setConfig('generations.max_items', '8');+ const nine = Object.fromEntries(Array.from({ length: 9 }, (_, i) => [`n${i}`, `Claim number ${i}.`]));+ expect(await publish(engine, nine, 'pin-1')).toMatchObject({ state: 'held', reason: 'oversize' });+ expect(await liveSlugs(engine, OWNER)).toEqual([]);+ });+ }, 120_000);++ test('a stale or moved producer is fenced and writes nothing; an identical replay changes nothing', async () => {+ await withBrain(databaseUrl, async engine => {+ await publish(engine, { a: 'Alpha claim.' }, 'pin-1');+ const stale = await publish(engine, { b: 'Beta claim.' }, 'pin-1', { expectedGeneration: 0 }).catch(error => error);+ expect(stale).toBeInstanceOf(OperationError);+ expect((stale as OperationError).code).toBe('generation_fenced');+ setSyntheticInput(key, input('pin-moved'));+ const moved = await publishGeneration(engine, syntheticAdapter, { key, items: items({ b: 'Beta claim.' }), input: input('pin-1') }).catch(error => error);+ expect((moved as OperationError).code).toBe('generation_fenced');+ expect(await liveSlugs(engine, OWNER)).toEqual([slug('a')]);+ const replay = await publish(engine, { a: 'Alpha claim.' }, 'pin-1');+ expect(replay.state).toBe('unchanged');+ expect((await engine.executeRaw('SELECT 1 FROM derived_generations')).length).toBe(1);+ });+ }, 120_000);++ test('an unrecorded row naming the key is protected without producer evidence and retired with it', async () => {+ await withBrain(databaseUrl, async engine => {+ await engine.putPage(slug('hand'), { type: 'note', title: 'hand', compiled_truth: 'A hand-written note.', frontmatter: { synthetic_owner: OWNER } });+ await engine.putPage(slug('legacy'), { type: 'note', title: 'legacy', compiled_truth: 'An older derived claim.', frontmatter: { synthetic_owner: OWNER, synthetic_producer: 'synthetic' } });+ await engine.createVersion(slug('legacy'), { sourceId: 'default' });+ await engine.setConfig('generations.shrink_floor', '0.05');+ const outcome = await publish(engine, { a: 'Alpha claim.' }, 'pin-1');+ expect(outcome).toMatchObject({ state: 'published', retired: [slug('legacy')], protected: [slug('hand')] });+ expect(await liveSlugs(engine, OWNER)).toEqual([slug('a'), slug('hand')]);+ });+ }, 120_000);++ test('restore republishes the replaced generation from the preview it bound, retiring what the generation added', async () => {+ await withBrain(databaseUrl, async engine => {+ await publish(engine, FOUR, 'pin-1');+ await publish(engine, { a: 'Alpha claim, revised.', b: 'Beta claim.', c: 'Gamma claim.', e: 'Epsilon claim.' }, 'pin-2');+ const selection: GenerationsSelection = { kind: 'synthetic', mode: 'restore', key: OWNER };+ const preview = await repair(engine, selection);+ expect(preview.listing).toEqual([{ item: `default:${OWNER}`, class: 'restore', detail: 'generation 2 back to 1: revive 2, retire 1' }]);+ expect(preview.apply_command).toContain(`--expect ${preview.preview_hash}`);+ const applied = await repair(engine, selection, preview.preview_hash);+ expect(applied.outcomes).toEqual({ restored: 1 });+ expect(await liveSlugs(engine, OWNER)).toEqual([slug('a'), slug('b'), slug('c'), slug('d')]);+ expect(await body(engine, 'a')).toContain('Alpha claim.');+ expect(await body(engine, 'a')).not.toContain('revised');+ expect(await retiredBy(engine, 'e')).toEqual({ deleted: true, retired_by: 'generation-restore' });+ const [live] = await engine.executeRaw<{ generation: number; restore_of: number | null }>("SELECT generation, restore_of FROM derived_generations WHERE state='live'");+ expect(Number(live!.generation)).toBe(3);+ expect(live!.restore_of).not.toBeNull();+ });+ }, 120_000);++ test('restore refuses a key with an item edited since, leaving every item of it unchanged', async () => {+ await withBrain(databaseUrl, async engine => {+ await publish(engine, FOUR, 'pin-1');+ await publish(engine, { a: 'Alpha claim.', b: 'Beta claim.', c: 'Gamma claim.', e: 'Epsilon claim.' }, 'pin-2');+ await engine.putPage(slug('e'), { type: 'note', title: 'e', compiled_truth: 'Epsilon, edited by hand.', frontmatter: { synthetic_owner: OWNER, synthetic_producer: 'synthetic' } });+ const selection: GenerationsSelection = { kind: 'synthetic', mode: 'restore', key: OWNER };+ const preview = await repair(engine, selection);+ expect(preview.listing?.[0]).toMatchObject({ class: 'refused' });+ expect(preview.listing?.[0]?.detail).toContain(`${slug('e')}: edited_since`);+ const applied = await repair(engine, selection, preview.preview_hash);+ expect(applied.outcomes).toEqual({ refused: 1 });+ expect(applied.stopped?.reason).toBe('incomplete');+ expect(await liveSlugs(engine, OWNER)).toEqual([slug('a'), slug('b'), slug('c'), slug('e')]);+ expect(await body(engine, 'e')).toContain('edited by hand');+ });+ }, 120_000);++ test('release-held publishes a held shrink once and refuses a held result that lacks proof', async () => {+ await withBrain(databaseUrl, async engine => {+ await publish(engine, FOUR, 'pin-1');+ await publish(engine, { a: 'Alpha claim.' }, 'pin-2');+ const selection: GenerationsSelection = { kind: 'synthetic', mode: 'release-held', held: true };+ const preview = await repair(engine, selection);+ expect(preview.listing).toEqual([expect.objectContaining({ class: 'release-held' })]);+ const applied = await repair(engine, selection, preview.preview_hash);+ expect(applied.outcomes).toEqual({ released: 1 });+ expect(await liveSlugs(engine, OWNER)).toEqual([slug('a')]);+ expect(await publish(engine, {}, 'pin-3')).toMatchObject({ state: 'held', reason: 'no_proof' });+ const noProof = await repair(engine, selection);+ expect(noProof.listing).toEqual([expect.objectContaining({ class: 'refused', detail: expect.stringContaining('no_proof is not releasable') })]);+ expect(await liveSlugs(engine, OWNER)).toEqual([slug('a')]);+ });+ }, 120_000);++ test('purging a page scrubs its preimages from the ledger, and restore then refuses it', async () => {+ await withBrain(databaseUrl, async engine => {+ await publish(engine, FOUR, 'pin-1');+ await publish(engine, { a: 'Alpha claim.', b: 'Beta claim.', c: 'Gamma claim.' }, 'pin-2');+ const { scrubGenerationLedger } = await import('../../src/core/generations/ledger-scrub.ts');+ expect(await scrubGenerationLedger(engine, 'default', { slug: slug('d') })).toEqual({ derived_generation_items: 1, derived_generations: 0 });+ const preview = await repair(engine, { kind: 'synthetic', mode: 'restore', key: OWNER });+ expect(preview.listing?.[0]?.detail).toContain(`${slug('d')}: no_preimage`);+ });+ }, 120_000);++ test('every preview command the generations surfaces print parses as a valid repair invocation', async () => {+ const commands = [repairPreviewCommand('generations').split(' '), repairPreviewCommand('generations', { source: 'default' }).split(' '),+ generationsPreviewArgv({ kind: 'atom' }), generationsPreviewArgv({ kind: 'atom', sourceId: 'default' }, 'release-held'),+ generationsPreviewArgv({ kind: 'atom', ownerKey: 'source_slug:notes/a', sourceId: 'default' })];+ for (const argv of commands) {+ expect(argv.slice(0, 3)).toEqual(['gbrain', 'repair', 'generations']);+ const parsed = parseRepairArgs(argv.slice(2));+ expect(parsed.kind).toBe('generations');+ expect(parsed.generationKind).toBe('atom');+ expect(Boolean(parsed.since || parsed.held || parsed.key)).toBe(true);+ }+ });+ });+}