Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Keep held facts and takes when gbrain re-creates a dropped section

garrytane387eaa0b18a
diff --git a/src/core/facts/fence-fact-append.ts b/src/core/facts/fence-fact-append.ts
index 246f0f5c1c..7f529fc81c 100644
--- a/src/core/facts/fence-fact-append.ts
+++ b/src/core/facts/fence-fact-append.ts
@@ -12,6 +12,9 @@
* number past both the fence and every facts row indexed from the page (a row the fence lost still owns its number,
* #6696 C9), optionally strikes the superseded row of the same page, and prepares the page write. The stored fence is
* normalized first (#6188); a fence that does not parse cleanly refuses typed (`target_fence_malformed`, #6385 R12).
+ * When the page has no facts fence at all (a rewrite dropped the section, so its rows are held `fence_absent`), the
+ * live rows a fence of the page held are rendered back into the section this append creates (`withHeldFactsFence`):
+ * otherwise the next projected write reads the new one-row section as the user's answer and expires them.
* - A request on `memory/unattributed` (`UNATTRIBUTED_MEMORY_SLUG`) with no page yet creates it: a `note` whose body is
* the one facts fence. Its rows project with no entity (extract-from-fence.ts), so a fact saved without an entity
* has a file home (GBRA-190 G4, D3). No other page is ever created here.
@@ -45,7 +48,7 @@ import { withPageTierKept } from '../trust/fence-append.ts';
import type { TrustTier } from '../trust/tier.ts';
import { extractFactsFromFenceText, UNATTRIBUTED_MEMORY_SLUG } from './extract-from-fence.ts';
import { rememberAcceptsPageCreatedSince } from '../persistence/page-identity.ts';
-import { fenceRowOf, type FenceRowInput } from './unfenced-facts.ts';
+import { fenceRowOf, withHeldFactsFence, type FenceRowInput } from './unfenced-facts.ts';
export type FenceFactAppendInput = {
/** The facts row to publish; `row_num` and `source_markdown_slug` are the helper's. kind and visibility default as insertFacts does. */
@@ -164,8 +167,9 @@ export async function prepareFenceFactAppend(engine: BrainEngine, row: WriteRequ
const fenced = { compiled_truth: target.page.compiled_truth, timeline: target.page.timeline ?? '' };
const rowNum = Math.max(indexedMax?.n ?? 0, ...[fenced.compiled_truth, fenced.timeline].flatMap(text => parseFactsFence(text).facts.map(f => f.rowNum))) + 1;
const cell = fenceCellFor(fact, rowNum);
+ const unfenced = snapshot ? (await withHeldFactsFence(engine, row.source_id, row.slug, fenced))[section] : fenced[section];
// #6385 R12: an entity fence that does not parse cleanly refuses typed instead of losing the rows it skipped.
- const appended = refuseUnparsedRewrite(target.page, row.slug, row.source_id, () => upsertFactRow(fenced[section], cell));
+ const appended = refuseUnparsedRewrite(target.page, row.slug, row.source_id, () => upsertFactRow(unfenced, cell));
let next = { ...fenced, [section]: appended.body };
if (input.supersede) next = strikeFactRowInPage(next, input.supersede.rowNum, rowNum, input.supersede.validUntil ? formatFenceDate(input.supersede.validUntil) : undefined);
const content = serializePageToMarkdown({ ...base, ...next }, snapshot?.tags ?? []);
diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.ts
index e2b69e4b1c..dbb8a7a386 100644
--- a/src/core/facts/fence-write.ts
+++ b/src/core/facts/fence-write.ts
@@ -49,6 +49,7 @@ import { gbrainPath } from '../config.ts';
import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';
import { isDurabilityHardened, commitWriteThroughFile } from '../brain-repo-durability.ts';
import { upsertFactRow, parseFactsFence, formatFenceDate } from '../facts-fence.ts';
+import { withHeldFactsFence } from './unfenced-facts.ts';
import { unparsedFenceRefusal } from '../fence-repair/refusal.ts';
import type { OperationError } from '../ops/contract.ts';
import { extractFactsFromFenceText } from './extract-from-fence.ts';
@@ -510,6 +511,7 @@ export async function writeFactsToFence(
} catch (err) {
console.warn(`[facts.fence] FACTS_ROW_NUM_HINT_UNAVAILABLE: ${target.slug} (source ${target.sourceId}): ${err instanceof Error ? err.message : String(err)}; numbering from the file alone`);
}
+ body = (await withHeldFactsFence(engine, target.sourceId, target.slug, { compiled_truth: body })).compiled_truth;
const fenceRefusal = refuseUnparsedFence(body, target, filePath);
if (fenceRefusal) return { inserted: 0, ids: [], fenceWriteFailed: true, fenceRefusal, ...withdrawnSkipped };
const { facts: existingFenceFacts } = parseFactsFence(body);
diff --git a/src/core/facts/relink-publish.ts b/src/core/facts/relink-publish.ts
index 04a5e96ff8..10f6485f23 100644
--- a/src/core/facts/relink-publish.ts
+++ b/src/core/facts/relink-publish.ts
@@ -26,6 +26,7 @@ import type { GBrainConfig } from '../config.ts';
import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { formatFenceDate, parseFactsFence, upsertFactRow } from '../facts-fence.ts';
+import { withHeldFactsFence } from './unfenced-facts.ts';
import { digest } from '../persistence/digest.ts';
import type { PreparedMutation } from '../persistence/coordinator.ts';
import type { WriteRequest } from '../persistence/model.ts';
@@ -189,7 +190,7 @@ export async function prepareRelinkMutation(engine: BrainEngine, row: WriteReque
if (links.length) {
// #6188 (D20): Tier 1 normalizes the entity's stored fence in this write; a residual refuses typed `target_fence_malformed`.
const target = await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: snapshot.page });
- ({ compiled_truth: body, timeline } = target.page);
+ ({ compiled_truth: body, timeline } = await withHeldFactsFence(engine, row.source_id, row.slug, { compiled_truth: target.page.compiled_truth, timeline: target.page.timeline }));
if (target.fixes.length) normalized = { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: target.fixes,
writer: row.principal_kind, path: snapshot.page.source_path ?? null, remote: row.authority.remote }) };
const parsed = parseFactsFence(body);
diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.ts
index 231aae29d8..791620f330 100644
--- a/src/core/facts/unfenced-facts.ts
+++ b/src/core/facts/unfenced-facts.ts
@@ -57,6 +57,8 @@ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'nod
import type { BrainEngine } from '../engine.ts';
import { sanitizeText } from '../batch-rows.ts';
import { isDurabilityHardened } from '../brain-repo-durability.ts';
+import { factsFenceHeld } from '../generations/fence-evidence.ts';
+import { readFenceBlocks } from '../generations/fence.ts';
import { fenceCellReadBackProblem, formatFenceDate, normalizeClaimWhitespace, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, type FactAttribution, type ParsedFact } from '../facts-fence.ts';
import { FENCE_SOURCE_DEFAULT } from './extract-from-fence.ts';
import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
@@ -342,6 +344,36 @@ export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?:
return { managed, groups, filePaths, databaseOnly, localPathById, outcome };
}
+/**
+ * The live facts rows of `slug` that a facts fence of the page held (fence-evidence.ts), each rendered as its fence row
+ * (`fenceRowOf`), in row order. A rewrite that drops the `## Facts` section keeps exactly these rows live (held
+ * `fence_absent`) until the user decides. A withdrawn row (expired: forgotten, struck, retired by an empty fence) is not
+ * among them, nor is a row no fence ever held or a conversation-extractor row (its replay owns it).
+ */
+export async function heldFenceFactRows(engine: BrainEngine, sourceId: string, slug: string): Promise<ParsedFact[]> {
+ const rows = await engine.executeRaw<FenceRowInput & { id: number; row_num: number; fact: string }>(`SELECT id, row_num, fact, kind, visibility, notability, context,
+ valid_from, valid_until, source, confidence, claim_metric, claim_value, claim_unit, claim_period, attributed_to FROM facts
+ WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL AND expired_at IS NULL
+ AND COALESCE(source,'') NOT LIKE 'cli:extract-conversation-facts%' ORDER BY row_num, id`, [sourceId, slug]);
+ if (!rows.length) return [];
+ const { held } = await factsFenceHeld(engine, { sourceId, slug, rows });
+ const seen = new Set<number>();
+ return rows.filter(r => held.has(Number(r.id)) && !seen.has(Number(r.row_num)) && seen.add(Number(r.row_num)))
+ .map(r => fenceRowOf(r, Number(r.row_num), r.fact));
+}
+
+/**
+ * `page` with its held facts rows (`heldFenceFactRows`) rendered into a new facts section when it has no facts fence
+ * at all, else unchanged. Every writer that adds a row to a page creates the section through this, so the section it
+ * creates carries the rows a dropped section held: otherwise the next projected write reads the new section as the
+ * user's answer and expires them.
+ */
+export async function withHeldFactsFence<T extends { compiled_truth: string; timeline?: string | null }>(engine: BrainEngine, sourceId: string, slug: string, page: T): Promise<T> {
+ if (readFenceBlocks(page, 'facts').state !== 'absent') return page;
+ const held = await heldFenceFactRows(engine, sourceId, slug);
+ return held.length ? { ...page, compiled_truth: replaceOrInsertFactsFence(page.compiled_truth, renderFactsTable(held)) } : page;
+}
+
/**
* Append a page's adoptable unfenced rows to its facts fence. Row numbering
* starts above every occupied `row_num` on the page, conversation-extractor
@@ -355,6 +387,7 @@ export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?:
*/
export async function planFence(engine: BrainEngine, sourceId: string, entitySlug: string, body: string, group: UnfencedFactRow[]):
Promise<{ body: string; assignments: Array<{ id: string; row_num: number; fact: string }>; rejected: UnadoptableFactRecord[] } | { warnings: string[] }> {
+ body = (await withHeldFactsFence(engine, sourceId, entitySlug, { compiled_truth: body })).compiled_truth;
const existingFence = parseFactsFence(body);
if (existingFence.warnings.length > 0) return { warnings: existingFence.warnings };
const occupiedRows = await engine.executeRaw<{ row_num: number; fact: string; source: string | null }>(
diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.ts
index 6637a25288..5c1f8d7114 100644
--- a/src/core/persistence/facts-prepare.ts
+++ b/src/core/persistence/facts-prepare.ts
@@ -5,6 +5,7 @@ import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
+import { withHeldFactsFence } from '../facts/unfenced-facts.ts';
import { factsFenceEditor, factsFenceSection, parseFactsFence, formatFenceDate } from '../facts-fence.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { wholeBodySnapshot } from './segmented-apply.ts';
@@ -174,7 +175,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
// #6188 (D20): the entity's stored fence is normalized in this same write; a residual refuses typed `target_fence_malformed`.
const target = snapshot ? await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: snapshot.page }) : null;
// #6686: the fence is edited in the section it lives in (a lone timeline fence stays below the sentinel); the other section is kept byte for byte.
- const fenced = { compiled_truth: target?.page.compiled_truth ?? '', timeline: target?.page.timeline ?? '' };
+ const fenced = await withHeldFactsFence(engine, row.source_id, row.slug, { compiled_truth: target?.page.compiled_truth ?? '', timeline: target?.page.timeline ?? '' });
const section = factsFenceSection(fenced);
// #6898 follow-up: the fence is parsed once and rendered once for the whole group, not once per fact.
const fence = factsFenceEditor(fenced, section);
diff --git a/src/core/persistence/takes-prepare.ts b/src/core/persistence/takes-prepare.ts
index fcb43a21c2..65a18e4629 100644
--- a/src/core/persistence/takes-prepare.ts
+++ b/src/core/persistence/takes-prepare.ts
@@ -30,6 +30,7 @@ import { withWriteAttribution } from './context.ts';
import { decideTakeWrite, recordFlaggedRow, recordWriteGateHold } from '../write-gate-store.ts';
import { writeGateRejectedError } from '../write-gate.ts';
import { beliefTransaction } from '../belief/writers.ts';
+import { fenceOwnerKey, readFenceBlocks, TAKE_FENCE_KIND } from '../generations/fence.ts';
/** Server-derived values are frozen after replay lookup, before admission. */
export async function normalizeTakesIntent(ctx: OperationContext, params: Record<string, unknown>): Promise<Record<string, unknown>> {
@@ -92,6 +93,26 @@ async function takeRemovalRequiresOwner(engine: BrainEngine, row: WriteRequest,
return error;
}
+/**
+ * Every stored take of page `pageId` as its fence row, in row order (resolution cells included when it is graded), while
+ * its take_fence generation is held `fence_absent`: once a fence parses again the projection compares it with exactly
+ * these rows (canonical-projections.ts `heldTakeFence`). None otherwise.
+ */
+export async function heldTakeRows(engine: BrainEngine, sourceId: string, slug: string, pageId: number): Promise<ParsedTake[]> {
+ if (!(await engine.executeRaw(`SELECT 1 FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held' AND held_reason='fence_absent'`,
+ [sourceId, TAKE_FENCE_KIND, fenceOwnerKey(slug)])).length) return [];
+ const rows = await engine.executeRaw<{ row_num: number; claim: string; kind: string; holder: string; weight: number; since_date: string | null; until_date: string | null;
+ source: string | null; active: boolean; resolved_at: Date | string | null; resolved_quality: TakeQuality | null; resolved_outcome: boolean | null; resolved_source: string | null;
+ resolved_value: number | null; resolved_unit: string | null; resolved_by: string | null }>(`SELECT row_num, claim, kind, holder, weight, since_date, until_date, source, active,
+ resolved_at, resolved_quality, resolved_outcome, resolved_source, resolved_value, resolved_unit, resolved_by FROM takes WHERE page_id=$1 ORDER BY row_num`, [pageId]);
+ return rows.map(t => ({ rowNum: Number(t.row_num), claim: t.claim, kind: t.kind, holder: t.holder, weight: Number(t.weight), active: t.active,
+ ...(t.since_date ? { sinceDate: t.since_date } : {}), ...(t.until_date ? { untilDate: t.until_date } : {}), ...(t.source ? { source: t.source } : {}),
+ ...(t.resolved_quality ? { resolvedQuality: t.resolved_quality, resolvedAt: t.resolved_at ? new Date(t.resolved_at).toISOString() : undefined,
+ ...(t.resolved_outcome !== null ? { resolvedOutcome: t.resolved_outcome } : {}), ...(t.resolved_source ? { resolvedEvidence: t.resolved_source } : {}),
+ ...(t.resolved_value !== null ? { resolvedValue: Number(t.resolved_value) } : {}), ...(t.resolved_unit ? { resolvedUnit: t.resolved_unit } : {}),
+ ...(t.resolved_by ? { resolvedBy: t.resolved_by } : {}) } : {}) }));
+}
+
/** `editBody`: a same-page edit published with the takes change (consolidation closes its fenced facts here). */
export async function prepareTakesMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, editBody?: (body: string) => string): Promise<PreparedMutation> {
try { return await prepare(engine,row,config,editBody); } catch (error) { return fail(error); }
@@ -110,7 +131,11 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
const defect = appends ? undefined : scanCanonicalFences(snapshot.page).defects.find(d => d.fence === 'takes');
if (defect) throw targetFenceRefusal(defect, row.slug, row.source_id);
const target = appends ? await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'takes', page: snapshot.page }) : null;
- const body = serializePageToMarkdown(target ? { ...snapshot.page, ...target.page } : snapshot.page,snapshot.tags);
+ const rendered = serializePageToMarkdown(target ? { ...snapshot.page, ...target.page } : snapshot.page,snapshot.tags);
+ // A rewrite that dropped the takes fence left the page's takes stored (held fence_absent): a takes write that creates
+ // the fence again renders them into it first, or the next projected write would read the new fence as their removal.
+ const held = readFenceBlocks(target?.page ?? snapshot.page,'takes').state==='absent' ? await heldTakeRows(engine,row.source_id,row.slug,snapshot.page.id) : [];
+ const body = held.length ? edit.replaceFence(upsertTakeRow(rendered,held[0]!).body,held) : rendered;
const parsed = parseTakesFence(body);
edit.assertFenceRoundTrips(parsed);
for (const key of ['claim','kind','holder','source','evidence','unit','resolved_by']) {
diff --git a/test/fence-absent-append-keeps-rows.test.ts b/test/fence-absent-append-keeps-rows.test.ts
new file mode 100644
index 0000000000..3a6fad72df
--- /dev/null
+++ b/test/fence-absent-append-keeps-rows.test.ts
@@ -0,0 +1,186 @@
+/**
+ * A page rewrite that drops its `## Facts` or takes section keeps the section's rows live under a `fence_absent`
+ * hold until the user decides. gbrain's own appends (remember, takes_add) used to build a brand-new section holding only
+ * the new row, so the next ordinary write (a tag, a timeline entry, an append, a get/put round trip) read that section as
+ * the user's answer and expired the remembered facts or deleted the takes it no longer listed. The append now renders
+ * the held rows back into the section it creates. A row the user withdrew (forget, takes_remove, an explicit empty
+ * section) stays withdrawn.
+ * Managed brain, repo-less (a plain content root) and Git-backed; PGLite, and Postgres from test/postgres-unit-arms.txt.
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+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 { 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 { durableGitRepo } from './helpers/git-publication.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+type Storage = 'repo-less' | 'git';
+const STORAGES: Storage[] = ['repo-less', 'git'];
+const gitSetup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };
+
+const PERSON = (body: string) => `---\ntype: person\ntitle: Alice Example\n---\n\n# Alice Example\n\n${body}`;
+const COMPANY = (body: string) => `---\ntype: company\ntitle: Acme Example\n---\n\n# Acme Example\n\n${body}`;
+const FACT_A = 'Alice Example is allergic to peanuts';
+const FACT_B = 'Alice Example rides a bike to work';
+const TAKE_A = 'Acme Example reaches profitability in 2027';
+const TAKE_B = 'Acme Example hires a finance lead this year';
+
+const op = (ctx: OperationContext, name: string, params: Record<string, unknown>) =>
+ operationsByName[name]!.handler(ctx, { request_id: randomUUID(), ...params }) as Promise<Record<string, unknown>>;
+const revision = async (engine: BrainEngine, slug: string) => (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision;
+const put = async (ctx: OperationContext, slug: string, content: string) => {
+ const prior = await ctx.engine.readPageSnapshot(slug, { sourceId: 'default' });
+ await op(ctx, 'put_page', { slug, content, ...(prior ? { expected_revision: prior.revision } : {}) });
+};
+const remember = (ctx: OperationContext, slug: string, fact: string) =>
+ op(ctx, 'remember', { fact, entity: slug, provenance: 'test', content_origin: 'user_said' });
+
+const facts = (engine: BrainEngine, slug: string) => engine.executeRaw<{ id: number; fact: string; row_num: number | null; expired: boolean }>(
+ "SELECT id::int AS id, fact, row_num, expired_at IS NOT NULL AS expired FROM facts WHERE source_id='default' AND source_markdown_slug=$1 ORDER BY id", [slug]);
+const takes = (engine: BrainEngine, slug: string) => engine.executeRaw<{ row_num: number; claim: string; active: boolean }>(
+ "SELECT t.row_num, t.claim, t.active FROM takes t JOIN pages p ON p.id=t.page_id WHERE p.source_id='default' AND p.slug=$1 ORDER BY t.row_num", [slug]);
+const body = async (engine: BrainEngine, slug: string) => {
+ const page = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.page;
+ return `${page.compiled_truth}\n${page.timeline ?? ''}`;
+};
+const fenceFacts = async (engine: BrainEngine, slug: string) => parseFactsFence(await body(engine, slug)).facts.filter(f => f.active).map(f => f.claim).sort();
+const fenceTakes = async (engine: BrainEngine, slug: string) => parseTakesFence(await body(engine, slug)).takes.map(t => t.claim).sort();
+const held = (engine: BrainEngine, slug: string) => engine.executeRaw<{ kind: string }>(
+ "SELECT kind FROM derived_generations WHERE source_id='default' AND owner_key=$1 AND state='held' ORDER BY kind", [`page:${slug}`]);
+
+/** The writes that used to read the re-created section as proof: each is an ordinary page write that projects the fences. */
+const FOLLOW_UPS: Array<[string, (ctx: OperationContext, slug: string) => Promise<unknown>]> = [
+ ['tag', (ctx, slug) => op(ctx, 'add_tag', { slug, tag: 'example' })],
+ ['timeline entry', (ctx, slug) => op(ctx, 'add_timeline_entry', { slug, date: '2026-01-01', summary: 'An example event' })],
+ ['append', (ctx, slug) => op(ctx, 'append_page', { slug, text: 'An appended line.' })],
+ ['get/edit/put round trip', async (ctx, slug) => {
+ const page = await op(ctx, 'get_page', { slug, include_content: true }) as { content: string; revision: string };
+ await op(ctx, 'put_page', { slug, content: page.content.replace('rewritten', 'edited'), expected_revision: page.revision });
+ }],
+];
+
+async function checkFileHolds(engine: BrainEngine, root: string, storage: Storage, slug: string, claims: string[]) {
+ if (storage === 'git') await settleManagedGitEffects(engine);
+ const file = readFileSync(join(root, `${slug}.md`), 'utf8');
+ for (const claim of claims) expect(file).toContain(claim);
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ for (const storage of STORAGES) {
+ const opts = { databaseUrl, ...(storage === 'git' ? { setup: gitSetup } : {}) };
+
+ describe(`a section re-created by gbrain's own append keeps the rows a fenceless rewrite left held (${backend}, ${storage})`, () => {
+ for (const [name, followUp] of FOLLOW_UPS) {
+ test(`fact: remember, fenceless put, remember, then ${name}: the first fact stays live`, () => 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'));
+ expect((await facts(engine, slug)).map(f => [f.fact, f.row_num, f.expired])).toEqual([[FACT_A, 1, false]]);
+ await remember(ctx, slug, FACT_B);
+ expect(await fenceFacts(engine, slug)).toEqual([FACT_A, FACT_B].sort());
+ await followUp(ctx, slug);
+ expect((await facts(engine, slug)).map(f => [f.fact, f.row_num, f.expired])).toEqual([[FACT_A, 1, false], [FACT_B, 2, false]]);
+ expect(await fenceFacts(engine, slug)).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('fact: the managed entity-fact writer (extraction, Google loops) 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 publishManagedEntityFacts(engine, 'default', slug, [{ fact: FACT_B, kind: 'fact', notability: 'medium', source: 'test-extractor',
+ visibility: 'world', validFrom: new Date('2026-01-01'), sessionId: null, confidence: 1 } as never]);
+ expect(await fenceFacts(engine, slug)).toEqual([FACT_A, FACT_B].sort());
+ await op(ctx, 'add_tag', { slug, tag: 'example' });
+ expect((await facts(engine, slug)).map(f => [f.fact, f.row_num, f.expired])).toEqual([[FACT_A, 1, false], [FACT_B, 2, false]]);
+ expect(await held(engine, slug)).toEqual([]);
+ await checkFileHolds(engine, root, storage, slug, [FACT_A, FACT_B]);
+ }, opts), 180_000);
+
+ test('fact: facts relink 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.insertFact({ fact: FACT_B, kind: 'fact', entity_slug: null,
+ visibility: 'world', source: 'chat' } as never, { source_id: 'default' }), TEST_WRITE_ATTRIBUTION));
+ expect((await runFactsRelink(engine, { sourceId: 'default', config: ctx.config, llm: false })).linked).toBe(1);
+ expect(await fenceFacts(engine, slug)).toEqual([FACT_A, FACT_B].sort());
+ await op(ctx, 'add_tag', { slug, tag: 'example' });
+ expect((await facts(engine, slug)).map(f => [f.fact, f.expired])).toEqual([[FACT_A, false], [FACT_B, false]]);
+ 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'));
+ await op(ctx, 'takes_add', { slug, claim: TAKE_A, kind: 'bet', holder: 'world' });
+ await put(ctx, slug, COMPANY('Acme v2, rewritten without the takes section.\n'));
+ expect((await takes(engine, slug)).map(t => t.claim)).toEqual([TAKE_A]);
+ await op(ctx, 'takes_add', { slug, claim: TAKE_B, kind: 'bet', holder: 'world' });
+ expect(await fenceTakes(engine, slug)).toEqual([TAKE_A, TAKE_B].sort());
+ await op(ctx, 'add_tag', { slug, tag: 'example' });
+ expect(await takes(engine, slug)).toEqual([{ row_num: 1, claim: TAKE_A, active: true }, { row_num: 2, claim: TAKE_B, active: true }]);
+ expect(await fenceTakes(engine, slug)).toEqual([TAKE_A, TAKE_B].sort());
+ expect(await held(engine, slug)).toEqual([]);
+ await checkFileHolds(engine, root, storage, slug, [TAKE_A, TAKE_B]);
+ }, opts), 180_000);
+
+ test('a forgotten fact stays forgotten: it is not rendered back into the re-created section', () => managedBrain(async ({ engine, ctx }) => {
+ const slug = 'people/alice-example';
+ await put(ctx, slug, PERSON('Alice v1.\n'));
+ const { id } = await remember(ctx, slug, FACT_A) as { id: number };
+ await op(ctx, 'forget', { id: String(id), reason: 'the user withdrew it' });
+ await put(ctx, slug, PERSON('Alice v2, rewritten by an agent without the facts section.\n'));
+ await remember(ctx, slug, FACT_B);
+ await op(ctx, 'add_tag', { slug, tag: 'example' });
+ const rows = await facts(engine, slug);
+ expect(rows.find(f => f.fact === FACT_A)).toMatchObject({ expired: true });
+ expect(rows.find(f => f.fact === FACT_B)).toMatchObject({ expired: false });
+ expect(await fenceFacts(engine, slug)).toEqual([FACT_B]);
+ }, opts), 180_000);
+
+ test('facts retired by an explicit empty section stay retired after a later fenceless put and remember', () => managedBrain(async ({ engine, ctx }) => {
+ 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.\n\n${emptyFenceBlock('facts')}`));
+ expect((await facts(engine, slug)).map(f => [f.fact, f.expired])).toEqual([[FACT_A, true]]);
+ await put(ctx, slug, PERSON('Alice v3, rewritten by an agent without the facts section.\n'));
+ await remember(ctx, slug, FACT_B);
+ await op(ctx, 'add_tag', { slug, tag: 'example' });
+ expect((await facts(engine, slug)).map(f => [f.fact, f.expired])).toEqual([[FACT_A, true], [FACT_B, false]]);
+ expect(await fenceFacts(engine, slug)).toEqual([FACT_B]);
+ }, opts), 180_000);
+
+ test('a removed take stays removed: it is not rendered back into the re-created section', () => managedBrain(async ({ engine, ctx }) => {
+ const slug = 'companies/acme-example';
+ await put(ctx, slug, COMPANY('Acme v1.\n'));
+ await op(ctx, 'takes_add', { slug, claim: TAKE_A, kind: 'bet', holder: 'world' });
+ await op(ctx, 'takes_remove', { slug, row_num: 1 });
+ await put(ctx, slug, COMPANY('Acme v2, rewritten without the takes section.\n'));
+ await op(ctx, 'takes_add', { slug, claim: TAKE_B, kind: 'bet', holder: 'world' });
+ await op(ctx, 'add_tag', { slug, tag: 'example' });
+ expect((await takes(engine, slug)).map(t => t.claim)).toEqual([TAKE_B]);
+ expect((await fenceTakes(engine, slug)).filter(claim => claim !== '(removed)')).toEqual([TAKE_B]);
+ }, opts), 180_000);
+ });
+ }
+}