Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): close the retired interval on replacement (#7214); fence rows take the page date, never the import time (#7247)
garrytane47f3805035e
diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.jsonindex c2b45c4570..fdf692529e 100644--- a/scripts/postgres-arm-weights.json+++ b/scripts/postgres-arm-weights.json@@ -55,6 +55,7 @@"test/facts-insert-guards-7105.test.ts": 8959,"test/facts-publication-large-fence-6898.test.ts": 34731,"test/fence-repair-receipts.test.ts": 11374,+ "test/fence-valid-from-page-date-7247.test.ts": 4000,"test/forecast-journal.test.ts": 17832,"test/frontmatter-reserved-keys-6454.test.ts": 5735,"test/get-chunks-paging.test.ts": 5048,@@ -355,6 +356,7 @@"test/recall-page-fill.test.ts": 7056,"test/receipt-compaction-newest-sync-gbra130.test.ts": 6880,"test/remediation-manual-only.test.ts": 14638,+ "test/remember-replaces-valid-until-7214.test.ts": 4500,"test/repair-apply-pending-6543.test.ts": 51967,"test/repair-embedding-effects.test.ts": 9932,"test/repair-failed-writes-conflict-6429.test.ts": 9306,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex cda8c94855..59d1f80abf 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1053,6 +1053,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.338.0', text: 'On Postgres, a keyword search whose words match more than 50,000 chunks now ranks the first 50,000 matches that pass its filters instead of all of them, so a common-word query on a large brain returns ranked rows in about a second instead of running into the keyword statement timeout and returning none; hybrid search reports `keyword_candidates_incomplete` when the bound applies. Its any-word retry (after an all-words match finds nothing) now matches only the words the planner statistics say fit about 20,000 chunks, still ranking with every word, and also reports `keyword_candidates_incomplete` when it drops a word.' },{ since: '0.60.338.0', text: 'The keyword arm keeps one chunk per page in its candidate pool (Postgres and PGLite), so a page with hundreds of matching chunks no longer pushes every other matching page out of the results.' },{ since: '0.60.338.0', text: 'The title arm\'s any-word retry (after an all-words title match finds nothing) now matches page titles only, as remote callers already did, and drops repeated words (#7135): a date in a question no longer pulls every dated timeline into ranking, which cut a 3-5 s title arm to well under a second on a large brain. A local all-words title match is unchanged.' },+ { since: 'TBD', text: 'A fact that replaces another (`remember` with `replaces`, a near-duplicate supersession, or a published facts batch that supersedes) now also closes the retired fact\'s `valid_until` at the new fact\'s `valid_from`, in the database row and in its struck facts-fence row, so as-of reads no longer see the retired fact as current for the time between (#7214). A backdated replacement, starting on or before the retired fact, leaves the retired interval as it was.' },+ { since: 'TBD', text: 'A facts-fence row with no `valid_from` cell now takes the page\'s stated date (frontmatter `event_date`, `date` or `published`, or a dated filename) on every write path: `put_page`, sync and import used to store the write time, and `extract_facts` used the page\'s creation or import time when the page stated no date (#7247). A page that states no date leaves such rows at the time they were recorded. Rows already stored keep their dates.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 88879feea8..c363570794 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -87,6 +87,7 @@ import { segmentedBodyMatchesFile, segmentedFactsFenceView } from '../page-body/import {duplicateActiveFenceRows,extractFactsFromFenceText,+ FACT_DATE_SOURCES,type FenceExtractedFact,} from '../facts/extract-from-fence.ts';import {@@ -369,7 +370,7 @@ async function listExistingFactsForPage(/** The page a reconcile plans from: its body as strings, or a segmented page whose fences are read from its segments. */type PageFenceInput = { id?: number; slug?: string; source_id?: string; body_storage?: Page['body_storage']; compiled_truth: string | null; timeline: string | null;- effective_date?: Date | string | null };+ effective_date?: Date | string | null; effective_date_source?: string | null };interface FenceReconcilePlan {/** Rows the parsed fence carries (duplicates included), for the pages-with-facts count. */@@ -423,8 +424,9 @@ async function planFenceReconcile(db: BrainEngine, page: PageFenceInput, slug: sreturn null;}// v0.35.4 (D-ENG-1): page.effective_date is the fallback valid_from, so- // trajectory queries see claim dates rather than import dates.- const pageEffectiveDate = page.effective_date ? new Date(page.effective_date) : null;+ // trajectory queries see claim dates rather than import dates. #7247: only a date the+ // page states; a creation or fallback date is when the page was made or imported.+ const pageEffectiveDate = page.effective_date && FACT_DATE_SOURCES.has(page.effective_date_source ?? '') ? new Date(page.effective_date) : null;// #1781: duplicate ACTIVE rows (same claim and source) index once.const duplicates = duplicateActiveFenceRows(parsed.facts);const extracted = extractFactsFromFenceText(parsed.facts, slug, sourceId, { pageEffectiveDate })diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.tsindex e7b532e573..eb099c15cc 100644--- a/src/core/engine-sql/facts.ts+++ b/src/core/engine-sql/facts.ts@@ -128,7 +128,8 @@ export async function insertFact() RETURNING id`)).rows;const id = Number(ins[0].id);- (await tx.run(sqlFragment`UPDATE facts SET expired_at = now(), superseded_by = ${id}+ (await tx.run(sqlFragment`UPDATE facts SET expired_at = now(), superseded_by = ${id},+ valid_until = CASE WHEN valid_from < ${validFrom}::timestamptz AND (valid_until IS NULL OR valid_until > ${validFrom}::timestamptz) THEN ${validFrom}::timestamptz ELSE valid_until ENDWHERE id = ${supersedeId} AND expired_at IS NULL`)).rows;return id;});diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.tsindex 1d52c52809..70e215a648 100644--- a/src/core/facts-fence.ts+++ b/src/core/facts-fence.ts@@ -663,8 +663,9 @@ export function factsFenceEditor<T extends { compiled_truth: string; timeline: s}rows.push(factRow(newRow, newRow.rowNum));},- strike(rowNum: number, by: number): void {- const struck = (f: ParsedFact): ParsedFact => f.rowNum === rowNum ? { ...f, active: false, supersededBy: by, context: `superseded by #${by}` } : f;+ strike(rowNum: number, by: number, validUntil?: string): void {+ const struck = (f: ParsedFact): ParsedFact => f.rowNum === rowNum+ ? { ...f, active: false, supersededBy: by, context: `superseded by #${by}`, ...(validUntil ? { validUntil } : {}) } : f;for (const key of ['compiled_truth', 'timeline'] as const) {if (key === section && rows) {if (!rows.some(f => f.rowNum === rowNum)) continue;@@ -806,12 +807,12 @@ export function factsFenceSection(page: { compiled_truth: string | null; timelin* #6686: strike fence row `rowNum` as superseded by row `by` in whichever section's fence holds it (a split page can* hold the old row in the other section than the one the new row went to); a page without the row is returned as is.*/-export function strikeFactRowInPage<T extends { compiled_truth: string; timeline: string }>(page: T, rowNum: number, by: number): T {+export function strikeFactRowInPage<T extends { compiled_truth: string; timeline: string }>(page: T, rowNum: number, by: number, validUntil?: string): T {for (const key of ['compiled_truth', 'timeline'] as const) {const rows = parseFactsFence(page[key]).facts;if (!rows.some(f => f.rowNum === rowNum)) continue;return { ...page, [key]: replaceOrInsertFactsFence(page[key], renderFactsTable(rows.map(f => f.rowNum === rowNum- ? { ...f, active: false, supersededBy: by, context: `superseded by #${by}` } : f))) };+ ? { ...f, active: false, supersededBy: by, context: `superseded by #${by}`, ...(validUntil ? { validUntil } : {}) } : f))) };}return page;}diff --git a/src/core/facts/extract-from-fence.ts b/src/core/facts/extract-from-fence.tsindex 831cee946b..0e294bf51b 100644--- a/src/core/facts/extract-from-fence.ts+++ b/src/core/facts/extract-from-fence.ts@@ -41,6 +41,18 @@import { attributionCompatible } from './attribution.ts';import type { NewFact, FactKind, FactVisibility } from '../engine.ts';import type { ParsedFact } from '../facts-fence.ts';+import { computeEffectiveDate } from '../effective-date.ts';++/** #7247: the page dates that say when its content happened. A page's creation or import time is not one. */+export const FACT_DATE_SOURCES: ReadonlySet<string> = new Set(['event_date', 'date', 'published', 'filename']);++/** #7247: the fallback valid_from for a page's fence rows without a cell, or null when the page states no such date. */+export function pageFactDate(page: { slug: string; frontmatter?: Record<string, unknown> | null; timeZone?: string | null }): Date | null {+ const invalid = new Date(Number.NaN);+ const { date, source } = computeEffectiveDate({ slug: page.slug, frontmatter: page.frontmatter ?? {}, filename: page.slug.split('/').pop() ?? null,+ timeZone: page.timeZone ?? undefined, createdAt: invalid, updatedAt: invalid });+ return date && source && FACT_DATE_SOURCES.has(source) ? date : null;+}/*** Fence-extracted fact row. Structural superset of `NewFact` with thediff --git a/src/core/facts/supersede-interval.ts b/src/core/facts/supersede-interval.tsnew file mode 100644index 0000000000..f97e2b85a2--- /dev/null+++ b/src/core/facts/supersede-interval.ts@@ -0,0 +1,10 @@+/**+ * #7214: when a fact replaces another, the retired fact's validity interval ends where the replacement's begins.+ * That holds only when the replacement starts after the retired fact and before any end the retired fact already+ * has; a backdated replacement leaves the interval as it was (null means: keep the stored valid_until).+ */+export function supersededValidUntil(retired: { valid_from: Date | string; valid_until?: Date | string | null }, replacementFrom: Date): Date | null {+ const next = replacementFrom.getTime();+ const until = retired.valid_until == null ? null : new Date(retired.valid_until).getTime();+ return next > new Date(retired.valid_from).getTime() && (until === null || until > next) ? replacementFrom : null;+}diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex 214ed6d27b..d7bea35dc4 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -5,7 +5,7 @@ import type { PageSnapshot } from '../page-state/types.ts';import { pipelined } from '../page-state/transactions.ts';import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../facts-fence.ts';import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../takes-fence.ts';-import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';+import { extractFactsFromFenceText, pageFactDate } from '../facts/extract-from-fence.ts';import { takesPreparation } from '../takes-write.ts';import { parseTimelineEntries } from '../link-extraction.ts';import { eachStoredTimelineRow, extractTimelineFromContent, hasExtractorDetail, supersededCitationTimeline, TimelineKeySet,@@ -486,11 +486,11 @@ export async function reprojectTimelineRow(tx: BrainEngine, pageId: number, bodyreturn true;}-export function compileCanonicalProjections(page: ParsedPage, slug: string, sourceId: string) {+export function compileCanonicalProjections(page: ParsedPage, slug: string, sourceId: string, factDate: Date | null = null) {const scan=scanCanonicalFences(page);if(scan.defects.length) throw fenceOperationError(scan.defects[0]!, slug, sourceId);const fields:Array<[FenceSection,string]>=[['body',page.compiled_truth],['timeline',page.timeline ?? '']];- return { factRows: extractFactsFromFenceText(scan.facts,slug,sourceId), takes: scan.takes, sections: scan.sections, quoted: scan.quoting ? quotedFenceRows(fields) : null };+ return { factRows: extractFactsFromFenceText(scan.facts,slug,sourceId,{ pageEffectiveDate: factDate }), takes: scan.takes, sections: scan.sections, quoted: scan.quoting ? quotedFenceRows(fields) : null };}/**@@ -532,7 +532,9 @@ function takeCollision(rows: number[], sections: Map<number, FenceSection>, slug*/export async function prepareCanonicalProjections(engine: BrainEngine, page: ParsedPage, slug: string, sourceId: string,prior: PageSnapshot | null, writer: ProjectionWriter, policy?: TimelineWritePolicy): Promise<(tx: BrainEngine, pageId?: number) => Promise<CanonicalProjectionResult>> {- const { factRows, takes, quoted, sections } = compileCanonicalProjections(page, slug, sourceId);+ // #7247: a fence row without a valid_from takes the page's stated date, as extract_facts does, never the import time.+ const factDate = pageFactDate({ slug, frontmatter: page.frontmatter, timeZone: await engine.getConfig('brain.timezone') });+ const { factRows, takes, quoted, sections } = compileCanonicalProjections(page, slug, sourceId, factDate);// #6259: a page the content-quality gate hid as junk projects no facts or takes. Rows projected before it// was quarantined are left as they are (hiding them would need a new row state); only new projection stops.const projectFences = !isQuarantined(page.frontmatter);diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex db5e92678c..f4b6b2b973 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -9,6 +9,7 @@ import { factsFenceEditor, factsFenceSection, parseFactsFence, formatFenceDate }import { serializePageToMarkdown } from '../markdown.ts';import { wholeBodySnapshot } from './segmented-apply.ts';import { assertFactNotWithdrawn, decideSingleFact, factWithdrawnRefusal, type FactCandidate } from '../facts/single-prepare.ts';+import { supersededValidUntil } from '../facts/supersede-interval.ts';import { assertFactNotPurged, isFactWithdrawn } from '../facts/withdrawal.ts';import { samePageRewording, warnSamePageShadow } from '../facts/same-page-shadow.ts';import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';@@ -215,7 +216,8 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ...(fact.attributed_to ? { attributedTo: fact.attributed_to } : {}) }));// Strike the superseded row in this page's fence, as the remember mutation does (#6686: in the section that holds it).if (supersedes && rowNum !== undefined && supersedes.source_markdown_slug === row.slug && supersedes.row_num != null) {- fence.strike(Number(supersedes.row_num), rowNum);+ const until = supersededValidUntil(supersedes, fact.valid_from!);+ fence.strike(Number(supersedes.row_num), rowNum, until ? formatFenceDate(until) : undefined);}entries.push({ fact, duplicateId: null, rowNum, supersedes, gate });}@@ -282,8 +284,8 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writif (taint) await recordTaintEdges(tx, { table: 'facts', id: ids[ids.length - 1], sourceId: row.source_id }, taint.inputs);if (entry.gate) await recordFlaggedRow(tx, entry.gate, { table: 'facts', id: ids[ids.length - 1], sourceId: row.source_id });if (entry.supersedes) {- await tx.executeRaw('UPDATE facts SET expired_at=COALESCE(expired_at,now()),superseded_by=$3 WHERE id=$1 AND source_id=$2',- [entry.supersedes.id, row.source_id, ids[ids.length - 1]]);+ await tx.executeRaw('UPDATE facts SET expired_at=COALESCE(expired_at,now()),superseded_by=$3,valid_until=COALESCE($4::timestamptz,valid_until) WHERE id=$1 AND source_id=$2',+ [entry.supersedes.id, row.source_id, ids[ids.length - 1], supersededValidUntil(entry.supersedes, entry.fact.valid_from!)]);superseded++;}}diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex cc6bcd9af4..8033c2f411 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -10,6 +10,7 @@ import { serializePageToMarkdown } from '../markdown.ts';import { pageBodyOverCeilingError } from '../page-body/page-shape.ts';import { materializedPage, segmentedOverCeiling } from './segmented-apply.ts';import { assertFactNotWithdrawn, decideReplacement, decideSingleFact, prepareFactEmbedding, type SingleFactIntent } from '../facts/single-prepare.ts';+import { supersededValidUntil } from '../facts/supersede-interval.ts';import { factEmbeddingDisabled } from '../embedding-disabled.ts';import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';import { preparePageMutation } from './page-prepare.ts';@@ -143,6 +144,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeinput: gateInput(requestChannelTrust(row) ?? { tier: 'unknown', origin: null }, row.id), cfg: await loadWriteGateConfig(engine) });if (gate.action === 'reject') throw writeGateRejectedError(gate.assessment);if (gate.action === 'hold') return { observedRevision, validate, apply: async tx => heldOutcome(gate.assessment, (await recordWriteGateHold(tx, gate.hold!)).holdId) };+ const retiredUntil = status === 'superseded' ? supersededValidUntil(decision.candidate!, validFrom) : null;let page: PreparedMutation | undefined;let rowNum: number | undefined;let fencesNormalized: Record<string, unknown> = {};@@ -167,7 +169,9 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequerowNum = appended.rowNum;let next = { ...fenced, [section]: appended.body };const old = decision.candidate;- if (status === 'superseded' && old?.source_markdown_slug === row.slug && old.row_num != null) next = strikeFactRowInPage(next, Number(old.row_num), rowNum);+ if (status === 'superseded' && old?.source_markdown_slug === row.slug && old.row_num != null) {+ next = strikeFactRowInPage(next, Number(old.row_num), rowNum, retiredUntil ? formatFenceDate(retiredUntil) : undefined);+ }const content = serializePageToMarkdown({ ...base, ...next }, snapshot.tags);// Reuse the canonical parser/chunker and durable filesystem publication.// The original caller revision was checked above; this CAS binds this render.@@ -198,8 +202,8 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeid = inserted.id;}if (status === 'superseded') {- await tx.executeRaw(`UPDATE facts SET expired_at=now(),superseded_by=$3- WHERE id=$1 AND source_id=$2 AND expired_at IS NULL`, [decision.candidate!.id, row.source_id, id]);+ await tx.executeRaw(`UPDATE facts SET expired_at=now(),superseded_by=$3,valid_until=COALESCE($4::timestamptz,valid_until)+ WHERE id=$1 AND source_id=$2 AND expired_at IS NULL`, [decision.candidate!.id, row.source_id, id, retiredUntil]);noteBelief({ kind: 'superseded', oldId: Number(decision.candidate!.id), newId: id });}const contestedBy = contestedOld ? await recordContestedFact(tx, { sourceId: row.source_id, oldId: contestedOld.id,diff --git a/test/eval-contradictions/no-valid-until-write.test.ts b/test/eval-contradictions/no-valid-until-write.test.tsindex 1ca64b8d32..25dcda83f8 100644--- a/test/eval-contradictions/no-valid-until-write.test.ts+++ b/test/eval-contradictions/no-valid-until-write.test.ts@@ -73,13 +73,16 @@ import { join } from 'node:path';const VALID_UNTIL_WRITE_ALLOWLIST: ReadonlySet<string> = new Set(['src/core/cycle/extract-facts.ts','src/core/cycle/phases/consolidate.ts',+ 'src/core/engine-sql/facts.ts', // #7214: insertFact's supersede closes the retired interval at the replacement's valid_from'src/core/facts/forget.ts','src/core/facts/insert-guard-schema.ts','src/core/facts/proposal-supersede.ts','src/core/facts/withdrawal.ts','src/core/facts/withdrawal-schema.ts','src/core/persistence/canonical-projections.ts',+ 'src/core/persistence/facts-prepare.ts', // #7214: a published supersession closes the retired interval (supersededValidUntil)'src/core/persistence/loop-fact-retirement.ts',+ 'src/core/persistence/memory-prepare.ts', // #7214: remember (replaces or cosine) closes the retired interval (supersededValidUntil)'src/core/persistence/prepared-maintenance.ts','src/core/postgres-engine.ts','src/core/pglite-engine.ts',diff --git a/test/fence-valid-from-page-date-7247.test.ts b/test/fence-valid-from-page-date-7247.test.tsnew file mode 100644index 0000000000..e582128d8f--- /dev/null+++ b/test/fence-valid-from-page-date-7247.test.ts@@ -0,0 +1,82 @@+/**+ * #7247: a facts-fence row without a valid_from cell takes the page's event date (frontmatter date, event_date,+ * published, or a dated filename), never the time the page was imported. Both fence readers agree: the managed+ * canonical projection (put_page, sync, import) and the extract_facts cycle phase.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';++let engine: BrainEngine;++async function call(name: string, params: Record<string, unknown>) {+ const res = await dispatchToolCall(engine, name, params, { remote: false });+ return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text!) as Record<string, any> };+}+const fence = (validFrom: string) => [+ '## Facts', '', '<!--- gbrain:facts:begin -->',+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',+ `| 1 | Acme Example ARR was 100 units | fact | 1.0 | private | medium | ${validFrom} | | test | |`,+ '<!--- gbrain:facts:end -->', ''].join('\n');+async function validFromOf(slug: string): Promise<string> {+ const [r] = await engine.executeRaw<{ valid_from: Date | string }>('SELECT valid_from FROM facts WHERE source_markdown_slug = $1', [slug]);+ return new Date(r!.valid_from).toISOString().slice(0, 10);+}++for (const backend of testBackends()) {+ describe(backend, () => {+ let pglite: PGLiteEngine | undefined;+ let template: Awaited<ReturnType<typeof persistencePostgresTemplate>> | undefined;+ let close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (backend === 'postgres') template = await persistencePostgresTemplate(requirePostgresTestDatabase());+ else { pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); }+ }, 120_000);+ afterAll(async () => { resetGateway(); await template?.dispose(); await pglite?.disconnect(); });+ beforeEach(async () => {+ if (pglite) { engine = pglite; await disposePersistenceConsumer(engine); await resetPgliteState(pglite); }+ else { const c = await template!.clone(); engine = c.engine; close = c.close; }+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ }, 60_000);+ afterEach(async () => { if (close) { await disposePersistenceConsumer(engine); await close(); close = undefined; } });++ describe('#7247 fence valid_from fallback', () => {+ test('a blank cell takes the page date, not the import time', async () => {+ const put = await call('put_page', { slug: 'companies/acme-example', content: `---\ntitle: Acme Example\ntype: company\ndate: 2025-05-01\n---\n# Acme Example\n\n${fence('')}` });+ expect(put.isError).toBe(false);+ expect(await validFromOf('companies/acme-example')).toBe('2025-05-01');+ });+ test('an explicit cell wins over the page date', async () => {+ await call('put_page', { slug: 'companies/acme-example', content: `---\ntitle: Acme Example\ntype: company\ndate: 2025-05-01\n---\n# Acme Example\n\n${fence('2025-02-01')}` });+ expect(await validFromOf('companies/acme-example')).toBe('2025-02-01');+ });+ });++ describe('#7247 a creation date is not an event date', () => {+ test('a page dated only by created: leaves blank cells at the recorded time (projection and extract_facts)', async () => {+ const today = new Date().toISOString().slice(0, 10);+ await call('put_page', { slug: 'companies/acme-example', content: `---\ntitle: Acme Example\ntype: company\ncreated: 2024-01-01\n---\n# Acme Example\n\n${fence('')}` });+ expect(await validFromOf('companies/acme-example')).toBe(today);+ await engine.executeRaw('DELETE FROM facts WHERE source_markdown_slug = $1', ['companies/acme-example']);+ const { runExtractFacts } = await import('../src/core/cycle/extract-facts.ts');+ await runExtractFacts(engine, { sourceId: 'default', slugs: ['companies/acme-example'] });+ expect(await validFromOf('companies/acme-example')).toBe(today);+ });+ test('extract_facts uses a stated page date for blank cells', async () => {+ await call('put_page', { slug: 'companies/acme-example', content: `---\ntitle: Acme Example\ntype: company\ndate: 2025-05-01\n---\n# Acme Example\n\n${fence('')}` });+ await engine.executeRaw('DELETE FROM facts WHERE source_markdown_slug = $1', ['companies/acme-example']);+ const { runExtractFacts } = await import('../src/core/cycle/extract-facts.ts');+ await runExtractFacts(engine, { sourceId: 'default', slugs: ['companies/acme-example'] });+ expect(await validFromOf('companies/acme-example')).toBe('2025-05-01');+ });+ });+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex ccf396b282..931e6f13d8 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -68,6 +68,7 @@ test/fact-purge-lookup-timeout-6511.test.tstest/facts-insert-guards-7105.test.tstest/facts-publication-large-fence-6898.test.tstest/fence-repair-receipts.test.ts+test/fence-valid-from-page-date-7247.test.tstest/forecast-journal.test.tstest/frontmatter-reserved-keys-6454.test.tstest/get-chunks-paging.test.ts@@ -371,6 +372,7 @@ test/purge-sync-tombstone-hold-7130.test.tstest/recall-page-fill.test.tstest/receipt-compaction-newest-sync-gbra130.test.tstest/remediation-manual-only.test.ts+test/remember-replaces-valid-until-7214.test.tstest/repair-apply-pending-6543.test.tstest/repair-embedding-effects.test.tstest/repair-failed-writes-conflict-6429.test.tsdiff --git a/test/remember-replaces-valid-until-7214.test.ts b/test/remember-replaces-valid-until-7214.test.tsnew file mode 100644index 0000000000..20eb767e97--- /dev/null+++ b/test/remember-replaces-valid-until-7214.test.ts@@ -0,0 +1,88 @@+/**+ * #7214: a replacement closes the retired fact's validity interval. When the+ * replacement starts after the retired fact, the retired row's valid_until is+ * the replacement's valid_from, in the facts table and in the struck fence row,+ * and a re-extraction of the page keeps it. A backdated replacement (starting+ * on or before the retired fact) leaves the interval as it was.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { parseFactsFence } from '../src/core/facts-fence.ts';++let engine: BrainEngine;++async function call(name: string, params: Record<string, unknown>) {+ const res = await dispatchToolCall(engine, name, params, { remote: false });+ return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text!) as Record<string, any> };+}+async function remember(fact: string, extra: Record<string, unknown> = {}) {+ return call('remember', { fact, provenance: 'test', entity: 'people/alice-example', ...extra });+}+async function validUntil(id: string): Promise<string | null> {+ const [r] = await engine.executeRaw<{ valid_until: Date | string | null }>('SELECT valid_until FROM facts WHERE id = $1', [Number(id)]);+ return r!.valid_until === null ? null : new Date(r!.valid_until).toISOString().slice(0, 10);+}+async function fenceRows() {+ const page = await call('get_page', { slug: 'people/alice-example', include_content: true });+ return parseFactsFence(String(page.body.content ?? page.body.compiled_truth)).facts;+}++for (const backend of testBackends()) {+ describe(backend, () => {+ let pglite: PGLiteEngine | undefined;+ let template: Awaited<ReturnType<typeof persistencePostgresTemplate>> | undefined;+ let close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (backend === 'postgres') template = await persistencePostgresTemplate(requirePostgresTestDatabase());+ else { pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); }+ }, 120_000);+ afterAll(async () => { resetGateway(); __setEmbedTransportForTests(null); await template?.dispose(); await pglite?.disconnect(); });+ beforeEach(async () => {+ if (pglite) { engine = pglite; await disposePersistenceConsumer(engine); await resetPgliteState(pglite); }+ else { const c = await template!.clone(); engine = c.engine; close = c.close; }+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ await call('put_page', { slug: 'people/alice-example', content: '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n\nA person.\n' });+ }, 60_000);+ afterEach(async () => { if (close) { await disposePersistenceConsumer(engine); await close(); close = undefined; } });++ describe('#7214 remember replaces closes the retired interval', () => {+ test('a later replacement sets valid_until to its valid_from in the row and the fence', async () => {+ const old = await remember('The test charge is 100 units.', { valid_from: '2026-01-01' });+ const res = await remember('The test charge is 200 units.', { valid_from: '2026-03-01', replaces: old.body.id });+ expect(res.body.status).toBe('superseded');+ expect(await validUntil(old.body.id)).toBe('2026-03-01');+ const struck = (await fenceRows()).find(f => f.claim === 'The test charge is 100 units.');+ expect(struck?.active).toBe(false);+ expect(struck?.validUntil).toBe('2026-03-01');+ expect(await validUntil(res.body.id)).toBeNull();+ });++ test('a backdated replacement leaves the retired interval open', async () => {+ const old = await remember('The test charge is 100 units.', { valid_from: '2026-03-01' });+ const res = await remember('The test charge is 200 units.', { valid_from: '2026-01-01', replaces: old.body.id });+ expect(res.body.status).toBe('superseded');+ expect(await validUntil(old.body.id)).toBeNull();+ });+ });++ describe('#7214 insertFact supersede closes the retired interval', () => {+ test('later replacement closes at its valid_from; backdated leaves it open', async () => {+ const a = await engine.insertFact({ fact: 'The test charge is 100 units.', entity_slug: 'people/alice-example', source: 'test', valid_from: new Date('2026-01-01') }, { source_id: 'default' }); // gbrain-allow-direct-insert: #7214 probe of the engine supersede path+ const b = await engine.insertFact({ fact: 'The test charge is 200 units.', entity_slug: 'people/alice-example', source: 'test', valid_from: new Date('2026-03-01') }, { source_id: 'default', supersedeId: a.id }); // gbrain-allow-direct-insert: #7214 probe of the engine supersede path+ expect(b.status).toBe('superseded');+ expect(await validUntil(String(a.id))).toBe('2026-03-01');+ const c = await engine.insertFact({ fact: 'The test charge is 50 units.', entity_slug: 'people/alice-example', source: 'test', valid_from: new Date('2025-06-01') }, { source_id: 'default', supersedeId: b.id }); // gbrain-allow-direct-insert: #7214 probe of the engine supersede path+ expect(c.status).toBe('superseded');+ expect(await validUntil(String(b.id))).toBeNull();+ });+ });+ });+}