Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(consolidate): close a fenced fact in its fence row, published with the take; the row derives from the cell (G4)
garrytane8a2327d1a4f
diff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.mdindex 8c0cb77542..150a950b86 100644--- a/docs/architecture/key-files/core-cycle-patterns.md+++ b/docs/architecture/key-files/core-cycle-patterns.md@@ -7,7 +7,7 @@ Patterns, drift reports and the cycle modules listed after them.- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still s... (line truncated to 2000 chars)- `src/core/cycle/drift.ts` report publication (#6052): a managed drift report whose publish is held (`publishOrHold`) is not linked in the detail, `reports_written` is 0 and `publish_deferred` 1, the detail names the hold (accepted and still publishing, or not admitted under database contention), and the phase is `partial`; every other publish error still throws.-- `src/core/cycle/phases/consolidate.ts` — the consolidate phase: clusters facts per page and promotes the best claim into a take. `cycle.consolidate.enabled` (default on; an explicit falsy value returns `skipped`, #6667) is read inside the phase; `dream --phase consolidate --once` bypasses it. Take identity for the upsert lookup is `(page_id, claim)` restricted to rows this phase authors (`kind='fact' AND holder='self'`) — `since_date` is NOT identity (it derives from MIN(valid_from) of the cluster and moves whenever extract_facts re-inserts, which degraded the lookup into duplicate INSERTs); deliberately NOT filtered on `active` (a superseded take still owns its claim — skipping it would resurrect a retired claim via the INSERT path); `ORDER BY id` keeps the pick deterministic across pre-existing duplicate rows. A resolved take is immutable — its id is reused for consolidation but the row is left untouched. Managed local consolidation passes the cycle source ID, publishes take, contributing facts and validity changes atomically. Retired/resolved matching takes produce a durable skipped receipt; semantic intent excludes vectors/timestamps/cache metadata, while a genuine newer fact/page snapshot changes request identity. Only live world-visible evidence is promoted; private facts remain private. #5575 ENG-3: fact tiers are read per bucket and external_untrusted facts cluster in a separate pass, so an external claim never shares a take with owner facts. Each cluster's take is written at `derive:consolidate` = min(cluster fact tiers, agent_written): unmanaged, the take insert or re-promotion, consolidation marks and valid_until writeback are one `derivedMaintenanceTransaction` (a re-promotion lowers the existing take to min(existing, cluster), even a resolved one); managed, the request carries `declareDerivation`. Edges: take -> every cluster fact. The unmanaged path runs the write gate (`decideTakeWrite`, config read once per run via `loadImportSanityConfig`) on each... (line truncated to 2000 chars)+- `src/core/cycle/phases/consolidate.ts` — the consolidate phase: clusters facts per page and promotes the best claim into a take. `cycle.consolidate.enabled` (default on; an explicit falsy value returns `skipped`, #6667) is read inside the phase; `dream --phase consolidate --once` bypasses it. Take identity for the upsert lookup is `(page_id, claim)` restricted to rows this phase authors (`kind='fact' AND holder='self'`) — `since_date` is NOT identity (it derives from MIN(valid_from) of the cluster and moves whenever extract_facts re-inserts, which degraded the lookup into duplicate INSERTs); deliberately NOT filtered on `active` (a superseded take still owns its claim — skipping it would resurrect a retired claim via the INSERT path); `ORDER BY id` keeps the pick deterministic across pre-existing duplicate rows. A resolved take is immutable — its id is reused for consolidation but the row is left untouched. Managed local consolidation passes the cycle source ID, publishes take, contributing facts and validity changes atomically: a fenced member on the entity page is closed in its `## Facts` fence row in the same page publication and its `valid_until` derives from that cell, an unfenced member is closed in the database, and a member fenced on another page stays open (test `test/consolidate-fenced-close-reimport.test.ts`). Retired/resolved matching takes produce a durable skipped receipt; semantic intent excludes vectors/timestamps/cache metadata, while a genuine newer fact/page snapshot changes request identity. Only live world-visible evidence is promoted; private facts remain private. #5575 ENG-3: fact tiers are read per bucket and external_untrusted facts cluster in a separate pass, so an external claim never shares a take with owner facts. Each cluster's take is written at `derive:consolidate` = min(cluster fact tiers, agent_written): unmanaged, the take insert or re-promotion, consolidation marks and valid_until writeback are one `derivedMaintenanceTransaction` (a re-promotion lowers the existing take to min(existing, cluster), even a resolved one); managed, the request carries `declareDerivation`. Edges: take -> every cluster fact. The unmanaged path runs the write gate (`decideTakeWrite`, config read once per run via `loadImportSanityConfig`) on each... (line truncated to 2000 chars)- `src/core/cycle/synthesize-verify.ts` — Mechanical claim verification on every page a synthesis child wrote (zero LLM). Exports the shared grounding primitive `normalizeForGrounding` (whitespace/curly-quote/dash/ellipsis/case folding, skipping markdown inline markup (`*`, backticks, `~~`; not `_`), WITH an offset map back to the original string, so every replacement is a verbatim transcript slice; a slice that differs from the quote only by that markup counts exact and is not spliced in) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). A source built with `groundSource(path, content, { tolerant: true })` (think, concepts and patterns; never dream synthesis) also reads markdown link syntax and any other square bracket as plain text (`[Name](target)`, `[Name]` and `Name` match; repairs drop link targets and never carry a `"`), folds `"` to `'`, and counts a quote exact when its words match once the writer's edge punctuation and elision, brackets (including a bracketed letter's case, `[T]he`), editorial insertions in a word (`decide[s]`, `want[ed]`) and inner quote style are set aside. Think also grounds against the user's question. `groundSource(path, content)` prepares a transcript: offset map, speaker turns (`parseSpeakerTurns`: bold `**Name** (ts):` anchors and standalone `[user]` / `[assistant]` / `[system]` role lines (the session-corpus renderer's turn boundaries, so a `Name:` label inside one turn never carries into the next) always, plain `Label:` anchors when the label is a role word or opens two or more lines), canonical numbers and dates (`numericFacts`: `$250K` = `$250,000` = `250 thousand`, `2026-03-14` = `March 14th`; the file basename counts), and speaker-mention patterns. In strict mode (dream synthesis) a quote that misses whole is retried on its core (`quoteCore`: edge elision and closing punctuation set aside) at the exact and normalized rungs; an exact core keeps the writer's quote, a normalized core is replaced by the verbatim source slice. `groundQuote` runs the ladder exact → normalized → near (word-trigram anchors, window clipped to the anchor's speaker turn, ≥0.8 token overlap, ambiguity within 0.05 falls through, trimmed to the first/last shared token, refused above 1.3x the... (line truncated to 2000 chars)diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex a4b16cd8a2..104753cfb7 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1240,6 +1240,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// GBRA-190 G4 (fact fences). `since` is stamped at the merge slot.{ since: 'TBD', text: 'A legacy fact row whose `notability` or `confidence` is empty (a long-lived database whose column lost its NOT NULL) is now adopted into its page\'s `## Facts` table with the column default (notability `medium`, confidence 1) instead of being refused as unadoptable (`parse`) on every run, which held its page out of fact reconciliation and booked an `integrity_guard` halt each cycle. The fence cell is written first and the row derives its values from it. A row with no kind or visibility is still refused.' },{ since: 'TBD', text: '`gbrain repair duplicate-facts` keeps the copy that is a row of a page\'s `## Facts` table over an older database-only copy of the same fact, so the legacy copy is superseded onto the fence row instead of holding it (which left the legacy row unfenced and its page out of fact reconciliation). With no fenced copy it still keeps the oldest row. It stays preview-first and explicit.' },+ { since: 'TBD', text: 'Dream consolidation on a managed brain now closes a fenced fact in its page: the closing `valid_until` is written into the fact\'s row in the entity page\'s `## Facts` fence, published with the take, and the database row takes its value from that cell, so a later sync or re-import keeps the fact closed. Before, only the database row was closed and the next re-import of the page reopened it. A fact with no fence row is still closed in the database. A fenced fact whose fence row is on another page is left open. Facts an earlier release closed in the database only are not changed (GBRA-190).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 8156ec32a3..52c09d72ba 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -10,7 +10,8 @@ import type { Action } from '../agent-output.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';import { fenceOperationError, scanCanonicalFences } from '../fence-repair/refusal.ts';-import { fenceCellReadBackProblem, parseFactsFence } from '../facts-fence.ts';+import { fenceCellReadBackProblem, formatFenceDate, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, type ParsedFact } from '../facts-fence.ts';+import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';import { submissionAuthority, authorizeStoredRequest, authorizeWrite } from './authority.ts';import { currentVerifiedLocalWriter, localHostId, registerLocalWriter } from './identity.ts';import { getWorktreeBinding, managedPersistenceEnabled, type WorktreeBinding } from './ownership.ts';@@ -568,9 +569,31 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, co}, apply: async () => ({ status: 'skipped', reason: 'retired_take', noop: true,facts_consolidated: 0, takes_written: 0, take_id: Number(existing.id) }) };}+ // The chain closes each fact at its successor's valid_from. A fenced fact is closed in its fence row, published with the+ // take on this page, and its row derives from that cell; an unfenced fact has no fence row and is closed in the database.+ // A fenced fact whose fence is on another page stays open: this publication does not write that file.+ const chronological = [...facts].sort((a, b) => Date.parse(String(a.value.valid_from)) - Date.parse(String(b.value.valid_from)) || a.id - b.id);+ const closes = chronological.slice(0, -1).map((fact, i) => ({ fact, until: String(chronological[i + 1].value.valid_from) }));+ const fenceCloses = new Map(closes.filter(c => c.fact.value.row_num !== null && c.fact.value.source_markdown_slug === row.slug)+ .map(c => [Number(c.fact.value.row_num), c]));+ const databaseCloses = closes.filter(c => c.fact.value.row_num === null);+ let closedRows: ParsedFact[] = [];+ const closeInFence = (body: string): string => {+ if (!fenceCloses.size) return body;+ const fence = parseFactsFence(body);+ for (const [rowNum, { fact }] of fenceCloses) {+ if (!fence.warnings.length && !fenceCellReadBackProblem(fence.facts.find(f => f.rowNum === rowNum), { fact: String(fact.value.fact), visibility: String(fact.value.visibility) })) continue;+ throw opError('revision_conflict', 'A consolidated fact does not match its fence row.',+ `Fact ${fact.id} on ${row.slug} in ${row.source_id} does not read back from fence row ${rowNum}, so consolidation request ${row.request_id} could not close it in the page and wrote nothing. The next extract_facts run reconciles the fence, and the next consolidate run re-clusters the current facts.`,+ { fix: receiptFix(row) });+ }+ const rows = fence.facts.map(f => fenceCloses.has(f.rowNum) ? { ...f, validUntil: formatFenceDate(new Date(fenceCloses.get(f.rowNum)!.until)) } : f);+ closedRows = rows.filter(f => fenceCloses.has(f.rowNum));+ return replaceOrInsertFactsFence(body, renderFactsTable(rows));+ };const prepared = await prepareTakesMutation(engine, { ...row, operation: existing ? 'takes_update' : 'takes_add',intent: existing ? { source: p.source, row_num: Number(existing.row_num), expected_revision: p.expected_revision }- : { ...p, kind: 'fact', holder: 'self' } }, config);+ : { ...p, kind: 'fact', holder: 'self' } }, config, closeInFence);return { ...prepared, additionalPageKeys: pages.map(page => ({ sourceId: row.source_id, slug: page.slug })),validate: async tx => {await prepared.validate?.(tx);@@ -598,10 +621,13 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, co{ fix: receiptFix(row) });const before = await factPreimages(tx, row.source_id, facts.map(f => f.id));for (const fact of facts) await tx.consolidateFact(fact.id, take.id);- const chronological = [...facts].sort((a, b) => Date.parse(String(a.value.valid_from)) - Date.parse(String(b.value.valid_from)) || a.id - b.id);- for (let i = 0; i < chronological.length - 1; i++) {- await tx.executeRaw('UPDATE facts SET valid_until=$1::timestamptz WHERE source_id=$2 AND id=$3',- [chronological[i + 1].value.valid_from, row.source_id, chronological[i].id]);+ for (const { fact, until } of databaseCloses) {+ await tx.executeRaw('UPDATE facts SET valid_until=$1::timestamptz WHERE source_id=$2 AND id=$3', [until, row.source_id, fact.id]);+ }+ const derived = extractFactsFromFenceText(closedRows, row.slug, row.source_id);+ for (const [i, cell] of closedRows.entries()) {+ await tx.executeRaw('UPDATE facts SET valid_until=$1::timestamptz WHERE source_id=$2 AND id=$3 AND row_num=$4 AND source_markdown_slug=$5',+ [derived[i].valid_until, row.source_id, fenceCloses.get(cell.rowNum)!.fact.id, cell.rowNum, row.slug]);}await recordConsolidationGeneration(tx, row.source_id, row.slug, before);return { ...outcome, noop: false, facts_consolidated: facts.length, takes_written: existing ? 0 : 1, take_id: Number(take.id) };diff --git a/src/core/persistence/takes-prepare.ts b/src/core/persistence/takes-prepare.tsindex 634a4c37eb..fcb43a21c2 100644--- a/src/core/persistence/takes-prepare.ts+++ b/src/core/persistence/takes-prepare.ts@@ -92,10 +92,11 @@ async function takeRemovalRequiresOwner(engine: BrainEngine, row: WriteRequest,return error;}-export async function prepareTakesMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {- try { return await prepare(engine,row,config); } catch (error) { return fail(error); }+/** `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); }}-async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {+async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, editBody?: (body: string) => string): Promise<PreparedMutation> {const stored = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });if (!stored || stored.page.id !== row.page_id) throw takesRefusal('page_identity_changed','The accepted page no longer exists.',row,`Page ${row.slug} was deleted or replaced after the takes request was accepted.`);@@ -214,6 +215,7 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainConresult={slug:row.slug,row_num:number,...(row.operation==='takes_resolve'?{quality:p.quality,resolved_by:p.resolved_by}:{})};}}+ if (editBody) next = editBody(next);// #6450 post-condition: never publish a fence the next write would refuse.const republished = parseTakesFence(next);if (republished.warnings.length) throw takesRefusal('invalid_params',`The write would publish a takes fence the next write would refuse: ${republished.warnings[0]}`,row,diff --git a/test/consolidate-fenced-close-reimport.test.ts b/test/consolidate-fenced-close-reimport.test.tsnew file mode 100644index 0000000000..7556c2d7b5--- /dev/null+++ b/test/consolidate-fenced-close-reimport.test.ts@@ -0,0 +1,147 @@+/**+ * GBRA-190 (G4, git is the parent): dream consolidation closes a fenced fact in+ * the page's facts fence, and the database row derives from the fence cell.+ * The consolidation writeback used to close the chain with+ * `UPDATE facts SET valid_until ...` only (the managed preparer in+ * prepared-maintenance.ts), so the canonical file's fence row stayed open and+ * the next re-import of the page reopened the fact: extract-facts takes an+ * active row's valid_until from its fence cell. Now the close is written into+ * the fence row of the published page, and a re-import keeps it. An unfenced+ * fact (no fence row) is still closed in the database, as before.+ *+ * The setup comes from G5's (GBRA-60) reproduction,+ * test/consolidate-ties-fenced-reimport.test.ts on capy/gbra60-g5-lanec-tests,+ * whose control asserted the reopen. Managed brain with a durable Git repo;+ * synthetic data only. The Postgres arm runs through test/postgres-unit-arms.txt.+ */+import { afterAll, beforeAll, 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 { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { performSync } from '../src/commands/sync.ts';+import { runPhaseConsolidate } from '../src/core/cycle/phases/consolidate.ts';+import { parseFactsFence, renderFactsTable, type ParsedFact } from '../src/core/facts-fence.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { durableGitRepo, git } from './helpers/git-publication.ts';+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const slug = 'companies/probe-example';+const VECTOR = '[' + [1, ...Array(1535).fill(0)].join(',') + ']';+const SERIES = [+ { claim: 'The deposit amount is $100,000.', value: 100000, from: '2026-01-01', confidence: 1 },+ { claim: 'The deposit amount is $82,000.', value: 82000, from: '2026-02-01', confidence: 0.9 },+ { claim: 'The deposit amount is $90,000.', value: 90000, from: '2026-03-01', confidence: 0.8 },+];+const UNFENCED = { claim: 'The deposit amount was first quoted as $120,000.', value: 120000, from: '2025-12-01T00:00:00Z' };+const typed = (rowNum: number, s: typeof SERIES[number]): ParsedFact => ({+ rowNum, claim: s.claim, kind: 'fact', confidence: s.confidence, visibility: 'world', notability: 'medium', validFrom: s.from, source: 'synthetic fixture', active: true,+ claimMetric: 'deposit_amount', claimValue: s.value, claimUnit: 'USD', claimPeriod: '2026-01-01',+});+const content = (prose: string) => `---\ntype: company\ntitle: Probe Example\n---\n\n# Probe Example\n\n${prose}\n\n## Facts\n\n`+ + `${renderFactsTable(SERIES.map((s, i) => typed(i + 1, s)))}\n`;+const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };+const file = (root: string) => join(root, `${slug}.md`);+const cells = (root: string) => new Map(parseFactsFence(readFileSync(file(root), 'utf8')).facts.map(f => [f.rowNum, f]));++const factRows = async (engine: BrainEngine) => (await engine.executeRaw<{ id: number; fact: string; row_num: number | null; valid_until: string | null;+ expired_at: string | null; consolidated_into: number | null }>(+ `SELECT id, fact, row_num, valid_until::text AS valid_until, expired_at::text AS expired_at, consolidated_into+ FROM facts WHERE source_id='default' AND entity_slug=$1 ORDER BY id`, [slug]))+ .map(r => ({ ...r, id: Number(r.id), row_num: r.row_num === null ? null : Number(r.row_num), consolidated_into: r.consolidated_into === null ? null : Number(r.consolidated_into) }));+const byClaim = async (engine: BrainEngine, claim: string) => (await factRows(engine)).find(r => r.fact === claim && r.expired_at === null)!;+const at = (value: string | null) => (value === null ? null : Date.parse(value));++/**+ * The page with its three typed fence rows, published and committed; embeddings for clustering; one unfenced fact of+ * the same metric, older than the series. The embeddings and the unfenced row are fixture data written with the+ * brain's managed mode off, as the #6023 managed test seeds its facts.+ */+async function seed(engine: BrainEngine, ctx: OperationContext): Promise<void> {+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content: content('Body.') } });+ await settleManagedGitEffects(engine);+ expect((await factRows(engine)).map(r => [r.fact, r.row_num])).toEqual(SERIES.map((s, i) => [s.claim, i + 1]));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try {+ await engine.executeRaw(`UPDATE facts SET embedding=$2::vector, embedded_at=now(), embedding_model='openai:text-embedding-3-large', embedded_text_hash=md5(fact)+ WHERE source_id='default' AND entity_slug=$1`, [slug, VECTOR]);+ await engine.executeRaw(`INSERT INTO facts(source_id,entity_slug,fact,kind,source,visibility,valid_from,confidence,embedding,embedded_at,embedding_model,+ embedded_text_hash,claim_metric,claim_unit,claim_period,claim_value)+ VALUES('default',$1,$2,'fact','synthetic fixture','world',$3::timestamptz,0.7,$4::vector,now(),'openai:text-embedding-3-large',md5($2),+ 'deposit_amount','USD','2026-01-01',$5)`, [slug, UNFENCED.claim, UNFENCED.from, VECTOR, UNFENCED.value]);+ } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+}++/** Re-import the page from its committed file: a prose edit committed through Git, then the owner's sync. */+async function reimport(engine: BrainEngine, root: string, prose: string): Promise<void> {+ writeFileSync(file(root), readFileSync(file(root), 'utf8').replace('Body.', prose));+ git(root, 'add', '--', `${slug}.md`); git(root, 'commit', '-q', '-m', 'hand edit');+ const result = await performSync(engine, { repoPath: root, sourceId: 'default', noPull: true, noEmbed: true, noExtract: true, concurrency: 1 });+ expect(['synced', 'first_sync']).toContain(result.status);+ const [page] = await engine.executeRaw<{ compiled_truth: string }>("SELECT compiled_truth FROM pages WHERE source_id='default' AND slug=$1", [slug]);+ expect(page!.compiled_truth).toContain(prose);+}++beforeAll(() => configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} }));+afterAll(() => resetGateway());++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ describe(`consolidation closes a fenced fact in its fence (${backend})`, () => {+ test('the close lands in the fence cell, the row derives from it, and a re-import keeps the fact closed', () => managedBrain(async ({ engine, ctx, root }) => {+ await seed(engine, ctx);+ const result = await runPhaseConsolidate(engine, { sourceId: 'default', minOldestAgeMs: 0 });+ expect(result.details).toMatchObject({ facts_consolidated: 4, takes_written: 1, buckets_failed: 0 });+ await settleManagedGitEffects(engine);++ const closed = await factRows(engine);+ expect(at((await byClaim(engine, SERIES[0].claim)).valid_until)).toBe(Date.parse(SERIES[1].from));+ expect(at((await byClaim(engine, SERIES[1].claim)).valid_until)).toBe(Date.parse(SERIES[2].from));+ expect((await byClaim(engine, SERIES[2].claim)).valid_until).toBeNull();+ // The unfenced fact has no fence row: it is closed in the database, as before.+ expect(at((await byClaim(engine, UNFENCED.claim)).valid_until)).toBe(Date.parse(SERIES[0].from));+ expect(closed.every(r => r.consolidated_into !== null)).toBe(true);+ expect(git(root, 'status', '--porcelain', '--', `${slug}.md`).trim()).toBe('');++ // The file is the parent: re-importing it keeps every close.+ await reimport(engine, root, 'Edited once.');+ expect(await factRows(engine)).toEqual(closed);+ const fence = cells(root);+ expect(fence.get(1)).toMatchObject({ claim: SERIES[0].claim, active: true, validUntil: SERIES[1].from });+ expect(fence.get(2)).toMatchObject({ claim: SERIES[1].claim, active: true, validUntil: SERIES[2].from });+ expect(fence.get(3)).toMatchObject({ claim: SERIES[2].claim, active: true });+ expect(fence.get(3)!.validUntil).toBeUndefined();+ expect(fence.has(4)).toBe(false);+ }, { setup, databaseUrl }), 180_000);++ test('a fenced fact whose fence is on another page stays open in its file and in the database', () => managedBrain(async ({ engine, ctx, root }) => {+ await seed(engine, ctx);+ const other = 'companies/other-example';+ const moved: ParsedFact = { ...typed(1, { claim: 'The deposit amount was set at $95,000.', value: 95000, from: '2025-11-01', confidence: 0.6 }) };+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: other, request_id: randomUUID(),+ content: `---\ntype: company\ntitle: Other Example\n---\n\n# Other Example\n\n## Facts\n\n${renderFactsTable([moved])}\n` } });+ await settleManagedGitEffects(engine);+ const otherFile = readFileSync(join(root, `${other}.md`), 'utf8');+ // The fact now names this entity while its fence row stays on the other page (as a rename alias or twin merge leaves it).+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try {+ await engine.executeRaw(`UPDATE facts SET entity_slug=$1, embedding=$3::vector, embedded_at=now(), embedding_model='openai:text-embedding-3-large',+ embedded_text_hash=md5(fact) WHERE source_id='default' AND source_markdown_slug=$2`, [slug, other, VECTOR]);+ } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }++ const result = await runPhaseConsolidate(engine, { sourceId: 'default', minOldestAgeMs: 0 });+ expect(result.details).toMatchObject({ facts_consolidated: 5, takes_written: 1, buckets_failed: 0 });+ await settleManagedGitEffects(engine);+ const kept = await byClaim(engine, moved.claim);+ expect(kept).toMatchObject({ row_num: 1, valid_until: null });+ expect(kept.consolidated_into).not.toBeNull();+ expect(readFileSync(join(root, `${other}.md`), 'utf8')).toBe(otherFile);+ expect(at((await byClaim(engine, UNFENCED.claim)).valid_until)).toBe(Date.parse(SERIES[0].from));+ expect(cells(root).get(1)!.validUntil).toBe(SERIES[1].from);+ }, { setup, databaseUrl }), 180_000);+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 557d5fde77..75ac5585a7 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -42,6 +42,7 @@ test/cli-page-writes.test.tstest/colon-slug-windows-5032.test.tstest/company-brain-policy.test.tstest/company-brain-runtime.test.ts+test/consolidate-fenced-close-reimport.test.tstest/consolidate-same-instant-6023.test.tstest/conversation-facts-oversized-sidecar.test.tstest/conversation-facts-purged-claim-7438.test.ts