Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): a live fact whose context says "superseded by #N" stays live

garrytan7cc44b00208b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c399d216c9..f94a99be95 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,7 +12,7 @@ identifiers and attribution are available in the pre-removal Git revision
## [Unreleased]
-**Fact extraction and capture now record who said what, and where a page came from, more faithfully.** Lines you quote with `>` in a turn are no longer saved as your own facts, a Claude Code Remote Control session is yours rather than an agent's, facts that open with a log word ("Notes from", "Watched") link to the one entity they name, a facts batch refused for a stale embedding config lands once the write owner restarts with the fixed config, `transcripts ingest --facts --json` reports a budget stop instead of reading complete, and a remote timeline entry, link or tag no longer overwrites how its page entered the brain.
+**Fact extraction and capture now record who said what, and where a page came from, more faithfully.** Lines you quote with `>` in a turn are no longer saved as your own facts, a Claude Code Remote Control session is yours rather than an agent's, facts that open with a log word ("Notes from", "Watched") link to the one entity they name, a facts batch refused for a stale embedding config lands once the write owner restarts with the fixed config, `transcripts ingest --facts --json` reports a budget stop instead of reading complete, a remote timeline entry, link or tag no longer overwrites how its page entered the brain, and a live fact whose context note happens to read "superseded by #N" is no longer hidden as superseded.
### Itemized changes
@@ -22,8 +22,9 @@ identifiers and attribution are available in the pre-removal Git revision
- `src/core/transcripts/ingest-facts.ts`, `src/commands/transcripts.ts`: `transcripts ingest --facts` returns `budgetExhausted`, `budgetReason`, `pagesSkippedTooLarge` and `pagesLockSkipped` in `--json` and prints a line for each in the human summary. Reported and first fixed by @harjothkhara (#8722, #8757).
- `src/core/context/session-speaker.ts`: a headless session that a `claude remote-control` server (or its `rc`, `remote`, `sync`, `bridge` aliases) hosts over `--sdk-url` is the owner's; a worker that session launches is still agent-launched. Existing speaker sidecars keep their first record. Reported and first fixed by @exGeni (#8080, #8892).
- `src/core/persistence/page-mutations.ts`: only remote writes that supply page text (put_page, edit_page, append_page, capture) stamp `mcp:<operation>` provenance; other remote page writes keep the stored `source_kind`, `ingested_via` and `ingested_at`. Reported and first fixed by @zsimovanforgeops (#8667).
-- Docs: `docs/guides/ambient-writeback.md` (Remote Control sessions under automatic detection) and the KEY_FILES entries for the touched files.
-- Tests: `test/facts/writeback-gate.test.ts`, `test/facts-embedding-refusal-heal-8526.test.ts` (PGLite and Postgres), `test/facts-subject-infer.test.ts`, `test/extract-conversation-facts.test.ts`, `test/agent-session-speaker-8064.serial.test.ts`, `test/put-page-provenance.test.ts`.
+- `src/core/facts-fence.ts`: only a struck (`~~claim~~`) row takes a `superseded by #N` link from its context cell, the way only a struck row reads `forgotten:`; a live row keeps the text as context and stays in recall. A live row an older build linked is cleared by a full reconcile, which `gbrain dream --phase extract_facts --source <id>` runs; the nightly cycle clears it only when the page changes, and on a managed brain an earlier reconcile receipt for an unchanged page can replay until then. Reported and first fixed by @alanshurafa (#9069, #9073).
+- Docs: `docs/guides/ambient-writeback.md` (Remote Control sessions under automatic detection), `docs/guides/fence-format.md` (the `context` column) and the KEY_FILES entries for the touched files.
+- Tests: `test/facts/writeback-gate.test.ts`, `test/facts-embedding-refusal-heal-8526.test.ts` (PGLite and Postgres), `test/facts-subject-infer.test.ts`, `test/extract-conversation-facts.test.ts`, `test/agent-session-speaker-8064.serial.test.ts`, `test/put-page-provenance.test.ts`, `test/facts-fence.test.ts`, `test/extract-facts-phase.test.ts`, `test/fence-write.test.ts`.
## [0.60.620.0] - 2026-11-09
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index d4b0b1db1a..207d3c974e 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -98,7 +98,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/extraction-review.ts` — Extraction quarantine lane markers, sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op, which also records `distinct` decisions (`distinct_from`); every decision publishes through the page door (Git first on a repository source, the database on a repo-less one) under `persistence/publication-guard.ts`, with the revision it read. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).
-- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`; #6385: cells are read by the column the header names (`factsHeaderLayout`, `FACTS_FENCE_COLUMNS`), so an unknown, repeated or missing required header column is one `FACTS_TABLE_MALFORMED` and no rows, a header in canonical order keeps the positional typed tail, and `factsRowProblem` lets a row leave off only trailing optional columns and refuses a non-empty cell past the layout; a confidence cell outside 0..1 or not a plain number is `FACTS_TABLE_MALFORMED`, a `claim_value` cell parses strictly (plain/scientific numbers, `1,234,567` separators, a leading currency symbol, a k/M/B suffix that scales; anything else such as `1,5` or `0.9abc` is `FACTS_TABLE_MALFORMED`), `formatFenceDate` writes UTC-midnight dates as `YYYY-MM-DD` and any other instant as a UTC timestamp so TTLs and write-time `valid_from` round-trip, so the page is non-authoritative instead of failing the DB CHECK), render (`renderFactsTable`), and strip (`stripFactsFence({keepVisibility})` — the remote-read privacy boundary `get_page`/`fetch_page`/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: `replaceOrInsertFactsFence(body, fenceBlock)` replaces an existing fence in place or inserts a fresh `## Facts` section ABOVE the timeline sentinel (`timelineSentinelOffset`, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (`upsertFactRow`, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. `upsertFactRow` throws `FenceRewriteRefusal` (fence-shared.ts) when the fence it starts from parses with warnings (#6385 R12): it re-renders the parsed rows, so a rewrite would delete the rows the parser skipped. `restoreHiddenFactRows(incoming, existing)` is the row-level, vis... (line truncated to 2000 chars)
+- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`; #6385: cells are read by the column the header names (`factsHeaderLayout`, `FACTS_FENCE_COLUMNS`), so an unknown, repeated or missing required header column is one `FACTS_TABLE_MALFORMED` and no rows, a header in canonical order keeps the positional typed tail, and `factsRowProblem` lets a row leave off only trailing optional columns and refuses a non-empty cell past the layout; only a struck row reads `superseded by #N` (`supersededBy`) or `forgotten:` from its context cell, so on a live row that text is plain context (#9069); a confidence cell outside 0..1 or not a plain number is `FACTS_TABLE_MALFORMED`, a `claim_value` cell parses strictly (plain/scientific numbers, `1,234,567` separators, a leading currency symbol, a k/M/B suffix that scales; anything else such as `1,5` or `0.9abc` is `FACTS_TABLE_MALFORMED`), `formatFenceDate` writes UTC-midnight dates as `YYYY-MM-DD` and any other instant as a UTC timestamp so TTLs and write-time `valid_from` round-trip, so the page is non-authoritative instead of failing the DB CHECK), render (`renderFactsTable`), and strip (`stripFactsFence({keepVisibility})` — the remote-read privacy boundary `get_page`/`fetch_page`/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: `replaceOrInsertFactsFence(body, fenceBlock)` replaces an existing fence in place or inserts a fresh `## Facts` section ABOVE the timeline sentinel (`timelineSentinelOffset`, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (`upsertFactRow`, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. `upsertFactRow` throws `FenceRewriteRefusal` (fence-shared.ts) when the fence it starts from parses with warnings (#6385 R12): it re-renders the parsed rows, so a rewrite would delete the rows the parser skipped. `restoreHiddenFactRows(incoming, existing)` is the row-level, vis... (line truncated to 2000 chars)
- `src/core/facts/attribution.ts` — speaker attribution's one dedup rule: `attributionCompatible(a, b)` is false only for two different known speakers (`user`, `assistant`, `other`); NULL (no recorded speaker) is compatible with either. Every dedup path applies it before candidate limits: `findCandidateDuplicates` (`attributedTo` option, SQL pre-limit), `decideSingleFact` exact and cosine matches, capture exact/near matches, hot-memory collapse (`collapseHotFacts` splits a fingerprint group by speaker when it holds two), fence reindex (`duplicateActiveFenceRows`) and the managed batch key (`facts-prepare.ts`). `facts.attributed_to` (migration v215) is written by the extractor (`facts.attribution`, default on per `docs/eval/decisions/p2-e3-heldout/`; `false` opts out), carried in the fence's 15th cell (only on rows that have it), returned by `recall` and hot memory, rendered `(assistant said)` in context packs, and kept out of `consolidate` (takes are the user's own). Pinned by `test/facts/speaker-attribution.test.ts`.
- `src/core/fence-shared.ts` — shared pipe-table primitives for the `## Takes` (`takes-fence.ts`) and `## Facts` (`facts-fence.ts`) fences: `parseRowCells`, `isSeparatorRow`, `stripStrikethrough`, `parseStringCell`, `escapeFenceCell`, and the rewrite guard (#6385 R12) `assertFenceRewritable` / `FenceRewriteRefusal` that `upsertFactRow`, `upsertTakeRow`, `supersedeRow` and `mergePhantomFenceRows` throw when their input fence parses with warnings (the message names the fence only; the warnings, which embed row text, stay on the error). `parseRowCells` is escape-aware: `\|` stays inside its cell and decodes back to a literal `|` (exact inverse of `escapeFenceCell`), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. `escapeFenceCell` also encodes fence-marker text (`gbrain:facts:begin` and the three siblings) by lengthening the ampersand run before `#58;` (`gbrain:X` → `gbrain&#58;X`, a literal `gbrain&#58;X` → `gbrain&amp;#58;X`), and `decodeFenceCell` (the decoder `parseRowCells` and `fence-repair/raw-rows.ts` share) removes exactly one level, so a claim that quotes a marker never becomes a live marker and a literal entity round-trips byte-identically; the lexical fail-closed privacy rule is unchanged. Pinned by the escape cases in `test/facts-fence.test.ts` + the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.
diff --git a/docs/guides/fence-format.md b/docs/guides/fence-format.md
index e99ef2c904..d053cfdd7a 100644
--- a/docs/guides/fence-format.md
+++ b/docs/guides/fence-format.md
@@ -47,7 +47,7 @@ Facts cells are read by the column the header names, in any order. A header with
| 7 | `valid_from` | free text | no | - | When it became true (`YYYY-MM-DD`), or empty. |
| 8 | `valid_until` | free text | no | - | When it stopped being true, or empty. |
| 9 | `source` | free text | no | - | Where it came from, free text. |
-| 10 | `context` | free text | yes | - | Free text. `superseded by #N` names the row that replaced a struck row; `forgotten: ...` marks a row withdrawn with `forget`. |
+| 10 | `context` | free text | yes | - | Free text. On a struck row, `superseded by #N` names the row that replaced it and `forgotten: ...` marks it withdrawn with `forget`. On a live row both are plain text. |
| 11 | `claim_metric` | free text | yes | - | Metric of a typed claim (`mrr`, `team_size`, ...), or empty. |
| 12 | `claim_value` | a number, optionally with 1,234 separators or a k/M/B suffix | yes | - | Value of a typed claim. |
| 13 | `claim_unit` | free text | yes | - | Unit (`USD`, `people`, ...), or empty. |
diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.ts
index 207c8afdb6..4ad1a46306 100644
--- a/src/core/facts-fence.ts
+++ b/src/core/facts-fence.ts
@@ -354,8 +354,8 @@ export function parseFactsFence(body: string): FactsFenceParseResult {
const { text: claimText, struck } = stripStrikethrough(claimRaw);
const context = parseStringCell(contextRaw);
- const supersededBy = parseSupersededByFromContext(context);
- const forgotten = parseForgottenFromContext(context);
+ const supersededBy = struck ? parseSupersededByFromContext(context) : undefined;
+ const forgotten = struck && parseForgottenFromContext(context);
facts.push({
rowNum,
@@ -370,7 +370,7 @@ export function parseFactsFence(body: string): FactsFenceParseResult {
context,
active: !struck,
supersededBy,
- forgotten: struck ? forgotten : false,
+ forgotten,
// v0.35.4 — typed-claim fields, all optional.
claimMetric: parseStringCell(claimMetricRaw),
claimValue,
diff --git a/test/extract-facts-phase.test.ts b/test/extract-facts-phase.test.ts
index 93035aba2f..ee2a4a8e35 100644
--- a/test/extract-facts-phase.test.ts
+++ b/test/extract-facts-phase.test.ts
@@ -1589,6 +1589,57 @@ describe('runExtractFacts — v0.46 (#3014) supersession transport + heal', () =
expect(healed.expired_at).not.toBeNull();
});
+ // #9069: only a struck row may carry the link. A live row whose context
+ // cell happens to read "superseded by #N" stays live and unlinked.
+ const LIVE_NOTE_FENCE = FACT_FENCE(
+ `| 1 | Will close by Q2 | commitment | 0.6 | world | medium | 2026-01-01 | | call | superseded by #2 |
+| 2 | Closed in Q3 | fact | 1.0 | world | high | 2026-07-01 | | call | |`,
+ );
+ const row1Of = async () => (await readSupersessionCols()).find(x => x.row_num === 1)!;
+
+ test('#9069: a live row with a "superseded by #2" context lands unlinked and stays out of supersessions', async () => {
+ await putPage('people/deal', LIVE_NOTE_FENCE);
+ const r = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect(r.factsInserted).toBe(2);
+ expect(r.warnings.filter(w => w.includes('superseded'))).toEqual([]);
+ const row1 = await row1Of();
+ expect(row1.superseded_by).toBeNull();
+ expect(row1.expired_at).toBeNull();
+ expect((await engine.listSupersessions('default')).length).toBe(0);
+ });
+
+ test('#9069: removing the strikethrough from a superseded row clears its link', async () => {
+ await putPage('people/deal', SUPERSEDE_FENCE);
+ await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect((await row1Of()).superseded_by).not.toBeNull();
+
+ await putPage('people/deal', LIVE_NOTE_FENCE);
+ await runExtractFacts(engine, { slugs: ['people/deal'] });
+ const row1 = await row1Of();
+ expect(row1.superseded_by).toBeNull();
+ expect(row1.expired_at).toBeNull();
+ });
+
+ // Existing data: the full walk that `gbrain dream --phase extract_facts` runs clears it without a page edit.
+ test('#9069: a live row stored with a wrong link by an older build is cleared by a full reconcile, page unchanged', async () => {
+ await putPage('people/deal', LIVE_NOTE_FENCE);
+ await runExtractFacts(engine, { slugs: ['people/deal'] });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await (engine as any).db.query(
+ `UPDATE facts SET superseded_by = (SELECT id FROM facts WHERE source_markdown_slug = 'people/deal' AND row_num = 2)
+ WHERE source_markdown_slug = 'people/deal' AND row_num = 1`,
+ );
+ expect((await row1Of()).superseded_by).not.toBeNull();
+ const idsBefore = await readIds();
+
+ await runExtractFacts(engine, {});
+ const row1 = await row1Of();
+ expect(row1.superseded_by).toBeNull();
+ expect(row1.expired_at).toBeNull();
+ expect(await readIds()).toEqual(idsBefore);
+ expect((await engine.listSupersessions('default')).length).toBe(0);
+ });
+
test('dangling reference (#N absent from fence) → warning, superseded_by NULL, expired_at set', async () => {
await putPage('people/deal', FACT_FENCE(
`| 1 | ~~Retired claim~~ | commitment | 0.6 | world | medium | 2026-01-01 | | call | superseded by #9 |`,
diff --git a/test/facts-fence.test.ts b/test/facts-fence.test.ts
index 02e3e04005..2eb8524d6a 100644
--- a/test/facts-fence.test.ts
+++ b/test/facts-fence.test.ts
@@ -201,6 +201,17 @@ describe('parseFactsFence — strikethrough semantics (Codex R2-#3 contract)', (
expect(r.facts[0].supersededBy).toBeUndefined();
});
+ test('#9069: an unstruck row whose context cell says "superseded by #N" stays live with no supersededBy', () => {
+ const body = wrapFenceBody(
+ `| 1 | Renewal is due in March | fact | 0.9 | world | medium | 2026-01-01 | | src | superseded by #2 |
+| 2 | Renewal moved to April | fact | 0.9 | world | medium | 2026-02-01 | | src | |`,
+ );
+ const r = parseFactsFence(body);
+ expect(r.warnings).toEqual([]);
+ expect(r.facts[0]).toMatchObject({ active: true, forgotten: false, context: 'superseded by #2' });
+ expect(r.facts[0].supersededBy).toBeUndefined();
+ });
+
test('case-insensitive "Superseded By #N" still parses', () => {
const body = wrapFenceBody(
`| 1 | ~~Old~~ | fact | 0.8 | world | medium | 2026-01-01 | | src | Superseded By #42 |`,
diff --git a/test/fence-write.test.ts b/test/fence-write.test.ts
index efc8737c63..7dbbea2c5a 100644
--- a/test/fence-write.test.ts
+++ b/test/fence-write.test.ts
@@ -430,12 +430,14 @@ describe('writeFactsToFence — stub guard (v0.34.5)', () => {
describe('writeFactsToFence — v0.46 (#3014) supersession-warning seam', () => {
test('forwards an unresolvable `superseded by #N` warning to console.warn', async () => {
- // The reachable shape through this path: writeFactsToFence appends
- // active rows, but `context` is caller-controlled free text, so a
- // "superseded by #N" context re-parses to supersededBy=N. When #N names
- // no row, insertFacts resolves it to NULL + a warning; this test pins
- // that writeFactsToFence forwards that warning to console.warn (the
- // no-swallowed-errors seam) rather than dropping it.
+ // The reachable shape through this path: `fact` and `context` are
+ // caller-controlled free text, and a claim that arrives already wrapped
+ // in `~~ ~~` re-parses as a struck row. A struck row with a
+ // "superseded by #N" context re-parses to supersededBy=N (an unstruck
+ // row never does, #9069). When #N names no row, insertFacts resolves it
+ // to NULL + a warning; this test pins that writeFactsToFence forwards
+ // that warning to console.warn (the no-swallowed-errors seam) rather
+ // than dropping it.
const captured: string[] = [];
const original = console.warn;
// eslint-disable-next-line no-console
@@ -445,7 +447,7 @@ describe('writeFactsToFence — v0.46 (#3014) supersession-warning seam', () =>
result = await writeFactsToFence(
engine,
{ sourceId: 'default', localPath: brainDir, slug: 'people/alice', resolutionSource: 'exact_page' },
- [baseInput({ fact: 'Points at a row that is not there', context: 'superseded by #99' })],
+ [baseInput({ fact: '~~Points at a row that is not there~~', context: 'superseded by #99' })],
);
} finally {
// eslint-disable-next-line no-console