Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(fences): encode fence-marker text inside a cell so a quoted marker is never live (#5395)

garrytan1371e04270f1
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index dab22b8667..4819201a95 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -102,7 +102,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`; 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. `restoreHiddenFactRows(incoming, existing)` is the row-level, visibility-aware merge `import-file.ts` applies per fence-bearing column (compiled_truth AND timeline) when a remote caller writes back a page it read with hidden rows stripped — without it, a remote get→edit→put round-trip would silently drop every non-`world` fact row. Rules: only non-`world` rows of the existing fence are restoration candidates (a caller's deletion of a VISIBLE row stays honored — world rows are never restored); a hidden row whose rowNum is absent from the incoming fence is restored at its stable rowNum (cross-page `#F<N>` refs survive); a rowNum collision (a caller-authored addition landing on a hidden number the caller never saw) keeps the hidden row's number and renumbers the CALLER's row onto fresh appended numbers (upsertFactRow's append-only contract); same rowNum + same claim keeps the incoming version (idempotent full-content write-throughs); either side parsing with warnings returns null — re-rendering a fence that didn't fully parse would drop the caller's unparsed rows — and `factsGapWarning` surfaces exactly that residual loss. Pure and side-effect-free. Pinned by `test/facts-fence.test.ts` + the remote write-back describes in `test/privacy-strip-and-forget.test.ts` (row-level merge, world-only deletion honored, timeline-embedded fence round-trip).
- `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`. `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. 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`.
+- `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`. `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 `#5395` block of `test/fence-marker-code-context.test.ts` and the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.
- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. In `inferLinkType` a per-edge verb counts only when it belongs to the link being typed (`attachedVerb`: a match with another link between it and this one, or written immediately before another link, is that link's), then precedence founded > invested_in > advises > works_at decides; `joined [X] as <role>` reads as works_at. `attendanceEvidenceRanges` accepts an `Attendees:`/`Participants:` line (plain or bold) and a `## Attendees`/`## Participants` link-list section (`Participants` since gbrain-evals N12-6, with a `LINK_EXTRACTOR_VERSION_TS` bump so meeting pages re-extract). Markdown links, bare-slug prose refs, and slash-shaped wikilinks match ANY dir-shaped path (`ANY_DIR_SEGMENT`), not a directory whitelist — nonexistent targets are dropped by the persist paths' page-existence checks (`resolveCandidateSources`, put_page's allSlugs filter, `addLinksBatch` INNER JOINs) and counted as `skippedMissingTarget` in the extract summaries; the `DIR_PATTERN` whitelist is only the typed fast-path for pass-2b wikilinks (non-whitelisted `[[dir/...]]` get an equivalent direct typed candidate in pass 2c, plus the flag-gated suffix rescue for non-exact matches). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEntityRefs`); `EntityRef.needsResolution: true` tags refs from this pass (the ref's `slug` is the wikilink TARGET, `name` the optional display alias). `SlugResolver` gains optional `resolveBasenameMatches(name): Promise<string[]>` (multi-match by design — emits one edge per matching page). The single shared basename matcher is `buildBasenameIndex(slugs)` + `queryBasenameIndex(index, name)` + `normalizeBasename` (keys raw/lower/slugified tail, stable-sorted shorter-first then lexical), used by `makeResolver`, the FS `resolveBasenameMatchesFromSlugs`, AND the doctor check so they cannot drift. `makeResolver` step 1 falls back to `resolveSlugWithAlias` (rename aliases) for a slug-shaped value with no live page; its fuzzy title step and live keyword step (source-scoped) accept a person/company/fund/organization candidate only under `sameEntityName`, so a near-name stays unresolved instead of linking to a different entity (`test/entity-resolution-near-names.test.ts`). With `link_resolution.global_basename` on, `extractFrontmatterLinks` passes `resolve(name, dirHint, { globalBasename, selfSlug })`, and a unique basename match (self excluded) resolves right after the exact steps and before the fuzzy and live keyword steps, the exact-name-first precedence of `resolveEntitySlug` (#5749, `test/link-resolution-basename-before-search.test.ts`). `makeResolver(engine, {mode, sourceId})` builds the index lazily via `engine.getAllSlugs({sourceId})` — source-scoped so a bare `[[name]]` never resolves to a same-tail page in a different source. `extractPageLinks` gains `opts.globalBasename` (routes `needsResolution` refs through `resolveBasenameMatches` keyed on `ref.slug`, emits candidates tagged `linkType: 'wikilink_basename'` + `linkSource: 'wikilink-resolved'`, skips self-loops) and `opts.skipFrontmatter`. All three surfaces (FS extract, DB extract, `put_page` auto-link) tag provenance with `link_source='wikilink-resolved'`; `put_page` includes it in its reconcilable-edge set so stale basename edges are removed when the wikilink or the flag goes away. Exports `WIKILINK_BASENAME_LINK_TYPE` + `isGlobalBasenameEnabled(engine)` (resolution order: env `GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME` → DB config `link_resolution.global_basename` → default false). `gbrain doctor`'s `link_resolution_opportunity` check surfaces a paste-ready enable hint when ≥5 bare wikilinks would resolve AND ≥20% match. Migration v113 widens `links_link_source_check` to admit `'wikilink-resolved'`; v114 then opens it to any kebab-case provenance (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, ≤64 chars) so external derivers register their own tag (e.g. `citation-graph`) without a migration. `LINK_EXTRACTOR_VERSION_TS` also lives here (bump like `CHUNKER_VERSION` to invalidate prior extract-stale stamps). Pinned by `test/link-extraction.test.ts`, `test/extract-fs.test.ts`, `test/doctor.test.ts`, `test/e2e/global-basename-pglite.test.ts`. #6191: `inferLinkType` applies `link-target-roles.ts` `targetTakesVerb` to every per-edge and fallback verb: `works_at` never types a link to a person, meeting, calendar-event, media, image or transcript target (unknown type: a `people/`, `meetings/`, `calendar/`, `cal/` slug), `founded`/`invested_in` never a temporal or media one; a refused verb keeps scanning lower-precedence rules, then `mentions` (`test/link-type-target-guard.test.ts`).
diff --git a/src/core/fence-repair/raw-rows.ts b/src/core/fence-repair/raw-rows.ts
index b48651bb8d..cd623a4400 100644
--- a/src/core/fence-repair/raw-rows.ts
+++ b/src/core/fence-repair/raw-rows.ts
@@ -17,7 +17,7 @@
import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';
import { indexOfOutsideCode, scanMarkdownCode, type MarkdownCodeMap } from '../fence-scan.ts';
-import { isSeparatorRow } from '../fence-shared.ts';
+import { decodeFenceCell, isSeparatorRow } from '../fence-shared.ts';
import { BASE_WIDTH, canonicalColumn, cellValid, COLUMNS, MIN_CELLS, NAMED_COLUMNS, parseRowNum, TOLERATED_TRAILING } from './schema.ts';
import type { FenceIssue, FenceKind, FenceReason, FenceSection } from './types.ts';
@@ -257,7 +257,7 @@ function cellAt(text: string, from: number, to: number): RawCell {
const raw = slice.trim();
const lead = slice.length - slice.trimStart().length;
const start = raw ? from + lead : from + Math.min(1, slice.length);
- return { raw, start, end: start + raw.length, text: raw.replace(/\\\|/g, '|').replace(/<br\s*\/?>/gi, '\n') };
+ return { raw, start, end: start + raw.length, text: decodeFenceCell(raw.replace(/\\\|/g, '|')) };
}
function strictHeaderCells(row: RawRow): boolean {
diff --git a/src/core/fence-shared.ts b/src/core/fence-shared.ts
index 95591960aa..2eb7ffd152 100644
--- a/src/core/fence-shared.ts
+++ b/src/core/fence-shared.ts
@@ -51,7 +51,46 @@ export function parseRowCells(line: string): string[] | null {
}
}
cells.push(cell.trim());
- return cells.map(cell => cell.replace(/<br\s*\/?>/gi, '\n'));
+ return cells.map(decodeFenceCell);
+}
+
+/**
+ * The cell-content decoder `parseRowCells` applies after cell boundaries are
+ * found: `<br>` (also `<br/>`, `<br />`, case insensitive) → `\n`, then one
+ * level of the fence-marker encoding below is removed. Exported so a parser
+ * that tracks offsets itself (`fence-repair/raw-rows.ts`) reads cells
+ * byte-identically to `parseRowCells`.
+ */
+export function decodeFenceCell(cell: string): string {
+ return cell.replace(/<br\s*\/?>/gi, '\n').replace(ENCODED_MARKER_RE, (_m, amps: string, kind: string, edge: string) =>
+ amps === '' ? `gbrain:${kind}:${edge}` : `gbrain&${amps.slice('amp;'.length)}#58;${kind}:${edge}`);
+}
+
+/**
+ * Fence-marker text inside a cell (#5395). A claim that quotes
+ * `gbrain:facts:begin` outside code would otherwise be written as a live
+ * marker inside the table: the fence scanner pairs with it, the row and
+ * every row after it vanish with no warning, and the remote boundary cuts
+ * the body at the section. The encoding lengthens the ampersand run in
+ * front of `#58;` (`&#58;` is the HTML entity for `:`; GFM renders it as a
+ * colon, and no marker regex matches it):
+ *
+ * gbrain:facts:begin → gbrain&#58;facts:begin
+ * gbrain&#58;facts:begin → gbrain&amp;#58;facts:begin
+ * gbrain&amp;#58;facts:begin → gbrain&amp;amp;#58;facts:begin
+ *
+ * Decoding removes exactly one level, so the codec is injective: a claim
+ * that literally held `gbrain&#58;facts:begin` reads back as that literal,
+ * never as a live marker. A `&#58;` not followed by `(facts|takes):(begin|end)`
+ * is left alone in both directions, and the transcript renderer's
+ * `gbrain\:facts:begin` form contains no bare marker and passes through.
+ */
+const BARE_OR_ENCODED_MARKER_RE = /gbrain(:|&(?:amp;)*#58;)(facts|takes):(begin|end)/g;
+const ENCODED_MARKER_RE = /gbrain&((?:amp;)*)#58;(facts|takes):(begin|end)/g;
+
+function encodeFenceMarkers(s: string): string {
+ return s.replace(BARE_OR_ENCODED_MARKER_RE, (_m, mid: string, kind: string, edge: string) =>
+ mid === ':' ? `gbrain&#58;${kind}:${edge}` : `gbrain&amp;${mid.slice(1)}${kind}:${edge}`);
}
/**
@@ -93,10 +132,11 @@ export function parseStringCell(raw: string): string | undefined {
/**
* Escape a value for safe placement inside a pipe-separated cell. Replaces
* literal `|` with `\|` and line breaks (`\r\n`, `\r`, `\n`) with `<br>` so
- * each row stays on one physical line. `parseRowCells` decodes these after
- * identifying cell boundaries. A literal `<br>` collides with this encoding
- * and reads back as a newline.
+ * each row stays on one physical line, and encodes fence-marker text (see
+ * `encodeFenceMarkers`) so a quoted marker never becomes a live one.
+ * `parseRowCells` decodes these after identifying cell boundaries. A
+ * literal `<br>` collides with this encoding and reads back as a newline.
*/
export function escapeFenceCell(s: string): string {
- return s.replace(/\|/g, '\\|').replace(/\r\n?|\n/g, '<br>');
+ return encodeFenceMarkers(s.replace(/\|/g, '\\|').replace(/\r\n?|\n/g, '<br>'));
}
diff --git a/test/fence-marker-code-context.test.ts b/test/fence-marker-code-context.test.ts
index f647b43cd8..f725483ebe 100644
--- a/test/fence-marker-code-context.test.ts
+++ b/test/fence-marker-code-context.test.ts
@@ -1,11 +1,12 @@
import { describe, expect, test } from 'bun:test';
import { codeEndAt, indexOfOutsideCode, scanMarkdownCode, unclosedCodeFenceStart } from '../src/core/fence-scan.ts';
import {
- TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence, stripTakesFence, upsertTakeRow,
+ TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence, renderTakesFence, stripTakesFence, upsertTakeRow,
} from '../src/core/takes-fence.ts';
import {
- FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, stripFactsFence,
+ FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, stripFactsFence, upsertFactRow,
} from '../src/core/facts-fence.ts';
+import { escapeFenceCell, parseRowCells } from '../src/core/fence-shared.ts';
import { sanitizeRemoteBody } from '../src/core/remote-body.ts';
import { preserveProtectedTakes } from '../src/core/persistence/protected-takes.ts';
import { compileCanonicalProjections } from '../src/core/persistence/canonical-projections.ts';
@@ -459,3 +460,115 @@ describe('adversarial fence matrix (remote privacy)', () => {
}
});
});
+
+describe('fence markers inside a cell are encoded, never live (#5395)', () => {
+ const rawBegin = '<!--- gbrain:facts:begin -->';
+ const rawEnd = '<!--- gbrain:facts:end -->';
+ const fact = (claim: string, extra: Partial<Parameters<typeof upsertFactRow>[1]> = {}) =>
+ ({ claim, kind: 'fact' as const, confidence: 1, visibility: 'world' as const, notability: 'high' as const, ...extra });
+
+ test('upsertFactRow with a raw marker in row 2 keeps every row and the remote body intact', () => {
+ const claim2 = `the row said ${rawBegin} then ${rawEnd} in plain text`;
+ let body = upsertFactRow('# Page\n\nIntro.\n', fact('row one')).body;
+ body = upsertFactRow(body, fact(claim2)).body;
+ body = upsertFactRow(body, fact('row three', { visibility: 'private' })).body;
+ const parsed = parseFactsFence(body);
+ expect(parsed.warnings).toEqual([]);
+ expect(parsed.facts.map(f => f.claim)).toEqual(['row one', claim2, 'row three']);
+ // Exactly one live begin and one live end marker on the page.
+ expect(body.split(FACTS_FENCE_BEGIN).length - 1).toBe(1);
+ expect(body.split(FACTS_FENCE_END).length - 1).toBe(1);
+ // The remote boundary still pairs the real markers: the private row is
+ // hidden, the world rows and the prose after the fence survive.
+ const remote = sanitizeRemoteBody(`${body}\n\nTail prose.\n`);
+ expect(remote).toContain('Intro.');
+ expect(remote).toContain('Tail prose.');
+ expect(remote).toContain('row one');
+ expect(remote).not.toContain('row three');
+ });
+
+ test('every cell position of the facts fence round-trips a raw marker', () => {
+ const m = 'gbrain:facts:end';
+ const row = fact(`claim ${m}`, { validFrom: `from ${m}`, validUntil: `until ${m}`, source: `src ${m}`, context: `ctx ${m}`, claimMetric: `metric ${m}`, claimValue: 1, claimUnit: `unit ${m}`, claimPeriod: `period ${m}` });
+ const body = upsertFactRow('', row).body;
+ const [f] = parseFactsFence(body).facts;
+ expect(f!.claim).toBe(`claim ${m}`);
+ expect(f!.validFrom).toBe(`from ${m}`);
+ expect(f!.validUntil).toBe(`until ${m}`);
+ expect(f!.source).toBe(`src ${m}`);
+ expect(f!.context).toBe(`ctx ${m}`);
+ expect(f!.claimMetric).toBe(`metric ${m}`);
+ expect(f!.claimUnit).toBe(`unit ${m}`);
+ expect(f!.claimPeriod).toBe(`period ${m}`);
+ // The only bare occurrence left on the page is the live end marker.
+ expect(body.split(m).length - 1).toBe(1);
+ });
+
+ test('the takes fence round-trips raw markers in the claim, source and evidence cells', () => {
+ const m = `${TAKES_FENCE_BEGIN} and ${TAKES_FENCE_END}`;
+ const upserted = upsertTakeRow('', { ...take(`take says ${m}`), source: `src ${m}` }).body;
+ expect(parseTakesFence(upserted).takes.map(t => [t.claim, t.source])).toEqual([[`take says ${m}`, `src ${m}`]]);
+ const body = renderTakesFence([{ ...take(`take says ${m}`), rowNum: 1, source: `src ${m}`, resolvedAt: '2026-01-01', resolvedQuality: 'correct' as const, resolvedOutcome: true, resolvedEvidence: `ev ${m}`, resolvedBy: `by ${m}` }]);
+ const parsed = parseTakesFence(body);
+ expect(parsed.warnings).toEqual([]);
+ expect(parsed.takes).toHaveLength(1);
+ expect(parsed.takes[0]!.claim).toBe(`take says ${m}`);
+ expect(parsed.takes[0]!.source).toBe(`src ${m}`);
+ expect(parsed.takes[0]!.resolvedEvidence).toBe(`ev ${m}`);
+ expect(parsed.takes[0]!.resolvedBy).toBe(`by ${m}`);
+ expect(body.split(TAKES_FENCE_BEGIN).length - 1).toBe(1);
+ expect(body.split(TAKES_FENCE_END).length - 1).toBe(1);
+ });
+
+ test('the codec is injective: a literal entity form and a nested form both survive', () => {
+ const literals = ['gbrain&#58;facts:begin', 'gbrain&amp;#58;takes:end', 'gbrain&amp;amp;#58;facts:end', 'gbrain:takes:begin'];
+ for (const literal of literals) {
+ const claim = `literal ${literal} here`;
+ const body = upsertFactRow('', fact(claim)).body;
+ expect(parseFactsFence(body).facts[0]!.claim).toBe(claim);
+ expect(body).not.toContain('gbrain:takes:begin');
+ }
+ // All four distinct inputs render as four distinct cells.
+ const rendered = literals.map(l => renderFactsTable([{ ...fact(l), rowNum: 1, active: true }]));
+ expect(new Set(rendered).size).toBe(literals.length);
+ // A `&#58;` not followed by the marker suffix is untouched.
+ const plain = 'colon &#58; entity and gbrain&#58;other:begin stay';
+ expect(parseFactsFence(upsertFactRow('', fact(plain)).body).facts[0]!.claim).toBe(plain);
+ expect(upsertFactRow('', fact(plain)).body).toContain(plain);
+ });
+
+ test('encode and decode are inverse over random ampersand runs', () => {
+ const kinds = ['facts', 'takes'];
+ const edges = ['begin', 'end'];
+ let seed = 5395;
+ const rnd = (n: number) => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed % n; };
+ for (let i = 0; i < 200; i++) {
+ const parts: string[] = [];
+ const n = 1 + rnd(4);
+ for (let j = 0; j < n; j++) {
+ const level = rnd(4);
+ const mid = level === 0 ? ':' : `&${'amp;'.repeat(level - 1)}#58;`;
+ parts.push(`x${rnd(10)} gbrain${mid}${kinds[rnd(2)]}:${edges[rnd(2)]}`);
+ }
+ const text = parts.join(rnd(2) ? ' ' : '');
+ const encoded = escapeFenceCell(text);
+ expect(encoded).not.toMatch(/gbrain:(facts|takes):(begin|end)/);
+ expect(parseRowCells(`| ${encoded} |`)).toEqual([text]);
+ // decode∘encode = id on the encoded image: a second parse of the already-decoded text is a no-op only when it holds no bare form,
+ // and encode∘decode = id on any encoded cell.
+ expect(escapeFenceCell(parseRowCells(`| ${encoded} |`)![0]!)).toBe(encoded);
+ }
+ });
+
+ test('repeated upsert is byte-idempotent and the transcript-escaped form still parses', () => {
+ const claim = `quoted ${rawBegin}`;
+ const once = upsertFactRow('', fact(claim)).body;
+ const twice = upsertFactRow(once, fact('another')).body;
+ expect(parseFactsFence(twice).facts.map(f => f.claim)).toEqual([claim, 'another']);
+ const reRendered = replaceOrInsertFactsFence(twice, renderFactsTable(parseFactsFence(twice).facts));
+ expect(reRendered).toBe(twice);
+ const escaped = 'see gbrain\\:facts:begin in a transcript';
+ const body = upsertFactRow('', fact(escaped)).body;
+ expect(parseFactsFence(body).facts[0]!.claim).toBe(escaped);
+ });
+});