Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Keep held facts when the dream cycle merges a duplicate stub page into a page whose facts section was dropped

garrytan436ab8a27eb7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c998dd6cec..d9a758dcb4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,15 +12,15 @@ identifiers and attribution are available in the pre-removal Git revision
## [Unreleased]
-**A fact or take no longer disappears when gbrain re-creates a `## Facts` or takes section that a page rewrite dropped.** When an agent rewrote a page without its facts or takes section, gbrain correctly kept those rows live until the user decided. But the next `remember`, `takes add`, fact extraction or `gbrain facts relink` on that page built a new section holding only its own row, and the write after that (a tag, a timeline entry, an append, or a get and put round trip) read the new section as the user's answer: the remembered facts expired and the takes were deleted, on repo-less and Git-backed brains alike. Those writers now render the held rows back into the section they create, so nothing is lost; a fact the user forgot, a take they removed, and rows retired by an explicit empty section stay withdrawn. `gbrain repair lost-fence-rows` previews the rows an older gbrain already lost this way and, after `--apply --expect <hash> --yes`, puts exactly those rows back from page history.
+**A fact or take no longer disappears when gbrain re-creates a `## Facts` or takes section that a page rewrite dropped.** When an agent rewrote a page without its facts or takes section, gbrain correctly kept those rows live until the user decided. But the next `remember`, `takes add`, fact extraction, `gbrain facts relink` or dream-cycle merge of a duplicate stub page into that page built a new section holding only its own row, and the write after that (a tag, a timeline entry, an append, or a get and put round trip) read the new section as the user's answer: the remembered facts expired and the takes were deleted, on repo-less and Git-backed brains alike. Those writers now render the held rows back into the section they create, so nothing is lost; a fact the user forgot, a take they removed, and rows retired by an explicit empty section stay withdrawn. `gbrain repair lost-fence-rows` previews the rows an older gbrain already lost this way and, after `--apply --expect <hash> --yes`, puts exactly those rows back from page history.
### Itemized changes
-- `src/core/facts/unfenced-facts.ts`: `heldFenceFactRows` lists the live rows a facts fence of the page held; `withHeldFactsFence` renders them into a new facts section when the page has none. Used by `remember` (`fence-fact-append.ts`), managed fact extraction (`persistence/facts-prepare.ts`, which also serves Google loops and the put backstop), `facts relink` (`relink-publish.ts`), unmanaged `writeFactsToFence` (`fence-write.ts`) and cycle fact adoption (`planFence`).
+- `src/core/facts/unfenced-facts.ts`: `heldFenceFactRows` lists the live rows a facts fence of the page held; `withHeldFactsFence` renders them into a new facts section when the page has none. Used by `remember` (`fence-fact-append.ts`), managed fact extraction (`persistence/facts-prepare.ts`, which also serves Google loops and the put backstop), `facts relink` (`relink-publish.ts`), unmanaged `writeFactsToFence` (`fence-write.ts`), cycle fact adoption (`planFence`) and the dream cycle's phantom redirect (`cycle/phantom-redirect.ts`, `cycle/phantom-redirect-managed.ts`).
- `src/core/persistence/takes-prepare.ts`: `heldTakeRows` reads the stored takes while the take fence is held `fence_absent`; a takes write that creates the fence renders them first (covers `takes add`, `takes propose --accept` and consolidation).
- `src/core/repair/lost-fence-rows.ts`: new explicit-only, preview-bound repair kind `lost-fence-rows`, registered in `repair/core.ts` and `repair/registry.ts`; `persistence/preview-approval.ts` accepts its approvals.
- Docs: `docs/guides/repair.md#lost-fence-rows`.
-- Tests: `test/fence-absent-append-keeps-rows.test.ts` (remember, takes add, managed extraction and relink, each followed by a tag, timeline entry, append or round trip; forget, takes remove and an empty section stay withdrawn; repo-less and Git), `test/repair-lost-fence-rows.test.ts` (preview writes nothing, apply restores exactly the listed rows, deliberate removals and empty sections are not listed, a changed page is skipped).
+- Tests: `test/fence-absent-append-keeps-rows.test.ts` (remember, takes add, managed extraction and relink, each followed by a tag, timeline entry, append or round trip; forget, takes remove and an empty section stay withdrawn; a managed phantom redirect into the page keeps the held fact; repo-less and Git), `test/repair-lost-fence-rows.test.ts` (preview writes nothing, apply restores exactly the listed rows, deliberate removals and empty sections are not listed, a changed page is skipped).
## [0.60.625.0] - 2026-11-09
diff --git a/src/core/cycle/phantom-redirect-managed.ts b/src/core/cycle/phantom-redirect-managed.ts
index d729739b86..fd8f7c08eb 100644
--- a/src/core/cycle/phantom-redirect-managed.ts
+++ b/src/core/cycle/phantom-redirect-managed.ts
@@ -25,6 +25,7 @@ import { parseFactsFence } from '../facts-fence.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { logPhantomEvent } from '../facts/phantom-audit.ts';
import { MOVE_WITHDRAWAL_SUBJECT_SQL } from '../facts/withdrawal-schema.ts';
+import { withHeldFactsFence } from '../facts/unfenced-facts.ts';
import { recordRenameAlias } from '../page-state/rename-alias.ts';
import { noteBelief } from '../belief/ledger.ts';
import { preparePageMutation } from '../persistence/page-prepare.ts';
@@ -50,7 +51,8 @@ export async function redirectManagedPhantom(engine: BrainEngine, page: Page, ca
const phantomFence = parseFactsFence(page.compiled_truth ?? '');
if (phantomFence.warnings.length > 0) return drift('phantom facts fence does not parse cleanly');
if (parseFactsFence(target.page.compiled_truth).warnings.length > 0) return drift('canonical facts fence does not parse cleanly');
- const merged = mergePhantomFenceRows(target.page.compiled_truth, phantomFence.facts, Number(dbMax?.n ?? 0));
+ const canonicalBody = (await withHeldFactsFence(engine, sourceId, canonical, { compiled_truth: target.page.compiled_truth, timeline: target.page.timeline })).compiled_truth;
+ const merged = mergePhantomFenceRows(canonicalBody, phantomFence.facts, Number(dbMax?.n ?? 0));
if (merged.body !== null && parseFactsFence(merged.body).warnings.length > 0) return drift('rendered fence failed re-parse');
const outcome = await submitMaintenanceIntent(engine, authority, canonical, {
kind: 'managed_maintenance_phantom_merge', expected_revision: target.revision,
diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.ts
index 43d3b7d17b..22fd1fb702 100644
--- a/src/core/cycle/phantom-redirect.ts
+++ b/src/core/cycle/phantom-redirect.ts
@@ -60,6 +60,7 @@ import { tryAcquireDbLock, syncLockId, type DbLockHandle } from '../db-lock.ts';
import { isAborted } from '../abort-check.ts';
import { logPhantomEvent, type PhantomOutcome } from '../facts/phantom-audit.ts';
import { MOVE_WITHDRAWAL_SUBJECT_SQL } from '../facts/withdrawal-schema.ts';
+import { withHeldFactsFence } from '../facts/unfenced-facts.ts';
import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';
import { fileBodyMatchesStored, fileDatabaseDriftToken, mirrorFileBody, readStoredBody, replaceStoredBody, replaceableFile } from '../facts/file-body-guard.ts';
import { recordRenameAlias } from '../page-state/rename-alias.ts';
@@ -261,7 +262,7 @@ async function mergeIntoCanonicalFile(
if (phantomFacts.length === 0) return { renumber: new Map<number, number>() };
await materializeCanonicalToDisk(engine, canonical, sourceId, canonicalPath);
const bytes = fs.readFileSync(canonicalPath, 'utf-8');
- const { body: newBody, renumber } = mergePhantomFenceRows(bytes, phantomFacts, dbMaxRowNum);
+ const { body: newBody, renumber } = mergePhantomFenceRows((await withHeldFactsFence(engine, sourceId, canonical, { compiled_truth: bytes })).compiled_truth, phantomFacts, dbMaxRowNum);
const stored = await readStoredBody(engine, sourceId, canonical);
if (stored && !fileBodyMatchesStored(bytes, canonical, stored)) return { held: canonicalDriftToken(canonical, phantomSlug, sourceId, 'before') };
if (newBody === null) return { renumber };
@@ -309,7 +310,8 @@ async function mergeIntoCanonicalBody(
): Promise<{ renumber: Map<number, number> } | { held: string }> {
const expected = canonical && await readStoredBody(engine, sourceId, canonical.slug);
if (!canonical || !expected) throw new Error('canonical page is gone');
- const { body, renumber } = mergePhantomFenceRows(expected.compiled_truth ?? '', phantomFacts, dbMaxRowNum);
+ const { body, renumber } = mergePhantomFenceRows((await withHeldFactsFence(engine, sourceId, canonical.slug, { compiled_truth: expected.compiled_truth ?? '', timeline: expected.timeline })).compiled_truth,
+ phantomFacts, dbMaxRowNum);
if (body === null) return { renumber };
const written = await maintenanceTransaction(engine, tx =>
replaceStoredBody(tx, sourceId, canonical.slug, { compiled_truth: body, timeline: expected.timeline ?? '' }, expected));
diff --git a/test/fence-absent-append-keeps-rows.test.ts b/test/fence-absent-append-keeps-rows.test.ts
index 3a6fad72df..e8e57a20a1 100644
--- a/test/fence-absent-append-keeps-rows.test.ts
+++ b/test/fence-absent-append-keeps-rows.test.ts
@@ -15,11 +15,13 @@ import type { BrainEngine } from '../src/core/engine.ts';
import type { OperationContext } from '../src/core/ops/contract.ts';
import { operationsByName } from '../src/core/operations.ts';
import { parseFactsFence } from '../src/core/facts-fence.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
import { parseTakesFence } from '../src/core/takes-fence.ts';
import { emptyFenceBlock } from '../src/core/generations/fence.ts';
import { publishManagedEntityFacts } from '../src/core/facts/managed-fact-write.ts';
import { runFactsRelink } from '../src/core/facts/relink.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { redirectManagedPhantom } from '../src/core/cycle/phantom-redirect-managed.ts';
import { durableGitRepo } from './helpers/git-publication.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
@@ -128,6 +130,25 @@ for (const backend of testBackends()) {
await checkFileHolds(engine, root, storage, slug, [FACT_A, FACT_B]);
}, opts), 180_000);
+ test('fact: a phantom redirect into the page keeps the held fact when it re-creates the section', () => managedBrain(async ({ engine, ctx, root }) => {
+ const slug = 'people/alice-example';
+ await put(ctx, slug, PERSON('Alice v1.\n'));
+ await remember(ctx, slug, FACT_A);
+ await put(ctx, slug, PERSON('Alice v2, rewritten by an agent without the facts section.\n'));
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.putPage('alice', { type: 'person', title: 'alice', timeline: '', frontmatter: {},
+ compiled_truth: '# alice\n\n## Facts\n\n<!--- gbrain:facts:begin -->\n\n'
+ + '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n'
+ + `| 1 | ${FACT_B} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |\n<!--- gbrain:facts:end -->` }, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));
+ const phantom = (await engine.readPageSnapshot('alice', { sourceId: 'default' }))!;
+ writeFileSync(join(root, 'alice.md'), serializePageToMarkdown(phantom.page, phantom.tags));
+ expect(await redirectManagedPhantom(engine, phantom.page, slug, 'default')).toEqual({ outcome: 'redirected', canonical: slug });
+ expect(await fenceFacts(engine, slug)).toEqual([FACT_A, FACT_B].sort());
+ await op(ctx, 'add_tag', { slug, tag: 'example' });
+ expect((await facts(engine, slug)).filter(f => !f.expired).map(f => f.fact).sort()).toEqual([FACT_A, FACT_B].sort());
+ expect(await held(engine, slug)).toEqual([]);
+ await checkFileHolds(engine, root, storage, slug, [FACT_A, FACT_B]);
+ }, opts), 180_000);
+
test('take: takes_add, fenceless put, takes_add, then a tag: the first take is not deleted', () => managedBrain(async ({ engine, ctx, root }) => {
const slug = 'companies/acme-example';
await put(ctx, slug, COMPANY('Acme v1.\n'));