Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-161 PR 1b: probes 1-7 (managed writer #7013, contention, crash resume, two-file retirement, transcript keys, rename map, upgrade adoption); locator-first transcript keys
garrytan32286e5d879a
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 249275fea1..188f34671f 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -1508,9 +1508,10 @@ function transcriptRoot(filePath: string, corpusDir: string, meetingDir: string/*** GBRA-161 PR 1b (Eng r3 F1): each transcript's generation key: its root label and path relative to that root, never its- * basename or content hash, so two files of one name in two folders never share a key. A file whose key has no live- * generation but whose content equals the input of a live transcript generation whose file is gone was moved: it keeps- * that key, and the generation's locator follows it (recorded even when the unchanged file is not extracted again).+ * basename or content hash, so two files of one name in two folders never share a key. A file a live generation names as+ * its locator keeps that generation's key (the rename map). A file whose key has no live generation but whose content+ * equals the input of a live transcript generation whose file is gone was moved: it keeps that key, and the generation's+ * locator follows it (recorded even when the unchanged file is not extracted again).*/async function resolveTranscriptKeys(engine: BrainEngine, sourceId: string, transcripts: ReadonlyArray<{ filePath: string; contentHash: string; root?: { path: string; label: string } }>,dryRun: boolean): Promise<Map<string, string>> {@@ -1519,9 +1520,14 @@ async function resolveTranscriptKeys(engine: BrainEngine, sourceId: string, tranconst live = await engine.executeRaw<{ id: number; owner_key: string; locator: string | null; input_pin: string | null }>(`SELECT id, owner_key, locator, input_pin FROM derived_generations WHERE source_id=$1 AND kind=$2 AND state='live' AND owner_key LIKE $3`,[sourceId, ATOM_KIND, `${TRANSCRIPT_KEY_PREFIX}%`]);+ const located = new Set<string>();+ for (const t of transcripts) {+ const at = live.find(row => row.locator === t.filePath);+ if (at) { own.set(t.filePath, at.owner_key.slice(TRANSCRIPT_KEY_PREFIX.length)); located.add(t.filePath); }+ }const claimed = new Set([...own.values()].map(key => `${TRANSCRIPT_KEY_PREFIX}${key}`).filter(key => live.some(row => row.owner_key === key)));for (const t of transcripts) {- if (claimed.has(`${TRANSCRIPT_KEY_PREFIX}${own.get(t.filePath)}`)) continue;+ if (located.has(t.filePath) || claimed.has(`${TRANSCRIPT_KEY_PREFIX}${own.get(t.filePath)}`)) continue;const moved = live.find(row => !claimed.has(row.owner_key) && row.input_pin === t.contentHash && row.locator && row.locator !== t.filePath && !existsSync(row.locator));if (!moved) continue;claimed.add(moved.owner_key);diff --git a/test/pathological/g1-managed-atom-keys.test.ts b/test/pathological/g1-managed-atom-keys.test.tsnew file mode 100644index 0000000000..21d60cbee0--- /dev/null+++ b/test/pathological/g1-managed-atom-keys.test.ts@@ -0,0 +1,128 @@+/**+ * GBRA-161 PR 1b probes on managed atom keys and adoption (generations/adapters/atoms.ts, cycle/extract-atoms.ts):+ * 5. Two transcripts with one file name in two folders get two keys (root label plus root-relative path, never the+ * basename) and two atoms; re-extracting one never retires or overwrites the other's.+ * 6. A transcript moved between runs keeps its key (the content pin matches the live generation whose file is gone):+ * the generation's locator follows the file, and the next re-extraction of the moved file retires the atoms of+ * the original key instead of leaving them orphaned under a second key.+ * 7. Populated-upgrade adoption: on the first managed publish of a page's atoms, an atom from before the ledger is+ * adopted (and retired when the result no longer has it) only on retained extractor evidence equal to its current+ * identity; a generated atom edited before the upgrade stays live and protected.+ * Seams: the phase's _transcripts / _pages / _chat inputs (no paid call). PGLite always, Postgres when DATABASE_URL is+ * set. Uses only APIs that exist before PR 1b, so it runs red on the PR 1a head.+ * Fails when: a transcript key is the basename or the absolute path (5, 6), or legacy ownership is read from origin+ * metadata alone (7).+ */+import { describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { managedBrain, pathologicalArms } from './harness.ts';++const sha256 = (text: string) => createHash('sha256').update(text).digest('hex');+const chat = (titles: string[]) => async (_o: ChatOpts): Promise<ChatResult> => {+ const text = JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: title + '.' })));+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 } };+};++function transcript(path: string, root: string, label: string) {+ const content = String(require('node:fs').readFileSync(path, 'utf8'));+ return { filePath: path, content, contentHash: sha256(content), root: { path: root, label } };+}++async function extractTranscripts(engine: BrainEngine, items: ReturnType<typeof transcript>[], titles: string[]) {+ const result = await runPhaseExtractAtoms(engine, { sourceId: 'default', _transcripts: items, _pages: [], _chat: chat(titles) });+ await disposePersistenceConsumer(engine);+ return result;+}++const transcriptAtoms = (engine: BrainEngine) => engine.executeRaw<{ slug: string; live: boolean; source_path: string; retired_by: string | null }>(+ "SELECT slug, deleted_at IS NULL AS live, frontmatter->>'source_path' AS source_path, frontmatter->>'retired_by' AS retired_by FROM pages WHERE source_id='default' AND type='atom' AND frontmatter ? 'source_path' ORDER BY slug");+const transcriptGenerations = (engine: BrainEngine) => engine.executeRaw<{ owner_key: string; locator: string | null }>(+ "SELECT owner_key, locator FROM derived_generations WHERE source_id='default' AND kind='atom' AND state='live' AND owner_key NOT LIKE 'source_slug:%' ORDER BY owner_key");+const said = (label: string) => (label + ': the team ships small changes, measures each launch and reviews outcomes weekly. ').repeat(10);++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe('GBRA-161 PR 1b managed atom keys and adoption (' + backend + ')', () => {+ test('probe 5: one file name in two folders is two keys; re-extracting one leaves the other alone', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-g1-keys-'));+ try {+ const corpus = join(dir, 'corpus');+ const a = join(corpus, 'team-a', '2026-09-07-standup.txt');+ const b = join(corpus, 'team-b', '2026-09-07-standup.txt');+ mkdirSync(join(corpus, 'team-a'), { recursive: true }); mkdirSync(join(corpus, 'team-b'), { recursive: true });+ writeFileSync(a, said('team a')); writeFileSync(b, said('team b'));+ await managedBrain(async ({ engine }) => {+ expect((await extractTranscripts(engine, [transcript(a, corpus, 'corpus'), transcript(b, corpus, 'corpus')], ['Ship small changes'])).status).toBe('ok');+ expect((await transcriptGenerations(engine)).map(row => row.owner_key)).toEqual(['transcript:corpus/team-a/2026-09-07-standup.txt', 'transcript:corpus/team-b/2026-09-07-standup.txt']);+ const first = await transcriptAtoms(engine);+ expect(first.filter(row => row.live).map(row => row.source_path).sort()).toEqual([a, b]);+ writeFileSync(b, said('team b, revised'));+ expect((await extractTranscripts(engine, [transcript(b, corpus, 'corpus')], ['Review outcomes weekly'])).status).toBe('ok');+ const after = await transcriptAtoms(engine);+ expect(after.find(row => row.source_path === a && row.slug === first.find(old => old.source_path === a)!.slug)).toMatchObject({ live: true, retired_by: null });+ expect(after.filter(row => row.live).map(row => [row.source_path, row.slug.includes('review-outcomes-weekly')]).sort()).toEqual([[a, false], [b, true]]);+ expect(after.find(row => row.slug === first.find(old => old.source_path === b)!.slug)).toMatchObject({ live: false, retired_by: 'managed-reextract' });+ }, { databaseUrl });+ } finally { rmSync(dir, { recursive: true, force: true }); }+ }, 240_000);++ test('probe 6: a transcript moved between runs keeps its key and its next re-extraction retires the old atoms', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-g1-rename-'));+ try {+ const corpus = join(dir, 'corpus');+ const before = join(corpus, '2026-09-07-standup.txt');+ const moved = join(corpus, 'archive', '2026-09-07-standup.txt');+ mkdirSync(join(corpus, 'archive'), { recursive: true });+ writeFileSync(before, said('standup'));+ await managedBrain(async ({ engine }) => {+ expect((await extractTranscripts(engine, [transcript(before, corpus, 'corpus')], ['Ship small changes'])).status).toBe('ok');+ const [original] = (await transcriptAtoms(engine)).filter(row => row.live);+ renameSync(before, moved);+ await extractTranscripts(engine, [transcript(moved, corpus, 'corpus')], ['Ship small changes']);+ expect(await transcriptGenerations(engine)).toEqual([{ owner_key: 'transcript:corpus/2026-09-07-standup.txt', locator: moved }]);+ writeFileSync(moved, said('standup, revised'));+ expect((await extractTranscripts(engine, [transcript(moved, corpus, 'corpus')], ['Review outcomes weekly'])).status).toBe('ok');+ expect(await transcriptGenerations(engine)).toEqual([{ owner_key: 'transcript:corpus/2026-09-07-standup.txt', locator: moved }]);+ const after = await transcriptAtoms(engine);+ expect(after.find(row => row.slug === original!.slug)).toMatchObject({ live: false, retired_by: 'managed-reextract' });+ expect(after.filter(row => row.live).map(row => [row.source_path, row.slug.includes('review-outcomes-weekly')])).toEqual([[moved, true]]);+ }, { databaseUrl });+ } finally { rmSync(dir, { recursive: true, force: true }); }+ }, 240_000);++ test('probe 7: populated upgrade adopts an evidenced legacy atom and protects one edited before the upgrade', async () => {+ const NOTE = 'notes/acme-example-upgrade';+ await managedBrain(async ({ engine }) => {+ const page = (await engine.getPage(NOTE, { sourceId: 'default' }))!;+ const result = await runPhaseExtractAtoms(engine, { sourceId: 'default', _transcripts: [], _chat: chat(['Ship small changes']),+ _pages: [{ slug: NOTE, content: page.compiled_truth, contentHash: page.content_hash! }] });+ await disposePersistenceConsumer(engine);+ expect(result.status).toBe('ok');+ const rows = await engine.executeRaw<{ slug: string; live: boolean; retired_by: string | null; body: string }>(+ "SELECT slug, deleted_at IS NULL AS live, frontmatter->>'retired_by' AS retired_by, compiled_truth AS body FROM pages WHERE source_id='default' AND type='atom' ORDER BY slug");+ expect(rows.find(row => row.slug === 'atoms/2026-01-01/legacy-unedited')).toMatchObject({ live: false, retired_by: 'managed-reextract' });+ expect(rows.find(row => row.slug === 'atoms/2026-01-01/legacy-edited')).toMatchObject({ live: true, retired_by: null, body: 'A person corrected this atom before the upgrade.' });+ expect(rows.filter(row => row.live).map(row => row.slug.includes('ship-small-changes') || row.slug.endsWith('legacy-edited'))).toEqual([true, true]);+ }, { databaseUrl, setup: async ({ engine }) => {+ await engine.putPage(NOTE, { type: 'note', title: 'Acme example upgrade', compiled_truth: said('upgrade'), timeline: '' }, { sourceId: 'default' });+ const hash = (await engine.getPage(NOTE, { sourceId: 'default' }))!.content_hash!.slice(0, 16);+ for (const name of ['legacy-unedited', 'legacy-edited']) {+ const slug = 'atoms/2026-01-01/' + name;+ await engine.putPage(slug, { type: 'atom', title: name, compiled_truth: 'Extracted before the ledger existed.',+ frontmatter: { atom_type: 'insight', source_slug: NOTE, source_hash: 'earlier0000hash0', managed_extraction: true, dream_generated: true, extracted_by: 'extract_atoms-v0.41.2.1' } }, { sourceId: 'default' });+ await engine.createVersion(slug, { sourceId: 'default' });+ }+ const edited = (await engine.getPage('atoms/2026-01-01/legacy-edited', { sourceId: 'default' }))!;+ await engine.putPage(edited.slug, { ...edited, compiled_truth: 'A person corrected this atom before the upgrade.' }, { sourceId: 'default' });+ expect(hash).toHaveLength(16);+ } });+ }, 240_000);+ });+}diff --git a/test/pathological/g1-managed-atom-probes.test.ts b/test/pathological/g1-managed-atom-probes.test.tsnew file mode 100644index 0000000000..3d920d4c40--- /dev/null+++ b/test/pathological/g1-managed-atom-probes.test.ts@@ -0,0 +1,206 @@+/**+ * GBRA-161 PR 1b probes on the managed atom writer (generations/managed.ts): a managed publication is admitted as create+ * members (new identities only), one managed_generation_activate request, then gated overwrite and retire members.+ *+ * Protects:+ * 1. #7013 on the managed writer: an honest empty re-extraction, and a re-extraction whose new atom failed to publish,+ * retire nothing; the activation never happens and its retire member refuses revision_conflict.+ * 2. Managed vs unmanaged contention on one key: an unmanaged generation that lands on the key between a managed+ * run's plan and its activation fences the activation (stale_generation); no member overwrites or retires, the+ * prior atoms keep their content, and the new identity it created is an orphan candidate (doctor, cleanup listing).+ * 3. A crash between activation and the member requests (simulated: every member request ends without committing,+ * as one a killed run never got to land): old and new atoms are both live (never neither), doctor counts the+ * pending members, and the next run resumes them so each retirement commits exactly once.+ * 4. The same crash with two real retirements: after the resume both canonical files are gone.+ * Seams: the phase's _pages / _chat inputs (no paid call), a consumer:preparing fault hook, the generation:member+ * fault point. PGLite always, Postgres when DATABASE_URL is set.+ * Fails when: the activation skips its live recheck (1), its expected-generation fence (2), or the run skips+ * resumeManagedGenerationMembers (3, 4).+ */+import { describe, expect, test } from 'bun:test';+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';+import { disposePersistenceConsumer, waitForWrites } from '../../src/core/persistence/service.ts';+import type { WriteRequest } from '../../src/core/persistence/model.ts';+import type { GBrainConfig } from '../../src/core/config.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { operations } from '../../src/core/operations.ts';+import { OperationError, type OperationContext } from '../../src/core/ops/contract.ts';+import { atomGenerationAdapter, atomOwnerKey } from '../../src/core/generations/adapters/atoms.ts';+import { publishGeneration } from '../../src/core/generations/publish.ts';+import { listPendingMembers } from '../../src/core/generations/managed.ts';+import { generationsRepair } from '../../src/core/generations/repair.ts';+import { generationPendingCheck } from '../../src/commands/doctor/checks/generations.ts';+import { settleManagedGitEffects } from '../helpers/managed-brain.ts';+import { managedBrain, pathologicalArms } from './harness.ts';++const NOTE = 'notes/acme-example-plan';+const KEY = { kind: 'atom', sourceId: 'default', ownerKey: atomOwnerKey({ kind: 'page', slug: NOTE }) };+const body = (label: string) => '---\ntype: note\ntitle: Acme example plan\n---\n\n' + (label + ': the team ships small changes, measures each launch and reviews outcomes weekly. ').repeat(12) + '\n';++function stubChat(titles: string[]) {+ let calls = 0;+ const chat = async (_o: ChatOpts): Promise<ChatResult> => {+ calls++;+ const text = JSON.stringify(titles.map(title => ({ title, body: title + '.', atom_type: 'insight' })));+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' };+ };+ return { chat, calls: () => calls };+}++const atoms = (engine: BrainEngine) => engine.executeRaw<{ slug: string; live: boolean; retired_by: string | null; body: string }>(+ "SELECT slug, deleted_at IS NULL AS live, frontmatter->>'retired_by' AS retired_by, compiled_truth AS body FROM pages WHERE source_id='default' AND type='atom' AND frontmatter->>'source_slug'=$1 ORDER BY slug", [NOTE]);+const slugOf = async (engine: BrainEngine, fragment: string) => (await atoms(engine)).find(row => row.slug.includes(fragment))!.slug;++async function extract(engine: BrainEngine, titles: string[]) {+ const stub = stubChat(titles);+ const page = (await engine.getPage(NOTE, { sourceId: 'default' }))!;+ const result = await runPhaseExtractAtoms(engine, { sourceId: 'default', _chat: stub.chat, _transcripts: [],+ _pages: [{ slug: NOTE, content: page.compiled_truth, contentHash: page.content_hash! }] });+ await disposePersistenceConsumer(engine);+ return { status: result.status, calls: stub.calls() };+}++async function edit(ctx: OperationContext, label: string) {+ const snap = await ctx.engine.readPageSnapshot(NOTE, { sourceId: 'default' });+ await operations.find(o => o.name === 'put_page')!.handler(ctx, { slug: NOTE, content: body(label), ...(snap ? { expected_revision: snap.revision } : {}) });+ await disposePersistenceConsumer(ctx.engine);+}++/** Waits for every request the run left queued (a failed activation stops the run's own wait before its members). */+async function drain(engine: BrainEngine) {+ const pending = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id='default' AND state IN ('queued','running','recovering')");+ await waitForWrites(engine, pending, { engine: engine.kind } as GBrainConfig, 60_000);+ await disposePersistenceConsumer(engine);+}++const requestsOf = (engine: BrainEngine, kind: string) => engine.executeRaw<{ slug: string; state: string; error_code: string | null; intent: Record<string, unknown> }>(+ "SELECT slug, state, error_code, intent FROM persistence_requests WHERE source_id='default' AND intent->>'kind'=$1 ORDER BY sequence", [kind]);+const activations = (engine: BrainEngine) => engine.executeRaw<{ id: string; state: string; members: Array<{ slug: string; action: string }> }>(+ 'SELECT id, state, members FROM derived_generation_activations ORDER BY created_at, id');+const liveGeneration = async (engine: BrainEngine) => (await engine.executeRaw<{ generation: number }>(+ "SELECT generation FROM derived_generations WHERE source_id='default' AND kind='atom' AND owner_key=$1 AND state='live'", [KEY.ownerKey]))[0]?.generation ?? null;++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe('GBRA-161 PR 1b managed atom generation probes (' + backend + ')', () => {+ test('probe 1 (#7013): an empty re-extraction and one whose new atom failed both retire nothing', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await edit(ctx, 'first');+ expect((await extract(engine, ['Ship small changes', 'Review outcomes weekly', 'Measure each launch'])).status).toBe('ok');+ expect((await atoms(engine)).map(row => row.live)).toEqual([true, true, true]);+ await edit(ctx, 'second');+ await extract(engine, []);+ expect((await atoms(engine)).map(row => [row.live, row.retired_by])).toEqual([[true, null], [true, null], [true, null]]);+ expect(await requestsOf(engine, 'managed_atom_delete')).toEqual([]);++ await edit(ctx, 'third');+ let fired = false;+ installFaultHook(async (point, detail) => {+ if (fired || point !== 'consumer:preparing' || !detail.writeId) return;+ const [row] = await engine.executeRaw<{ slug: string; kind: string | null }>("SELECT slug, intent->>'kind' AS kind FROM persistence_requests WHERE id=$1::uuid", [detail.writeId]);+ if (row?.kind !== 'managed_atom_page' || !row.slug.includes('track-error-budgets')) return;+ fired = true;+ throw new OperationError('revision_conflict', 'Page ' + row.slug + ' changed after the atom batch was accepted.', 'Run the atom drain again.');+ });+ try { await extract(engine, ['Ship small changes', 'Review outcomes weekly', 'Track error budgets']).catch(() => undefined); }+ finally { installFaultHook(undefined); }+ expect(fired).toBe(true);+ await drain(engine);+ const after = await atoms(engine);+ expect(after.filter(row => row.slug.includes('measure-each-launch'))).toEqual([expect.objectContaining({ live: true, retired_by: null })]);+ expect(after.some(row => row.slug.includes('track-error-budgets') && row.live)).toBe(false);+ const deletes = await requestsOf(engine, 'managed_atom_delete');+ expect(deletes.map(row => [row.state === 'committed', row.error_code])).toEqual([[false, 'revision_conflict']]);+ expect((await activations(engine)).at(-1)!.state).toBe('pending');+ }, { databaseUrl });+ }, 240_000);++ test('probe 2: an unmanaged generation landing between plan and activation fences it; nothing is overwritten or retired', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await edit(ctx, 'first');+ await extract(engine, ['Ship small changes', 'Review outcomes weekly', 'Measure each launch']);+ const before = await atoms(engine);+ const measure = await slugOf(engine, 'measure-each-launch');+ expect(await liveGeneration(engine)).toBe(1);+ await edit(ctx, 'second');+ let landed = false;+ installFaultHook(async (point, detail) => {+ if (landed || point !== 'consumer:preparing' || !detail.writeId) return;+ const [row] = await engine.executeRaw<{ kind: string | null }>("SELECT intent->>'kind' AS kind FROM persistence_requests WHERE id=$1::uuid", [detail.writeId]);+ if (row?.kind !== 'managed_generation_activate') return;+ landed = true;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try {+ const outcome = await publishGeneration(engine, atomGenerationAdapter, { key: KEY, items: [], approved: { retire: [], retiredBy: 'stale-atoms' } });+ expect(outcome.state).toBe('unchanged');+ await engine.executeRaw("UPDATE derived_generations SET generation=generation+1 WHERE source_id='default' AND kind='atom' AND owner_key=$1 AND state='live'", [KEY.ownerKey]);+ } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+ });+ try { await extract(engine, ['Ship small changes', 'Review outcomes weekly', 'Track error budgets']).catch(() => undefined); }+ finally { installFaultHook(undefined); }+ expect(landed).toBe(true);+ await drain(engine);+ expect(await liveGeneration(engine)).toBe(2);+ const [activation] = (await activations(engine)).slice(-1);+ expect(activation!.state).toBe('pending');+ const after = await atoms(engine);+ for (const prior of before) expect(after.find(row => row.slug === prior.slug)).toMatchObject({ live: true, retired_by: null, body: prior.body });+ expect(after.find(row => row.slug === measure)?.live).toBe(true);+ const created = after.find(row => row.slug.includes('track-error-budgets'))!;+ expect(created.live).toBe(true);+ expect((await requestsOf(engine, 'managed_atom_delete')).every(row => row.state !== 'committed')).toBe(true);+ expect((await requestsOf(engine, 'managed_atom_page')).filter(row => row.intent.phase === 'overwrite').every(row => row.state !== 'committed')).toBe(true);+ const doctor = await generationPendingCheck(engine, ['default']);+ expect(doctor.status).toBe('warn');+ expect(doctor.details).toMatchObject({ orphans: 1, orphan_candidates: [{ slug: created.slug, activation_id: activation!.id }] });+ const listing = await generationsRepair.plan(engine, { brain_id: 'brain', source_ids: ['default'] }, null,+ { apply: false, generations: { kind: 'atom', mode: 'cleanup', since: new Date(0).toISOString() } });+ expect(listing.listing).toEqual([expect.objectContaining({ item: 'default:' + created.slug, class: 'orphan_candidate' })]);+ expect(after.find(row => row.slug === created.slug)?.retired_by ?? null).toBeNull();+ }, { databaseUrl });+ }, 240_000);++ for (const files of [false, true]) {+ test('probe ' + (files ? '4: a two-file retirement resumed after a crash leaves both canonical files gone'+ : '3: a crash between activation and its members leaves old and new live; the next run retires each once'), async () => {+ await managedBrain(async ({ engine, ctx, root }) => {+ await edit(ctx, 'first');+ await extract(engine, ['Ship small changes', 'Review outcomes weekly', 'Measure each launch', 'Pair on reviews']);+ await settleManagedGitEffects(engine);+ const retiring = [await slugOf(engine, 'measure-each-launch'), await slugOf(engine, 'pair-on-reviews')];+ if (files) for (const slug of retiring) expect(existsSync(join(root, slug + '.md'))).toBe(true);+ await edit(ctx, 'second');+ let crashes = 0;+ installFaultHook(async point => { if (point === 'generation:member') { crashes++; throw new OperationError('revision_conflict', 'Simulated crash: the member request never landed.', 'Run the atom drain again.'); } });+ try { await extract(engine, ['Ship small changes', 'Review outcomes weekly', 'Track error budgets']).catch(() => undefined); await drain(engine); }+ finally { installFaultHook(undefined); }+ expect(crashes).toBeGreaterThan(0);+ const mid = await atoms(engine);+ for (const slug of retiring) expect(mid.find(row => row.slug === slug)?.live).toBe(true);+ expect(mid.find(row => row.slug.includes('track-error-budgets'))?.live).toBe(true);+ expect((await activations(engine)).at(-1)!.state).toBe('activated');+ const pending = await listPendingMembers(engine, ['default'], 'atom');+ expect(pending.filter(row => row.action === 'retire').map(row => row.slug).sort()).toEqual([...retiring].sort());+ expect((await generationPendingCheck(engine, ['default'])).details).toMatchObject({ retire_pending: 2 });++ await extract(engine, ['Ship small changes', 'Review outcomes weekly', 'Track error budgets']);+ await extract(engine, ['Ship small changes', 'Review outcomes weekly', 'Track error budgets']);+ const after = await atoms(engine);+ for (const slug of retiring) expect(after.find(row => row.slug === slug)).toMatchObject({ live: false, retired_by: 'managed-reextract' });+ expect(await listPendingMembers(engine, ['default'], 'atom')).toEqual([]);+ expect((await generationPendingCheck(engine, ['default'])).status).toBe('ok');+ const committed = (await requestsOf(engine, 'managed_atom_delete')).filter(row => row.state === 'committed').map(row => row.slug).sort();+ expect(committed).toEqual([...retiring].sort());+ if (files) {+ await settleManagedGitEffects(engine);+ for (const slug of retiring) expect(existsSync(join(root, slug + '.md'))).toBe(false);+ }+ }, { databaseUrl });+ }, 240_000);+ }+ });+}