Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(atoms): a zero-yield managed re-extraction retires nothing (#7013)

garrytanf122db2bae53
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index 494ded8e2d..57b6d00760 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -412,7 +412,8 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA
}
const originKey = origin.kind === 'page' ? 'source_slug' : 'source_path';
// #6503: a partial extraction read only the head, so it retires nothing an earlier extraction produced.
- const retirements = failure || origin.partialInputChars ? [] : reviewedRetirements ?? await engine.executeRaw<ManagedAtomRetirement>(
+ // #7013: retirement needs a replacement generation; a zero-yield extraction (or its retry) retires nothing.
+ const retirements = failure || origin.partialInputChars || !atoms.length ? [] : 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
diff --git a/src/core/repair/stale-atoms.ts b/src/core/repair/stale-atoms.ts
index ad86f13b2c..d6e1b5ec6f 100644
--- a/src/core/repair/stale-atoms.ts
+++ b/src/core/repair/stale-atoms.ts
@@ -8,8 +8,11 @@
* (b) `origin_changed`: the atom's 16-character source hash (a managed
* `pending:` prefix stripped) differs from its live source page's
* current hash, and that page already completed an extraction at its
- * current hash (managed: the completed `managed-atoms` checkpoint;
- * unmanaged: a non-managed atom of that page carrying the hash).
+ * current hash that produced atoms (managed: the completed
+ * `managed-atoms` checkpoint plus a live atom of that page carrying the
+ * hash; unmanaged: a non-managed atom of that page carrying the hash).
+ * A zero-yield extraction is no replacement, so it leaves the earlier
+ * atoms out of this class (#7013).
*
* The kind is explicit-only and preview-bound: the preview lists every atom
* with its class and saves the set under its hash; `--apply --expect <hash>`
@@ -88,7 +91,11 @@ async function staleAtoms(db: BrainEngine, sourceIds: string[], atomId?: number)
WHEN origin_hash IS NOT NULL AND atom_hash<>substring(origin_hash from 1 for 16) THEN 'origin_changed'
END AS class,
CASE WHEN managed THEN (SELECT ac.fingerprint FROM op_checkpoints ac WHERE ${managedAtomCompletedSql({ sourceId: 'atom.origin_source_id',
- slug: 'atom.origin_live_slug', pageId: 'atom.origin_page_id', contentHash: 'atom.origin_hash' })} ORDER BY ac.fingerprint LIMIT 1)
+ slug: 'atom.origin_live_slug', pageId: 'atom.origin_page_id', contentHash: 'atom.origin_hash' })}
+ AND EXISTS (SELECT 1 FROM pages r WHERE r.source_id=atom.source_id AND r.type='atom' AND r.deleted_at IS NULL
+ AND r.frontmatter->>'source_slug'=atom.origin_slug
+ AND regexp_replace(COALESCE(r.frontmatter->>'source_hash',''),'^pending:','')=substring(atom.origin_hash from 1 for 16))
+ ORDER BY ac.fingerprint LIMIT 1)
ELSE (SELECT 'unmanaged:'||e.id FROM pages e WHERE e.source_id=atom.source_id AND e.type='atom' AND e.deleted_at IS NULL
AND COALESCE(e.frontmatter->>'managed_extraction','')<>'true' AND e.frontmatter->>'source_slug'=atom.origin_slug
AND e.frontmatter->>'source_hash'=substring(atom.origin_hash from 1 for 16) ORDER BY e.id LIMIT 1)
diff --git a/test/pathological/h1-zero-yield-atom-reextract.test.ts b/test/pathological/h1-zero-yield-atom-reextract.test.ts
new file mode 100644
index 0000000000..f01a868e4a
--- /dev/null
+++ b/test/pathological/h1-zero-yield-atom-reextract.test.ts
@@ -0,0 +1,116 @@
+/**
+ * H-1 (#7013): a zero-yield re-extraction never retires an existing atom generation.
+ *
+ * Protects: on a managed brain, a page whose atoms were published once is edited and re-extracted; the model
+ * honestly returns `[]`. The prior atom stays live (no `retired_by`), the scan state advances for the new
+ * content (the completed `managed-atoms` checkpoint and the page state, so the next run makes no model call), and
+ * `gbrain repair stale-atoms` does not list the kept atom. A later non-empty extraction still retires it, and an
+ * unmanaged brain agrees with the managed one.
+ * Fails when: `publishManagedAtoms(..., [])` computes retirements for every prior atom of the origin and
+ * soft-deletes them with `retired_by: managed-reextract` (master before the fix), or the stale-atoms preview counts
+ * a zero-yield completion as a replacement.
+ * Seams: the phase's `_pages` / `_chat` test 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 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 { staleAtomsRepair } from '../../src/core/repair/stale-atoms.ts';
+import { operations } from '../../src/core/operations.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { managedBrain, pathologicalArms } from './harness.ts';
+
+const NOTE = 'notes/acme-example-launch';
+const body = (label: string) => `---\ntype: note\ntitle: Acme example launch\n---\n\n${`${label}: the team measures every launch against exit criteria and reviews them 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 }>(
+ `SELECT slug, deleted_at IS NULL AS live, frontmatter->>'retired_by' AS retired_by FROM pages
+ WHERE source_id='default' AND type='atom' AND frontmatter->>'source_slug'=$1 ORDER BY slug`, [NOTE]);
+
+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);
+}
+
+async function staleAtomsListed(engine: BrainEngine): Promise<string[]> {
+ const [{ id }] = await engine.executeRaw<{ id: string }>('SELECT id FROM persistence_brain LIMIT 1').catch(() => [{ id: 'brain' }]);
+ const plan = await staleAtomsRepair.plan(engine, { brain_id: String(id), source_ids: ['default'] }, null, { apply: false });
+ return plan.items.map(item => item.slug);
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`H-1 zero-yield atom re-extraction (${backend})`, () => {
+ test('H-1 managed: an honest [] re-extraction keeps the prior atom live and advances the scan state', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await edit(ctx, 'first');
+ expect((await extract(engine, ['Launch exit criteria'])).status).toBe('ok');
+ const [atom] = await atoms(engine);
+ expect(atom).toEqual({ slug: atom!.slug, live: true, retired_by: null });
+
+ await edit(ctx, 'second');
+ const empty = await extract(engine, []);
+ expect({ status: empty.status, calls: empty.calls }).toEqual({ status: 'ok', calls: 1 });
+ expect(await atoms(engine)).toEqual([{ slug: atom!.slug, live: true, retired_by: null }]);
+ const page = (await engine.getPage(NOTE, { sourceId: 'default' }))!;
+ const [state] = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM op_checkpoints WHERE op='managed-atoms' AND completed_keys->0->>'locator'=$1
+ AND completed_keys->0->>'contentHash'=$2 AND completed_keys->0->>'failure' IS NULL`, [NOTE, page.content_hash]);
+ expect(state!.n).toBe(1);
+ expect((await extract(engine, ['Never asked'])).calls).toBe(0);
+ expect(await staleAtomsListed(engine)).toEqual([]);
+
+ await edit(ctx, 'third');
+ expect((await extract(engine, ['Launch review cadence'])).status).toBe('ok');
+ const after = await atoms(engine);
+ expect(after.find(row => row.slug === atom!.slug)).toEqual({ slug: atom!.slug, live: false, retired_by: 'managed-reextract' });
+ expect(after.filter(row => row.live).length).toBe(1);
+ }, { databaseUrl });
+ }, 240_000);
+
+ test('H-1 unmanaged: the same [] re-extraction keeps the prior atom, matching the managed path', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-h1-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ await engine.putPage(NOTE, { type: 'note', title: 'Acme example launch', compiled_truth: body('first'), timeline: '' }, { sourceId: 'default' });
+ await extract(engine, ['Launch exit criteria']);
+ const [atom] = await atoms(engine);
+ expect(atom!.live).toBe(true);
+ await engine.putPage(NOTE, { type: 'note', title: 'Acme example launch', compiled_truth: body('second'), timeline: '' }, { sourceId: 'default' });
+ expect((await extract(engine, [])).calls).toBe(1);
+ expect(await atoms(engine)).toEqual([{ slug: atom!.slug, live: true, retired_by: null }]);
+ expect(await staleAtomsListed(engine)).toEqual([]);
+ } finally { await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }, 240_000);
+ });
+}