Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-161 PR 2: fence restore transplants the fence block; probes for canonical edits, fence_absent surfaces, restore

garrytan92863056e436
diff --git a/src/core/generations/fence-restore.ts b/src/core/generations/fence-restore.ts
new file mode 100644
index 0000000000..ea6e72b63d
--- /dev/null
+++ b/src/core/generations/fence-restore.ts
@@ -0,0 +1,67 @@
+/**
+ * GBRA-161 PR 2 (plan D6): a fence kind restores by transplanting the fence block the earlier generation recorded into
+ * the page as it is now, through an ordinary guarded `put_page` of the page's current content bound to its current
+ * revision (`edit_page` refuses to write fence markers). Only the fence block changes: the body around it, the timeline, the tags and the other fence are left as they are, and the page
+ * projection then re-derives the rows (a new generation). A page whose fence was edited since the live generation (or
+ * removed, or moved to another section) is refused whole (`edited_since`, `section_moved`); a generation whose block
+ * was too large to keep restores nothing (`no_preimage`).
+ */
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import { OperationError, type OperationContext } from '../ops/contract.ts';
+import { serializePageToMarkdown } from '../markdown.ts';
+import { submitPageMutation } from '../persistence/page-mutations.ts';
+import { fenceName, fenceSlugOf, readFenceBlocks, type FenceBlocks, type FenceGenerationKind } from './fence.ts';
+import type { GenerationKey } from './contract.ts';
+
+export interface FenceRestorePlan { revive: string[]; retire: string[]; refused: string[]; content: string | null; revision: string | null }
+
+/** What transplanting generation `prevId`'s fence block over the live generation `liveId`'s would do, read now. */
+export async function planFenceRestore(db: BrainEngine, key: GenerationKey, liveId: number, prevId: number): Promise<FenceRestorePlan> {
+ const generations = await db.executeRaw<{ id: number; fence: FenceBlocks | null }>(
+ `SELECT id, completeness->'fence' AS fence FROM derived_generations WHERE id = ANY($1::bigint[])`, [[liveId, prevId]]);
+ const blocks = new Map(generations.map(row => [Number(row.id), row.fence && typeof row.fence === 'object' ? row.fence : null]));
+ const items = await db.executeRaw<{ generation_id: number; item_key: string }>(
+ `SELECT generation_id, item_key FROM derived_generation_items WHERE generation_id = ANY($1::bigint[]) AND action <> 'retired'`, [[liveId, prevId]]);
+ const owned = (id: number) => new Set(items.filter(item => Number(item.generation_id) === id).map(item => item.item_key));
+ const [target, current] = [owned(prevId), owned(liveId)];
+ const revive = [...target].filter(itemKey => !current.has(itemKey)).sort();
+ const retire = [...current].filter(itemKey => !target.has(itemKey)).sort();
+ const refuse = (reason: string): FenceRestorePlan => ({ revive, retire, refused: [`${key.ownerKey}: ${reason}`], content: null, revision: null });
+ const want = blocks.get(prevId); const recorded = blocks.get(liveId);
+ if (!want || !recorded) return refuse('no_preimage');
+ const slug = fenceSlugOf(key.ownerKey);
+ const snapshot = slug ? await db.readPageSnapshot(slug, { sourceId: key.sourceId }) : null;
+ if (!snapshot || snapshot.page.deleted_at) return refuse('page_gone');
+ const read = readFenceBlocks(snapshot.page, fenceName(key.kind as FenceGenerationKind));
+ if (read.state !== 'parsed' || read.blocks.body !== recorded.body || read.blocks.timeline !== recorded.timeline) return refuse('edited_since');
+ let content = serializePageToMarkdown(snapshot.page, await db.getTags(slug!, { sourceId: key.sourceId }));
+ for (const section of ['body', 'timeline'] as const) {
+ const [now, then] = [read.blocks[section], want[section]];
+ if (now === then) continue;
+ if (now === null) return refuse('section_moved');
+ const at = content.indexOf(now);
+ if (at === -1 || content.indexOf(now, at + 1) !== -1) return refuse('block_ambiguous');
+ content = content.slice(0, at) + (then ?? '') + content.slice(at + now.length);
+ }
+ return { revive, retire, refused: [], content, revision: snapshot.revision };
+}
+
+/** Applies an approved fence restore: re-plans under the page's current revision and writes the page with only its fence block changed. */
+export async function applyFenceRestore(ctx: OperationContext, key: GenerationKey, approved: { id: number; restore_to_id: number; revive: string[]; retire: string[]; refused: string[] }):
+ Promise<'changed' | string[] | { written: boolean }> {
+ const [live] = await ctx.engine.executeRaw<{ id: number }>(`SELECT id FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='live'`,
+ [key.sourceId, key.kind, key.ownerKey]);
+ if (Number(live?.id) !== approved.id) return 'changed';
+ const plan = await planFenceRestore(ctx.engine, key, approved.id, approved.restore_to_id);
+ if (JSON.stringify([plan.revive, plan.retire, plan.refused]) !== JSON.stringify([approved.revive, approved.retire, approved.refused])) return 'changed';
+ if (plan.refused.length) return plan.refused;
+ try {
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: fenceSlugOf(key.ownerKey)!, source_id: key.sourceId, expected_revision: plan.revision!,
+ content: plan.content!, request_id: randomUUID() } });
+ } catch (error) {
+ if (error instanceof OperationError && error.code === 'revision_conflict') return 'changed';
+ throw error;
+ }
+ return { written: true };
+}
diff --git a/src/core/generations/fence.ts b/src/core/generations/fence.ts
index 4da8030cbe..97d4e81c9b 100644
--- a/src/core/generations/fence.ts
+++ b/src/core/generations/fence.ts
@@ -201,7 +201,7 @@ export function emptyFenceBlock(fence: 'facts' | 'takes'): string {
/**
* The owner's decision a held fence waits for (`ask_user`). For an absent fence: whether the section was removed on
* purpose. Restoring the fence keeps the rows; writing the empty fence retires them. Neither is the default and nothing
- * runs without the user. A database-only page (no file to edit) changes through `put_page` or `edit_page`.
+ * runs without the user. A database-only page (no file to edit) changes through `put_page` (`edit_page` refuses fence markers).
*/
export function fenceAbsentFix(hold: Pick<FenceHold, 'source_id' | 'kind' | 'slug' | 'rows' | 'read' | 'reason'>, opts: { databaseOnly: boolean }): Action {
const fence = fenceName(hold.kind);
@@ -216,9 +216,9 @@ export function fenceAbsentFix(hold: Pick<FenceHold, 'source_id' | 'kind' | 'slu
}
const block = emptyFenceBlock(fence);
const write = opts.databaseOnly
- ? ' This page has no file, so either change is a page write: read it with get_page (include_content: true), then put_page with expected_revision and the full '
- + 'content (restored section, or the empty block appended), or edit_page with expected_revision and edits: [{ old_text: <the page\'s last line>, new_text: <that line, a blank line, then the block> }].'
- : ' Edit the page\'s file and sync it, or write the page with put_page or edit_page and its expected_revision.';
+ ? ' This page has no file, so either change is a put_page: read it with get_page (include_content: true), then put_page with that revision as expected_revision and the full '
+ + 'content with the section restored or the empty block appended (edit_page refuses to write fence markers).'
+ : ' Edit the page\'s file and sync it, or read it with get_page (include_content: true) and put_page the full content with that revision as expected_revision.';
return { consent: [], actor: 'user', requires_exclusive: false, ask_user: true,
why: `Page ${hold.slug} (source ${hold.source_id}) was written without its ${section} section, so gbrain kept its ${what} live instead of retiring them; `
+ `nothing was retired. The user may have deleted the whole ${section} section on purpose, or an edit may have lost it: ask which. `
diff --git a/src/core/generations/repair.ts b/src/core/generations/repair.ts
index 259c32d851..833304df31 100644
--- a/src/core/generations/repair.ts
+++ b/src/core/generations/repair.ts
@@ -31,6 +31,7 @@ import { generationAdapter, generationKinds } from './adapters/index.ts';
import { readGenerationsConfig, restoreDaysHint } from './config.ts';
import { RELEASABLE_HELD_REASONS, type GenerationAdapter, type GenerationKey, type HeldReason, type ProposedItem } from './contract.ts';
import { listOrphanCandidates, listPendingMembers } from './managed.ts';
+import { applyFenceRestore, planFenceRestore } from './fence-restore.ts';
import { activateGeneration, assertItemsLive, itemSetHash, lockGeneration, publishGeneration, readLiveGeneration, type LedgerItem } from './publish.ts';
export const GENERATION_MODES = ['restore', 'release-held', 'cleanup'] as const;
@@ -152,7 +153,8 @@ async function selectEntries(db: BrainEngine, adapter: GenerationAdapter<unknown
WHERE g.source_id = ANY($1::text[]) AND g.kind = $2 AND g.state = 'live'${where} ORDER BY g.id`, params);
const entries: Entry[] = [];
for (const row of rows) {
- const plan = await planRestore(db, adapter, keyOf(adapter.kind, row.source_id, row.owner_key), Number(row.id), Number(row.prev_id));
+ const key = keyOf(adapter.kind, row.source_id, row.owner_key);
+ const plan = adapter.fence ? await planFenceRestore(db, key, Number(row.id), Number(row.prev_id)) : await planRestore(db, adapter, key, Number(row.id), Number(row.prev_id));
if (!plan.revive.length && !plan.retire.length && !plan.refused.length) continue;
entries.push({ mode: 'restore', id: Number(row.id), source_id: row.source_id, owner_key: row.owner_key, generation: Number(row.generation),
restore_to: Number(row.prev_generation), restore_to_id: Number(row.prev_id), revive: plan.revive, retire: plan.retire, refused: plan.refused });
@@ -264,6 +266,12 @@ async function applyEntry(ctx: OperationContext, adapter: GenerationAdapter<unkn
if (outcome.state === 'held') return { applied: false, outcome: 'refused', reason: `${approved.owner_key}: still held (${outcome.reason})` };
return { applied: true, outcome: 'released', detail: { generation: outcome.generation, ...(outcome.state === 'published' ? { retired: outcome.retired.length } : {}) } };
}
+ if (adapter.fence) {
+ const restored = await applyFenceRestore(ctx, key, approved);
+ if (restored === 'changed') return changed('the live generation, its fence or the page changed since the preview');
+ if (Array.isArray(restored)) return { applied: false, outcome: 'refused', reason: restored.join(', ') };
+ return { applied: true, outcome: 'restored', detail: { restore_of: approved.restore_to, revived: approved.revive.length, retired: approved.retire.length } };
+ }
if (await managedPersistenceEnabled(ctx.engine)) {
return { applied: false, outcome: 'refused', reason: `${approved.owner_key}: a managed source restores retired atoms with gbrain repair atoms-restore; a generation restore here runs on unmanaged brains only` };
}
diff --git a/test/pathological/g2-consolidation-generations.test.ts b/test/pathological/g2-consolidation-generations.test.ts
index 649322493b..8742c85279 100644
--- a/test/pathological/g2-consolidation-generations.test.ts
+++ b/test/pathological/g2-consolidation-generations.test.ts
@@ -49,7 +49,7 @@ async function seed(engine: BrainEngine, fact: string, at: string, claim?: { met
}
const facts = (engine: BrainEngine) => engine.executeRaw<{ id: number; valid_until: string | null; consolidated: boolean; into: number | null }>(
- 'SELECT id, valid_until::text AS valid_until, consolidated_at IS NOT NULL AS consolidated, consolidated_into AS "into" FROM facts ORDER BY id');
+ 'SELECT id::int AS id, valid_until::text AS valid_until, consolidated_at IS NOT NULL AS consolidated, consolidated_into::int AS "into" FROM facts ORDER BY id');
async function repair(engine: BrainEngine, selection: GenerationsSelection, expectHash?: string): Promise<RepairResult> {
const scope = await resolveRepairScope(engine, 'default');
diff --git a/test/pathological/g2-fence-generations.test.ts b/test/pathological/g2-fence-generations.test.ts
index 6eda80a7f2..384ae54384 100644
--- a/test/pathological/g2-fence-generations.test.ts
+++ b/test/pathological/g2-fence-generations.test.ts
@@ -7,6 +7,21 @@ import { describe, expect, test } from 'bun:test';
import type { BrainEngine } from '../../src/core/engine.ts';
import { pathologicalArms } from './harness.ts';
import { FACTS_FENCE, managedSource, PERSON } from './managed-fixture.ts';
+import { renderTakesFence } from '../../src/core/takes-fence.ts';
+import { emptyFenceBlock } from '../../src/core/generations/fence.ts';
+import { generationHeldCheck } from '../../src/commands/doctor/checks/generations.ts';
+import { readSyncStatus } from '../../src/core/persistence/sync-status.ts';
+import { operationsByName } from '../../src/core/operations.ts';
+import { resolveRepairScope, type RepairResult } from '../../src/core/repair/core.ts';
+import { repairRunner } from '../../src/core/repair/registry.ts';
+import type { GenerationsSelection } from '../../src/core/generations/repair.ts';
+
+async function repair(engine: BrainEngine, sourceId: string, selection: GenerationsSelection, expectHash?: string): Promise<RepairResult> {
+ const scope = await resolveRepairScope(engine, sourceId);
+ const quiet = { info: () => {}, warn: () => {}, error: () => {} };
+ return (await repairRunner(engine, { apply: expectHash !== undefined, noEmbed: true, logger: quiet })).run('generations', scope,
+ { explicit: true, sourceFlag: sourceId, generations: selection, ...(expectHash ? { expect: expectHash } : {}) });
+}
const ROW = (n: number, claim: string) => `| ${n} | ${claim} | fact | 1.0 | world | medium | 2020-01-01 | | chat | |`;
const SLUG = 'people/alice-example';
@@ -16,6 +31,24 @@ async function factRows(engine: BrainEngine, sourceId: string) {
'SELECT fact, row_num, expired_at IS NOT NULL AS expired FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY id', [sourceId, SLUG]);
}
+const TAKES = (n: number) => `## Takes\n\n${renderTakesFence(Array.from({ length: n }, (_, i) => ({ rowNum: i + 1, claim: `Take ${i + 1}`, kind: 'take' as const,
+ holder: 'world', weight: 0.7, active: true })))}\n`;
+const FACTS = (n: number) => n ? FACTS_FENCE(Array.from({ length: n }, (_, i) => ROW(i + 1, `Claim ${i + 1}`)).join('\n')) : emptyFenceBlock('facts');
+
+async function liveCounts(engine: BrainEngine, sourceId: string, slug: string) {
+ const [row] = await engine.executeRaw<{ facts: number; takes: number }>(`SELECT
+ (SELECT count(*)::int FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND expired_at IS NULL) AS facts,
+ (SELECT count(*)::int FROM takes t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND p.slug=$2) AS takes`, [sourceId, slug]);
+ return { facts: Number(row!.facts), takes: Number(row!.takes) };
+}
+
+async function ledger(engine: BrainEngine, sourceId: string, slug: string) {
+ return engine.executeRaw<{ kind: string; state: string; retired: number; preimages: number }>(`SELECT g.kind, g.state,
+ (SELECT count(*)::int FROM derived_generation_items i WHERE i.generation_id=g.id AND i.action='retired') AS retired,
+ (SELECT count(*)::int FROM derived_generation_items i WHERE i.generation_id=g.id AND i.action='retired' AND i.preimage IS NOT NULL) AS preimages
+ FROM derived_generations g WHERE g.source_id=$1 AND g.owner_key=$2 AND g.state IN ('live','held') ORDER BY g.kind, g.state`, [sourceId, `page:${slug}`]);
+}
+
describe('GBRA-161 PR 2 fence generations', () => {
for (const { backend, databaseUrl } of pathologicalArms()) {
test(`[${backend}] B-5: a page write whose body lost its facts fence keeps every fact live`, async () => {
@@ -27,5 +60,78 @@ describe('GBRA-161 PR 2 fence generations', () => {
['Alice founded acme-example', 1, false], ['Alice plays chess', 2, false], ['Alice lives in Lisbon', 3, false]]);
});
}, 120_000);
+
+ test(`[${backend}] canonical edits 10→9, 10→1 and 10→0 publish with no shrink floor and record each retired row`, async () => {
+ await managedSource(databaseUrl, async () => {}, async ({ engine, sourceId, put }) => {
+ for (const keep of [9, 1, 0]) {
+ const slug = `people/edit-${keep}-example`;
+ await put(slug, PERSON('Edit Example', `${FACTS(10)}\n${TAKES(10)}`));
+ expect(await liveCounts(engine, sourceId, slug)).toEqual({ facts: 10, takes: 10 });
+ await put(slug, PERSON('Edit Example', `${FACTS(keep)}\n${keep ? TAKES(keep) : emptyFenceBlock('takes')}`));
+ expect(await liveCounts(engine, sourceId, slug)).toEqual({ facts: keep, takes: keep });
+ expect(await ledger(engine, sourceId, slug)).toEqual([
+ { kind: 'fact_fence', state: 'live', retired: 10 - keep, preimages: 10 - keep },
+ { kind: 'take_fence', state: 'live', retired: 10 - keep, preimages: 10 - keep }]);
+ }
+ });
+ }, 180_000);
+
+ test(`[${backend}] an absent fence is listed with an ask_user fix in doctor, sync status and get_page`, async () => {
+ await managedSource(databaseUrl, async () => {}, async ({ engine, sourceId, put }) => {
+ await put(SLUG, PERSON('Alice Example', FACTS(3)));
+ await put(SLUG, PERSON('Alice Example', 'The facts section was removed in this edit.\n'));
+ expect(await ledger(engine, sourceId, SLUG)).toEqual([{ kind: 'fact_fence', state: 'held', retired: 0, preimages: 0 },
+ { kind: 'fact_fence', state: 'live', retired: 0, preimages: 0 }]);
+ const check = await generationHeldCheck(engine, [sourceId]);
+ expect(check.status).toBe('warn');
+ const status = await readSyncStatus(engine, sourceId);
+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true }, dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ const page = await operationsByName.get_page!.handler(ctx as never, { slug: SLUG }) as { fence_held?: Array<{ kind: string; reason: string; rows: number; fix: Record<string, unknown> }> };
+ expect(page.fence_held?.map(hold => [hold.kind, hold.reason, hold.rows])).toEqual([['fact_fence', 'fence_absent', 3]]);
+ expect(status.fence_holds.map(hold => [hold.slug, hold.reason, hold.rows])).toEqual([[SLUG, 'fence_absent', 3]]);
+ for (const fix of [check.fix as unknown as Record<string, unknown>, status.fence_holds[0]!.fix as unknown as Record<string, unknown>, page.fence_held![0]!.fix]) {
+ expect(fix).toMatchObject({ ask_user: true, actor: 'user' });
+ expect(fix.argv).toBeUndefined();
+ expect(String(fix.why)).toContain('deleted the whole ## Facts section on purpose');
+ expect(String(fix.why)).toContain('To keep the rows, restore the ## Facts section');
+ expect(String(fix.why)).toContain(emptyFenceBlock('facts'));
+ expect(String(fix.user_message)).toContain('To keep them, restore the ## Facts section. To remove them, add this empty section');
+ }
+ expect(status.next).toEqual(status.fence_holds[0]!.fix);
+ await put(SLUG, PERSON('Alice Example', `The facts section was removed in this edit.\n\n${emptyFenceBlock('facts')}`));
+ expect(await liveCounts(engine, sourceId, SLUG)).toEqual({ facts: 0, takes: 0 });
+ expect(await ledger(engine, sourceId, SLUG)).toEqual([{ kind: 'fact_fence', state: 'live', retired: 3, preimages: 3 }]);
+ expect((await generationHeldCheck(engine, [sourceId])).status).toBe('ok');
+ });
+ }, 180_000);
+
+ test(`[${backend}] a fence restore transplants only the fence block: body, timeline, tags and the takes fence survive, and a republish keeps the rows`, async () => {
+ await managedSource(databaseUrl, async () => {}, async ({ engine, sourceId, put }) => {
+ const timeline = '\n<!-- timeline -->\n\n## Timeline\n\n- **2024-02-01** | meeting — Kickoff with acme-example\n';
+ const page = (prose: string, facts: number) => PERSON('Alice Example', `${prose}\n\n${TAKES(2)}\n${FACTS(facts)}${timeline}`, 'tags: [alpha-example, beta-example]\n');
+ await put(SLUG, page('Alice is an example person.', 3));
+ await put(SLUG, page('Alice is an example person.', 1));
+ await put(SLUG, page('Alice is an example person. A later edit changed this paragraph.', 1));
+ expect(await liveCounts(engine, sourceId, SLUG)).toEqual({ facts: 1, takes: 2 });
+ const before = (await engine.readPageSnapshot(SLUG, { sourceId }))!;
+ const selection: GenerationsSelection = { kind: 'fact_fence', mode: 'restore', key: `page:${SLUG}` };
+ const preview = await repair(engine, sourceId, selection);
+ expect(preview.listing).toEqual([{ item: `${sourceId}:page:${SLUG}`, class: 'restore', detail: 'generation 2 back to 1: revive 2, retire 0' }]);
+ expect((await repair(engine, sourceId, selection, preview.preview_hash)).outcomes).toEqual({ restored: 1 });
+ const after = (await engine.readPageSnapshot(SLUG, { sourceId }))!;
+ expect(after.page.compiled_truth).toBe(before.page.compiled_truth.replace(ROW(1, 'Claim 1'), [1, 2, 3].map(n => ROW(n, `Claim ${n}`)).join('\n')));
+ expect(after.page.compiled_truth).toContain('A later edit changed this paragraph.');
+ expect(after.page.compiled_truth).toContain(TAKES(2));
+ expect(after.page.timeline).toBe(before.page.timeline);
+ expect((await engine.getTags(SLUG, { sourceId })).sort()).toEqual(['alpha-example', 'beta-example']);
+ expect(await liveCounts(engine, sourceId, SLUG)).toEqual({ facts: 3, takes: 2 });
+ const [entries] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM timeline_entries t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND p.slug=$2', [sourceId, SLUG]);
+ expect(Number(entries!.n)).toBe(1);
+ await put(SLUG, `---\ntitle: Alice Example\ntype: person\ntags: [alpha-example, beta-example]\n---\n# Alice Example\n\n${after.page.compiled_truth.replace(/^# Alice Example\n\n/, '')}${timeline}`);
+ expect(await liveCounts(engine, sourceId, SLUG)).toEqual({ facts: 3, takes: 2 });
+ const edited = await repair(engine, sourceId, selection);
+ expect(edited.listing?.[0]?.class).not.toBe('refused');
+ });
+ }, 180_000);
}
});