Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(fences): ignore takes/facts markers quoted in code on the read side; the privacy boundary only hides more (#5397)

time-attack2d12fd1d0b55
diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.ts
index a7753c596f..bfbb3604c9 100644
--- a/src/core/cycle/phantom-redirect.ts
+++ b/src/core/cycle/phantom-redirect.ts
@@ -51,6 +51,7 @@ import {
FACTS_FENCE_END,
type ParsedFact,
} from '../facts-fence.ts';
+import { locateOutsideCode } from '../fence-scan.ts';
import { parseMarkdown, splitBody, serializeMarkdown } from '../markdown.ts';
import { tryAcquireDbLock, syncLockId, type DbLockHandle } from '../db-lock.ts';
import { isAborted } from '../abort-check.ts';
@@ -143,10 +144,9 @@ export function stripFenceAndFrontmatterAndLeadingH1(body: string): string {
// 1. Strip the entire `## Facts\n\n<fence>...<fence>` block. We grab
// the `## Facts` heading too (with surrounding blank lines) so the
// section header doesn't count as residue.
- const beginIdx = working.indexOf(FACTS_FENCE_BEGIN);
- const endIdx = beginIdx >= 0
- ? working.indexOf(FACTS_FENCE_END, beginIdx + FACTS_FENCE_BEGIN.length)
- : -1;
+ const located = locateOutsideCode(working, FACTS_FENCE_BEGIN, FACTS_FENCE_END);
+ const beginIdx = located.beginIdx;
+ const endIdx = beginIdx >= 0 ? located.endIdx : -1;
if (beginIdx !== -1 && endIdx !== -1) {
// Walk backward from beginIdx to swallow a leading `## Facts\n\n`
// (or `## facts\n\n` — case-insensitive markdown headings).
diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.ts
index 2d4afb4340..0e26f0fb33 100644
--- a/src/core/facts-fence.ts
+++ b/src/core/facts-fence.ts
@@ -47,6 +47,7 @@ import {
parseStringCell,
escapeFenceCell,
} from './fence-shared.ts';
+import { findLineOutsideFencedCode, locateOutsideCode, protectedRegions, unclosedCodeFenceStart } from './fence-scan.ts';
// HTML-comment fence markers — verbatim per spec. Same shape as the takes
// fence markers so anyone who's seen one immediately recognizes the other.
@@ -178,8 +179,7 @@ function parseForgottenFromContext(context: string | undefined): boolean {
* `FACTS_TABLE_MALFORMED` sync-failures entries.
*/
export function parseFactsFence(body: string): FactsFenceParseResult {
- const beginIdx = body.indexOf(FACTS_FENCE_BEGIN);
- const endIdx = body.indexOf(FACTS_FENCE_END, beginIdx + FACTS_FENCE_BEGIN.length);
+ const { beginIdx, endIdx } = locateOutsideCode(body, FACTS_FENCE_BEGIN, FACTS_FENCE_END);
const warnings: string[] = [];
if (beginIdx === -1 && endIdx === -1) return { facts: [], warnings };
@@ -553,19 +553,22 @@ export function upsertFactRow(
* page.timeline, where extract_facts refuses to reconcile it
* (FACTS_FENCE_BELOW_SENTINEL) — a blind EOF append on any page that already
* had a timeline froze the fence permanently. No sentinel → EOF append.
+ * An unclosed code block before that point would swallow the fence (it would
+ * render as code), so the fence goes above the block's opener instead.
*/
export function replaceOrInsertFactsFence(body: string, fenceBlock: string): string {
- const beginIdx = body.indexOf(FACTS_FENCE_BEGIN);
- const endIdx = body.indexOf(FACTS_FENCE_END, beginIdx + FACTS_FENCE_BEGIN.length);
+ const { beginIdx, endIdx } = locateOutsideCode(body, FACTS_FENCE_BEGIN, FACTS_FENCE_END);
if (beginIdx !== -1 && endIdx !== -1) {
return body.slice(0, beginIdx) + fenceBlock + body.slice(endIdx + FACTS_FENCE_END.length);
}
const section = `## Facts\n\n${fenceBlock}\n`;
const sentinelAt = timelineSentinelOffset(body);
- if (sentinelAt !== -1) {
- const head = body.slice(0, sentinelAt);
+ const codeAt = unclosedCodeFenceStart(sentinelAt === -1 ? body : body.slice(0, sentinelAt));
+ const insertAt = codeAt !== -1 ? codeAt : sentinelAt;
+ if (insertAt !== -1) {
+ const head = body.slice(0, insertAt);
const sep = head === '' ? '' : head.endsWith('\n\n') ? '' : head.endsWith('\n') ? '\n' : '\n\n';
- return `${head}${sep}${section}\n${body.slice(sentinelAt)}`;
+ return `${head}${sep}${section}\n${body.slice(insertAt)}`;
}
const sep = body.endsWith('\n') ? '\n' : '\n\n';
return `${body}${sep}${section}`;
@@ -593,28 +596,31 @@ function timelineSentinelOffset(body: string): number {
if (lines[i].trim() === '---') { start = i + 1; break; }
}
}
- let offset = 0;
- for (let i = 0; i < start; i++) offset += lines[i].length + 1;
- for (let i = start; i < lines.length; i++) {
- const trimmed = lines[i].trim();
+ const bodyLines = lines.slice(start);
+ // Same code rule as findTimelineSplitIndex: a sentinel quoted inside a
+ // closed fenced code block is not the page's sentinel.
+ const at = findLineOutsideFencedCode(bodyLines, (i) => {
+ const trimmed = bodyLines[i].trim();
if (
trimmed === '<!-- timeline -->' ||
trimmed === '<!--timeline-->' ||
/^---\s+timeline\s+---$/i.test(trimmed)
) {
- return offset;
+ return true;
}
- if (trimmed === '---' && lines.slice(start, i).join('\n').trim().length > 0) {
- for (let j = i + 1; j < lines.length; j++) {
- const next = lines[j].trim();
+ if (trimmed === '---' && bodyLines.slice(0, i).join('\n').trim().length > 0) {
+ for (let j = i + 1; j < bodyLines.length; j++) {
+ const next = bodyLines[j].trim();
if (next.length === 0) continue;
- if (/^##\s+(timeline|history)\s*$/i.test(next)) return offset;
- break;
+ return /^##\s+(timeline|history)\s*$/i.test(next);
}
}
- offset += lines[i].length + 1;
- }
- return -1;
+ return false;
+ });
+ if (at === -1) return -1;
+ let offset = 0;
+ for (let i = 0; i < start + at; i++) offset += lines[i].length + 1;
+ return offset;
}
export interface StripFactsFenceOpts {
@@ -662,23 +668,27 @@ export function stripFactsFence(body: string, opts: StripFactsFenceOpts = {}): s
// Pages without a compiled body have nothing to strip. Guard so the privacy
// strip is a safe no-op rather than crashing on `undefined.indexOf`.
if (typeof body !== 'string') return body;
- const beginIdx = body.indexOf(FACTS_FENCE_BEGIN);
- if (beginIdx === -1) return body;
- const endIdx = body.indexOf(FACTS_FENCE_END, beginIdx + FACTS_FENCE_BEGIN.length);
- if (endIdx === -1) return body;
-
- // Whole-fence strip mode (chunker case).
- if (!opts.keepVisibility || opts.keepVisibility.length === 0) {
- return body.slice(0, beginIdx) + body.slice(endIdx + FACTS_FENCE_END.length);
+ // Privacy boundary: the same regions sanitizeRemoteBody hides, including a
+ // fence quoted in a code block and an ambiguous tail (see protectedRegions).
+ const { regions, truncatedAt } = protectedRegions(body, FACTS_PAIR);
+ if (regions.length === 0 && truncatedAt === -1) return body;
+ const keep = opts.keepVisibility && opts.keepVisibility.length > 0 ? new Set(opts.keepVisibility) : null;
+ let out = '';
+ let cursor = 0;
+ for (const region of regions) {
+ out += body.slice(cursor, region.start);
+ cursor = region.end;
+ // Whole-fence strip mode (chunker case) drops the block. Selective
+ // row-level mode (get_page case) parses, filters and renders it; the
+ // parser's lenient posture means malformed rows are silently dropped,
+ // which is the safe direction at a privacy boundary — when in doubt,
+ // strip rather than leak.
+ if (keep) {
+ const { facts } = parseFactsFence(body.slice(region.start, region.end));
+ out += renderFactsTable(facts.filter(f => keep.has(f.visibility)));
+ }
}
-
- // Selective row-level strip mode (get_page case). Parse, filter, render.
- // The parser's lenient posture means malformed rows are silently dropped,
- // which is the safe direction at a privacy boundary — when in doubt,
- // strip rather than leak.
- const { facts } = parseFactsFence(body);
- const keep = new Set(opts.keepVisibility);
- const kept = facts.filter(f => keep.has(f.visibility));
- const replacement = renderFactsTable(kept);
- return body.slice(0, beginIdx) + replacement + body.slice(endIdx + FACTS_FENCE_END.length);
+ return out + (truncatedAt === -1 ? body.slice(cursor) : body.slice(cursor, truncatedAt));
}
+
+const FACTS_PAIR = [{ begin: FACTS_FENCE_BEGIN, end: FACTS_FENCE_END }];
diff --git a/src/core/fence-scan.ts b/src/core/fence-scan.ts
index f44a46c465..08729f14d1 100644
--- a/src/core/fence-scan.ts
+++ b/src/core/fence-scan.ts
@@ -92,3 +92,396 @@ export function scanFencedBlocks(
}
return { fences, capped: false };
}
+
+/**
+ * Where markdown code sits in a body, for deciding whether facts/takes fence
+ * marker text is live: closed fenced code blocks (same opener/closer grammar as
+ * scanFencedBlocks above) and inline code spans that open and close on the
+ * same line. A page that documents the marker syntax in a ```markdown example
+ * or a `backtick` mention is quoting the marker, not writing a fence.
+ *
+ * Fenced blocks are found up front in one line walk. Inline spans are only
+ * needed on the few lines that hold a marker, so codeEndAt computes them for
+ * that line on demand (spans never cross lines, so the answer is the same as
+ * computing every line) and keeps the last line's spans for the next query.
+ *
+ * The two kinds of code are not equally reliable. An inline span is decided
+ * within its own line. Whether a fenced block is closed depends on pairing
+ * fence lines across the whole body, so one stray ``` far away shifts every
+ * pairing after it: a stray opener pairs with the NEXT block's opener, and a
+ * real fence between them reads as "inside a closed block". So:
+ * - fenced blocks are trusted only when the pairing shows no sign of a
+ * stray: every opener closes, and no block holds a line that could open a
+ * block as long as its own (correct nesting uses a longer outer fence).
+ * Otherwise `fenced` is empty and every marker outside an inline span
+ * stays live, exactly as before;
+ * - the privacy boundary (protectedRegions) never trusts fenced blocks at
+ * all: a real fence wrapped in a balanced code block must still be hidden;
+ * - inline spans are same-line only (a multi-line span stays live);
+ * - indented code blocks are not recognised (a fence line is never indented
+ * by four spaces in writer output, and the lazy-continuation rules would
+ * make a guess here fail open).
+ * Offsets index the string as given (CRLF / CR line endings are preserved).
+ */
+export interface MarkdownCodeMap {
+ readonly body: string;
+ /** Closed fenced code blocks, sorted and disjoint; empty when fence pairing is untrustworthy. */
+ readonly fenced: Array<[number, number]>;
+ /** Start of the first fenced code block that never closes (runs to EOF), or -1. */
+ readonly unclosedAt: number;
+ readonly hasCR: boolean;
+ /** Inline spans of the line last queried by inlineCodeEndAt. */
+ line: { start: number; end: number; spans: Array<[number, number]> } | null;
+}
+
+export function scanMarkdownCode(markdown: string): MarkdownCodeMap {
+ const fenced: Array<[number, number]> = [];
+ const len = markdown.length;
+ const hasCR = markdown.includes('\r');
+ // Line ends are found with a cursor that only moves forward: a per-line
+ // indexOf that runs to EOF on every line lacking the character is quadratic
+ // on ordinary prose. CR handling is skipped when the body has none.
+ const eol: EolCursor = { s: markdown, cr: hasCR ? -1 : Infinity };
+ let mispaired = false;
+ let start = 0;
+ while (start <= len) {
+ const end = lineEnd(eol, start);
+ const next = lineNext(markdown, end);
+ const open = fenceOpenerAt(markdown, start, end);
+ if (open) {
+ let s = next;
+ let closedAt = -1;
+ while (s <= len) {
+ const e = lineEnd(eol, s);
+ if (closesFence(markdown, s, e, open)) { closedAt = lineNext(markdown, e); break; }
+ // A correctly nested example uses a longer outer fence, so an inner
+ // line that could open a block as long as this one means the opener
+ // is a stray that paired with the wrong line.
+ if (!mispaired && opensFenceAsLong(markdown, s, e, open)) mispaired = true;
+ s = lineNext(markdown, e);
+ }
+ if (closedAt !== -1) {
+ fenced.push([start, Math.min(closedAt, len)]);
+ start = closedAt;
+ continue;
+ }
+ // Unclosed: this is the block every fence writer must stay above. No
+ // block is trusted any more, so there is nothing left to pair.
+ return { body: markdown, fenced: [], unclosedAt: start, hasCR, line: null };
+ }
+ start = next;
+ }
+ return { body: markdown, fenced: mispaired ? [] : fenced, unclosedAt: -1, hasCR, line: null };
+}
+
+/**
+ * End of the markdown code that contains offset `at` (a closed fenced block or
+ * an inline span on at's line), or -1 when `at` is not inside code.
+ */
+export function codeEndAt(map: MarkdownCodeMap, at: number): number {
+ const fencedEnd = insideRange(map.fenced, at);
+ if (fencedEnd !== -1) return fencedEnd;
+ return inlineCodeEndAt(map, at);
+}
+
+/** End of the same-line inline code span that contains `at`, or -1. */
+export function inlineCodeEndAt(map: MarkdownCodeMap, at: number): number {
+ const s = map.body;
+ let line = map.line;
+ if (!line || at < line.start || at > line.end) {
+ // Bounds of at's line, scanning only that line (never toward EOF/BOF).
+ let start = s.lastIndexOf('\n', at - 1) + 1;
+ let end = s.indexOf('\n', at);
+ if (end === -1) end = s.length;
+ if (map.hasCR) {
+ for (let k = start; k < at; k++) if (s[k] === '\r') start = k + 1;
+ for (let k = at; k < end; k++) if (s[k] === '\r') { end = k; break; }
+ }
+ // Search inside the line only: an indexOf over the whole body would run to
+ // the next backtick anywhere (EOF on backtick-free pages) for every query.
+ const text = s.slice(start, end);
+ const spans: Array<[number, number]> = [];
+ if (text.includes('`')) {
+ pushInlineCodeRanges(text, 0, text.length, spans);
+ for (const span of spans) { span[0] += start; span[1] += start; }
+ }
+ line = map.line = { start, end, spans };
+ }
+ return insideRange(line.spans, at);
+}
+
+interface EolCursor { s: string; cr: number }
+
+/** Offset of the line terminator (\n, \r\n or \r) of the line at `start`, or length. */
+function lineEnd(c: EolCursor, start: number): number {
+ const nlAt = c.s.indexOf('\n', start);
+ const nl = nlAt === -1 ? c.s.length : nlAt;
+ if (c.cr === Infinity) return nl;
+ if (c.cr < start) {
+ const at = c.s.indexOf('\r', start);
+ c.cr = at === -1 ? Infinity : at;
+ }
+ return c.cr < nl ? c.cr : nl;
+}
+
+/** Start of the line after the terminator at `end` (length + 1 past the last line). */
+function lineNext(s: string, end: number): number {
+ if (end >= s.length) return s.length + 1;
+ return s[end] === '\r' && s[end + 1] === '\n' ? end + 2 : end + 1;
+}
+
+// Fence lines are judged by comparing characters in place: slicing the line
+// and running a regex costs more than the rest of the scan on code-heavy
+// pages. The grammar is CommonMark's, as in scanFencedBlocks:
+// opener ^ {0,3}(`{3,}|~{3,})(.*)$ a backtick info string holds no backtick
+// closer ^ {0,3}(`{3,}|~{3,})[ \t]*$ same char, at least as long as the opener
+// `(.*)$` rejects the line terminators `.` does not match (CR, U+2028, U+2029).
+
+/** Offset of the fence char run after up to three spaces of indent, or -1. */
+function fenceRunStart(s: string, start: number, end: number): number {
+ let p = start;
+ while (p < end && p - start < 3 && s[p] === ' ') p++;
+ return p < end && (s[p] === '`' || s[p] === '~') ? p : -1;
+}
+
+/** The opener run (e.g. "```") when the line opens a fenced code block. */
+function fenceOpenerAt(s: string, start: number, end: number): string | null {
+ const p = fenceRunStart(s, start, end);
+ if (p === -1) return null;
+ const c = s[p]!;
+ let q = p;
+ while (q < end && s[q] === c) q++;
+ if (q - p < 3) return null;
+ for (let k = q; k < end; k++) {
+ const ch = s[k];
+ if ((c === '`' && ch === '`') || ch === '\r' || ch === '\u2028' || ch === '\u2029') return null;
+ }
+ return s.slice(p, q);
+}
+
+function opensFenceAsLong(s: string, start: number, end: number, opener: string): boolean {
+ const inner = fenceOpenerAt(s, start, end);
+ return !!inner && inner[0] === opener[0] && inner.length >= opener.length;
+}
+
+function closesFence(s: string, start: number, end: number, opener: string): boolean {
+ const p = fenceRunStart(s, start, end);
+ if (p === -1 || s[p] !== opener[0]) return false;
+ let q = p;
+ while (q < end && s[q] === opener[0]) q++;
+ if (q - p < opener.length) return false;
+ for (let k = q; k < end; k++) if (s[k] !== ' ' && s[k] !== '\t') return false;
+ return true;
+}
+
+function pushInlineCodeRanges(s: string, start: number, end: number, out: Array<[number, number]>): void {
+ let k = start;
+ while (k < end) {
+ k = s.indexOf('`', k);
+ if (k === -1 || k >= end) return;
+ let run = k;
+ while (run < end && s[run] === '`') run++;
+ const len = run - k;
+ let escaped = 0;
+ for (let b = k - 1; b >= start && s[b] === '\\'; b--) escaped++;
+ if (escaped % 2 === 1) { k = run; continue; }
+ let close = -1;
+ for (let c = run; c < end;) {
+ c = s.indexOf('`', c);
+ if (c === -1 || c >= end) break;
+ let r = c;
+ while (r < end && s[r] === '`') r++;
+ if (r - c === len) { close = c; break; }
+ c = r;
+ }
+ if (close === -1) { k = run; continue; }
+ out.push([k, close + len]);
+ k = close + len;
+ }
+}
+
+function insideRange(ranges: Array<[number, number]>, at: number): number {
+ let lo = 0;
+ let hi = ranges.length - 1;
+ while (lo <= hi) {
+ const mid = (lo + hi) >> 1;
+ const [s, e] = ranges[mid]!;
+ if (at < s) hi = mid - 1;
+ else if (at >= e) lo = mid + 1;
+ else return e;
+ }
+ return -1;
+}
+
+/**
+ * `body.indexOf(needle, fromIndex)`, skipping occurrences that start inside
+ * markdown code (see scanMarkdownCode). The code scan only runs when the
+ * needle is present at all, so marker-free pages pay one indexOf. Callers that
+ * search one body repeatedly pass `code` (scanned once) to avoid rescans.
+ */
+export function indexOfOutsideCode(
+ body: string,
+ needle: string,
+ fromIndex = 0,
+ code?: MarkdownCodeMap,
+): number {
+ let at = body.indexOf(needle, fromIndex);
+ if (at === -1) return -1;
+ code ??= scanMarkdownCode(body);
+ for (let skip = codeEndAt(code, at); skip !== -1; skip = codeEndAt(code, at)) {
+ at = body.indexOf(needle, skip);
+ if (at === -1) return -1;
+ }
+ return at;
+}
+
+/**
+ * Offset where an unclosed fenced code block opens (it runs to EOF), or -1.
+ * Fence writers insert a new fence above it so the fence is not rendered as
+ * code — the same "place the fence where it is read" rule as the timeline
+ * sentinel (#4756).
+ */
+export function unclosedCodeFenceStart(markdown: string): number {
+ return scanMarkdownCode(markdown).unclosedAt;
+}
+
+/**
+ * Index of the first of `lines` (a body split on '\n') for which `isSentinel`
+ * holds and that does not start inside a closed fenced code block, or -1.
+ * The line-based form of indexOfOutsideCode for whole-line markers (the
+ * timeline sentinel): inline spans cannot hold a whole line, so only fenced
+ * blocks matter, under the same fence grammar and trust rule as
+ * MarkdownCodeMap (a trailing CR is a line ending; a bare CR mid-line is not).
+ *
+ * No joined body is built. Lines are first checked for a candidate alone, as
+ * without code awareness; the fence walk starts only once one exists. When
+ * the pairing turns out untrustworthy the answer is the first candidate
+ * anywhere, so a first candidate outside every block is the answer either
+ * way and ends the walk; only a candidate quoted in a block before it makes
+ * the rest of the body worth reading.
+ */
+export function findLineOutsideFencedCode(
+ lines: readonly string[],
+ isSentinel: (i: number) => boolean,
+): number {
+ let first = 0;
+ while (first < lines.length && !isSentinel(first)) first++;
+ if (first === lines.length) return -1;
+ const walk: FenceWalk = { opener: null, mispaired: false };
+ for (let i = 0; i < first; i++) stepFenceWalk(walk, lines[i]!);
+ let firstQuoted = -1;
+ let firstOutside = -1;
+ for (let i = first; i < lines.length; i++) {
+ const candidate = i === first || isSentinel(i);
+ if (candidate && !walk.opener) {
+ if (firstQuoted === -1 || walk.mispaired) return firstQuoted === -1 ? i : firstQuoted;
+ if (firstOutside === -1) firstOutside = i;
+ continue;
+ }
+ if (candidate && firstQuoted === -1) firstQuoted = i;
+ stepFenceWalk(walk, lines[i]!);
+ }
+ // An unclosed block or a mispairing: no block is trusted.
+ return walk.opener || walk.mispaired ? firstQuoted : firstOutside;
+}
+
+interface FenceWalk { opener: string | null; mispaired: boolean }
+
+/** Advance the fence pairing by one line (a trailing CR is its line ending). */
+function stepFenceWalk(walk: FenceWalk, line: string): void {
+ // A fence line starts with indent, ` or ~; every other line is prose to it.
+ const c0 = line.charCodeAt(0);
+ if (c0 !== 32 && c0 !== 96 && c0 !== 126) return;
+ const end = line.charCodeAt(line.length - 1) === 13 ? line.length - 1 : line.length;
+ if (!walk.opener) {
+ walk.opener = fenceOpenerAt(line, 0, end);
+ } else if (closesFence(line, 0, end, walk.opener)) {
+ walk.opener = null;
+ } else if (!walk.mispaired && opensFenceAsLong(line, 0, end, walk.opener)) {
+ walk.mispaired = true;
+ }
+}
+
+/**
+ * Locate a begin/end marker pair outside markdown code with ONE code scan —
+ * the paired form of indexOfOutsideCode that every fence reader and writer
+ * uses. Same offsets as the two-call form: `endIdx` is searched from
+ * `beginIdx + begin.length` even when `beginIdx` is -1.
+ */
+export function locateOutsideCode(
+ body: string,
+ begin: string,
+ end: string,
+): { beginIdx: number; endIdx: number } {
+ if (!body.includes(begin) && !body.includes(end)) return { beginIdx: -1, endIdx: -1 };
+ const code = scanMarkdownCode(body);
+ const beginIdx = indexOfOutsideCode(body, begin, 0, code);
+ return { beginIdx, endIdx: indexOfOutsideCode(body, end, beginIdx + begin.length, code) };
+}
+
+/** A begin/end marker pair that delimits a protected fence. */
+export interface FencePair {
+ readonly begin: string;
+ readonly end: string;
+}
+
+/** A protected fence found by protectedRegions: body.slice(start, end) spans begin..end markers. */
+export interface ProtectedRegion {
+ /** Index into the `pairs` argument. */
+ readonly pair: number;
+ readonly start: number;
+ readonly end: number;
+ /**
+ * True when readers (parse, upsert) also see this fence. False when its begin
+ * sits inside markdown code (an inline span or a closed fenced block): readers
+ * treat it as an example and project nothing from it; only the privacy
+ * boundary hides it.
+ */
+ readonly read: boolean;
+}
+
+/**
+ * The privacy boundary's view of protected fences: what must never leave the
+ * page (remote reads, chunks, synopses) and what a remote write must keep.
+ *
+ * It never hides less than the plain lexical scan: every marker token opens or
+ * closes regions exactly as before, whether or not it sits in markdown code,
+ * because a stray ``` elsewhere can make a real fence look like the inside of
+ * a closed block (see MarkdownCodeMap). The one difference only hides more: a
+ * region whose begin readers see runs past an end marker quoted in code to the
+ * end readers pair with it, so rows between the two never leak. Every other
+ * marker inside such a region still makes the tail ambiguous.
+ *
+ * `truncatedAt` is where an ambiguous tail starts (an unpaired begin, a second
+ * begin, the wrong end): everything from there to EOF is protected. -1 when
+ * every begin paired.
+ */
+export function protectedRegions(
+ body: string,
+ pairs: readonly FencePair[],
+): { regions: ProtectedRegion[]; truncatedAt: number } {
+ const regions: ProtectedRegion[] = [];
+ const markers = pairs.flatMap(p => [p.begin, p.end]);
+ const pattern = new RegExp(markers.map(m => m.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'), 'g');
+ // The code scan runs only once a marker exists at all.
+ let code: MarkdownCodeMap | undefined;
+ let open: { pair: number; start: number; read: boolean } | null = null;
+ // Each token is visited once, in body order.
+ for (const token of body.matchAll(pattern)) {
+ const at = token.index;
+ code ??= scanMarkdownCode(body);
+ const read = codeEndAt(code, at) === -1;
+ if (!open) {
+ const pair = pairs.findIndex(p => p.begin === token[0]);
+ if (pair !== -1) open = { pair, start: at, read };
+ continue;
+ }
+ const isEnd = token[0] === pairs[open.pair]!.end;
+ // A reader-visible fence runs to its reader-visible end.
+ if (open.read && !read && isEnd) continue;
+ if (!isEnd) return { regions, truncatedAt: open.start };
+ regions.push({ pair: open.pair, start: open.start, end: at + token[0].length, read: open.read });
+ open = null;
+ }
+ return { regions, truncatedAt: open ? open.start : -1 };
+}
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index 5541a7e67a..46ba39be3b 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -6,6 +6,7 @@ import {
commentValueKeys, frontmatterKeyHazard, recoverFrontmatter, unclosedFenceProtectedKey, yamlLocationMessage,
RECOVERY_VERSION, type FrontmatterRecovery, type RecoveryKind,
} from './frontmatter-recovery.ts';
+import { findLineOutsideFencedCode } from './fence-scan.ts';
export {
recoverFrontmatter, RECOVERY_VERSION, PROTECTED_FRONTMATTER_KEYS, IDENTITY_FRONTMATTER_KEYS,
@@ -826,30 +827,34 @@ export function splitBody(body: string): { compiled_truth: string; timeline: str
* shape) so the frontmatter's `---` delimiters can't false-positive rule 3.
*/
export function findTimelineSplitIndex(lines: string[]): number {
- for (let i = 0; i < lines.length; i++) {
- const trimmed = lines[i].trim();
+ // A sentinel quoted inside a fenced code block (a markdown example) is not
+ // a separator. Mispaired fences (see MarkdownCodeMap) leave every candidate
+ // live, as before.
+ return findLineOutsideFencedCode(lines, (i) => isTimelineSentinelLine(lines, i));
+}
- if (trimmed === '<!-- timeline -->' || trimmed === '<!--timeline-->') {
- return i;
- }
+function isTimelineSentinelLine(lines: string[], i: number): boolean {
+ const trimmed = lines[i].trim();
- if (trimmed === '--- timeline ---' || /^---\s+timeline\s+---$/i.test(trimmed)) {
- return i;
- }
+ if (trimmed === '<!-- timeline -->' || trimmed === '<!--timeline-->') {
+ return true;
+ }
+
+ if (trimmed === '--- timeline ---' || /^---\s+timeline\s+---$/i.test(trimmed)) {
+ return true;
+ }
- if (trimmed === '---') {
- const beforeContent = lines.slice(0, i).join('\n').trim();
- if (beforeContent.length === 0) continue;
+ if (trimmed === '---') {
+ const beforeContent = lines.slice(0, i).join('\n').trim();
+ if (beforeContent.length === 0) return false;
- for (let j = i + 1; j < lines.length; j++) {
- const next = lines[j].trim();
- if (next.length === 0) continue;
- if (/^##\s+(timeline|history)\s*$/i.test(next)) return i;
- break;
- }
+ for (let j = i + 1; j < lines.length; j++) {
+ const next = lines[j].trim();
+ if (next.length === 0) continue;
+ return /^##\s+(timeline|history)\s*$/i.test(next);
}
}
- return -1;
+ return false;
}
/** A timeline entry line: a bullet whose text starts with a 4-digit year
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 6aacc20865..9e624382e0 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -13,6 +13,40 @@ import { sanitizeForJsonb } from '../batch-rows.ts';
import { materializedMarker, materializedMarkerHash, timelineKey, timelineKeyHash } from '../timeline-marker.ts';
import { opError, OperationError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
+import { codeEndAt, indexOfOutsideCode, protectedRegions, scanMarkdownCode, type MarkdownCodeMap } from '../fence-scan.ts';
+
+const FENCE_MARKERS=[FACTS_FENCE_BEGIN,FACTS_FENCE_END,TAKES_FENCE_BEGIN,TAKES_FENCE_END];
+const FENCE_PAIRS=[{begin:FACTS_FENCE_BEGIN,end:FACTS_FENCE_END},{begin:TAKES_FENCE_BEGIN,end:TAKES_FENCE_END}];
+
+/** True when `marker` occurs more than once outside markdown code (`code` = that body's scan). */
+function repeatsOutsideCode(body:string,marker:string,code:MarkdownCodeMap):boolean {
+ const first=indexOfOutsideCode(body,marker,0,code);
+ return first!==-1 && indexOfOutsideCode(body,marker,first+marker.length,code)!==-1;
+}
+
+/** True when some occurrence of a fence marker sits in markdown code (`code` = that body's scan). */
+function quotesMarker(body:string,code:MarkdownCodeMap):boolean {
+ for(const marker of FENCE_MARKERS) {
+ for(let at=body.indexOf(marker);at!==-1;at=body.indexOf(marker,at+marker.length)) if(codeEndAt(code,at)!==-1) return true;
+ }
+ return false;
+}
+
+/**
+ * Rows held by fences whose begin sits in markdown code. Readers treat such a
+ * fence as an example and project nothing from it, so a real fence wrapped in
+ * code would silently delete the rows it holds. Keys are `row_num:text`.
+ */
+function quotedFenceRows(fields:string[]):{facts:Set<string>,takes:Set<string>} {
+ const facts=new Set<string>(),takes=new Set<string>();
+ for(const field of fields) for(const region of protectedRegions(field,FENCE_PAIRS).regions) {
+ if(region.read) continue;
+ const text=field.slice(region.start,region.end);
+ if(region.pair===0) for(const f of parseFactsFence(text).facts) facts.add(`${f.rowNum}:${f.claim}`);
+ else for(const t of parseTakesFence(text).takes) takes.add(`${t.rowNum}:${t.claim}`);
+ }
+ return {facts,takes};
+}
type CanonicalBody = Pick<ParsedPage, 'compiled_truth' | 'timeline'>;
@@ -226,8 +260,13 @@ function fenceError(message: string, slug: string, sourceId: string, what: strin
export function compileCanonicalProjections(page: ParsedPage, slug: string, sourceId: string) {
const fields=[page.compiled_truth,page.timeline ?? ''];
- for(const field of fields) for(const marker of [FACTS_FENCE_BEGIN,FACTS_FENCE_END,TAKES_FENCE_BEGIN,TAKES_FENCE_END]) {
- if(field.split(marker).length>2) throw fenceError('Each canonical body section must contain at most one facts fence and one takes fence.', slug, sourceId, 'A body section repeats a facts or takes fence marker');
+ let quoting=false;
+ for(const field of fields) {
+ // One code scan per field serves all four marker checks; an example quoted in code is not a second fence.
+ if(!FENCE_MARKERS.some(marker=>field.includes(marker))) continue;
+ const code=scanMarkdownCode(field);
+ if(FENCE_MARKERS.some(marker=>repeatsOutsideCode(field,marker,code))) throw fenceError('Each canonical body section must contain at most one facts fence and one takes fence.', slug, sourceId, 'A body section repeats a facts or takes fence marker');
+ quoting ||= quotesMarker(field,code);
}
const factSets=fields.map(parseFactsFence),takeSets=fields.map(parseTakesFence);
if ([...factSets,...takeSets].some(set=>set.warnings.length)) throw fenceError('A canonical facts or takes fence cannot be parsed losslessly.', slug, sourceId, 'A facts or takes table does not parse cleanly');
@@ -235,7 +274,28 @@ export function compileCanonicalProjections(page: ParsedPage, slug: string, sour
for(const rows of [facts,takes]) if(new Set(rows.map(row=>row.rowNum)).size!==rows.length) {
throw fenceError('Canonical row numbers must be unique across the entire page.', slug, sourceId, 'Two facts or takes rows share a row number');
}
- return { factRows: extractFactsFromFenceText(facts,slug,sourceId), takes };
+ return { factRows: extractFactsFromFenceText(facts,slug,sourceId), takes, quoted: quoting ? quotedFenceRows(fields) : null };
+}
+
+/**
+ * Refuse, rather than silently delete, rows a fence quoted in markdown code
+ * still holds: readers project nothing from such a fence, so a real fence
+ * wrapped in a code block would otherwise expire its facts and drop its takes.
+ */
+async function refuseQuotedFenceLoss(tx: BrainEngine, pageId: number, quoted: { facts: Set<string>; takes: Set<string> },
+ takeRowsGone: number[], factRows: ReturnType<typeof extractFactsFromFenceText>, slug: string, sourceId: string): Promise<void> {
+ const refuse = () => fenceError('A takes or facts fence sits inside markdown code, so this write would remove the rows it holds.', slug, sourceId,
+ 'Move the fence out of the code block (or inline code span), or delete the fence to remove its rows; a fence quoted in code holds rows');
+ if (quoted.takes.size && takeRowsGone.length) {
+ const gone = await tx.executeRaw<{ row_num: number; claim: string }>('SELECT row_num,claim FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])', [pageId, takeRowsGone]);
+ if (gone.some(r => quoted.takes.has(`${r.row_num}:${r.claim}`))) throw refuse();
+ }
+ if (quoted.facts.size) {
+ const kept = new Set(factRows.map(f => `${f.row_num}:${f.fact}:${f.visibility}`));
+ const live = await tx.executeRaw<{ row_num: number; fact: string; visibility: string }>(`SELECT row_num,fact,visibility FROM facts
+ WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL`, [sourceId, slug]);
+ if (live.some(r => !kept.has(`${r.row_num}:${r.fact}:${r.visibility}`) && quoted.facts.has(`${r.row_num}:${r.fact}`))) throw refuse();
+ }
}
function takeCollision(): OperationError {
@@ -251,7 +311,7 @@ function takeCollision(): OperationError {
*/
export async function prepareCanonicalProjections(engine: BrainEngine, page: ParsedPage, slug: string, sourceId: string,
prior: PageSnapshot | null, writer: ProjectionWriter): Promise<(tx: BrainEngine, pageId?: number) => Promise<void>> {
- const { factRows, takes } = compileCanonicalProjections(page, slug, sourceId);
+ const { factRows, takes, quoted } = compileCanonicalProjections(page, slug, sourceId);
const { timeline, exactIncoming, pinned } = classifyTimeline(prior ? await storedTimeline(engine, prior.page.id) : [],
page, prior?.page ?? null, slug, writer);
const deletions = JSON.stringify(pinned.filter(row => row.action === 'delete')
@@ -272,6 +332,7 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
return async (tx, pageId) => {
const id = pageId ?? (await tx.readPageSnapshot(slug, { sourceId }))?.page.id;
if (id == null) return;
+ if (quoted) await refuseQuotedFenceLoss(tx, id, quoted, takeRowsGone, factRows, slug, sourceId);
// Fact IDs in permanent receipts remain meaningful when a canonical row is
// removed/replaced. Expire and detach its row position instead of deleting it.
// Conversation-extractor rows share the page coordinate without a fence
diff --git a/src/core/persistence/protected-takes.ts b/src/core/persistence/protected-takes.ts
index 8f94fb5426..baca6dd954 100644
--- a/src/core/persistence/protected-takes.ts
+++ b/src/core/persistence/protected-takes.ts
@@ -1,21 +1,30 @@
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';
import { opError } from '../ops/contract.ts';
+import { protectedRegions } from '../fence-scan.ts';
-function fence(body:string):string|null {
- const start=body.indexOf(TAKES_FENCE_BEGIN);
- if(start<0) return null;
- const end=body.indexOf(TAKES_FENCE_END,start+TAKES_FENCE_BEGIN.length);
- if(end<0 || body.indexOf(TAKES_FENCE_BEGIN,start+TAKES_FENCE_BEGIN.length)>=0) {
+const TAKES_PAIR=[{begin:TAKES_FENCE_BEGIN,end:TAKES_FENCE_END}];
+
+/** The takes fence remote reads hide in this body (the region stripTakesFence removes); read=false when readers see it as code. */
+function fence(body:string):{text:string,read:boolean}|null {
+ const {regions,truncatedAt}=protectedRegions(body,TAKES_PAIR);
+ if(regions.length===0 && truncatedAt===-1) return null;
+ if(truncatedAt!==-1 || regions.length>1) {
throw opError('invalid_params','The takes fence must be repaired before replacing this page.',
'The stored page has an unclosed or repeated takes fence, so a full replacement could lose takes. Ask the user to repair the fence (one begin and one end marker) in the page, then replace it again.');
}
- return body.slice(start,end+TAKES_FENCE_END.length);
+ const region=regions[0]!;
+ return {text:body.slice(region.start,region.end),read:region.read};
}
/** Remote full-page reads omit takes; a round trip must preserve their canonical fence. */
export function preserveProtectedTakes(incoming:string,stored:string):string {
const before=fence(stored),after=fence(incoming);
- if(after!==null && after!==before) throw opError('permission_denied','Use the scoped takes operations to mutate a takes fence.',
+ if(after!==null && after.text!==before?.text) throw opError('permission_denied','Use the scoped takes operations to mutate a takes fence.',
'Send the page without its takes fence (it is preserved automatically), and change takes with takes_add, takes_update, takes_supersede, or takes_resolve.');
if(before===null || after!==null) return incoming;
- return `${incoming.trimEnd()}\n\n${before}\n`;
+ // A fence quoted in markdown code was hidden from the remote reader, but
+ // re-appending it at EOF would move it out of the code and make it live.
+ if(!before.read) throw opError('invalid_params','This page quotes a takes fence inside markdown code, so a remote replacement cannot preserve it.',
+ 'Ask the user to replace this page with a local write (gbrain put on the brain host), or send the page with only the prose you mean to change through a scoped edit.',
+ { why: 'Remote reads hide the quoted fence; re-appending it at the end of the page would move it out of the code block and turn the example into a live takes fence.' });
+ return `${incoming.trimEnd()}\n\n${before.text}\n`;
}
diff --git a/src/core/remote-body.ts b/src/core/remote-body.ts
index a2851b67ea..d572dc1227 100644
--- a/src/core/remote-body.ts
+++ b/src/core/remote-body.ts
@@ -2,12 +2,13 @@ import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, renderFactsTable }
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from './takes-fence.ts';
import { sanitizeText } from './batch-rows.ts';
import { stripMaterializedMarkers } from './timeline-marker.ts';
+import { protectedRegions, type FencePair } from './fence-scan.ts';
-const protectedMarkerPattern = new RegExp(
- [FACTS_FENCE_BEGIN, FACTS_FENCE_END, TAKES_FENCE_BEGIN, TAKES_FENCE_END]
- .map(marker => marker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'),
- 'g',
-);
+// Index 0 is the facts pair: its world rows are re-rendered, never dropped.
+const PROTECTED_PAIRS: readonly FencePair[] = [
+ { begin: FACTS_FENCE_BEGIN, end: FACTS_FENCE_END },
+ { begin: TAKES_FENCE_BEGIN, end: TAKES_FENCE_END },
+];
/**
* Strict protected-body boundary shared by remote reads and chunk creation.
@@ -20,33 +21,22 @@ export function sanitizeRemoteBody(body: string, opts: { includeWithdrawn?: bool
// detection could turn an unrecognized marker into a protected stored fence.
body = sanitizeText(body);
if (!opts.keepMaterializedMarkers) body = stripMaterializedMarkers(body);
- let cursor = 0;
+ // Never hides less than the lexical marker scan; see protectedRegions.
+ const { regions, truncatedAt } = protectedRegions(body, PROTECTED_PAIRS);
const output: string[] = [];
- let open: { start: number; endMarker: string; facts: boolean } | undefined;
- // Each token is visited once. Looking for every marker from each block's
- // cursor would repeatedly scan the remaining body when a marker is absent.
- for (const token of body.matchAll(protectedMarkerPattern)) {
- const marker = token[0];
- if (!open) {
- const facts = marker === FACTS_FENCE_BEGIN;
- if (!facts && marker !== TAKES_FENCE_BEGIN) continue;
- output.push(body.slice(cursor, token.index));
- open = { start: token.index, endMarker: facts ? FACTS_FENCE_END : TAKES_FENCE_END, facts };
- continue;
- }
- // Another begin or the wrong end makes the protected tail ambiguous.
- if (marker !== open.endMarker) return output.join('');
- cursor = token.index + marker.length;
- if (open.facts) {
+ let cursor = 0;
+ for (const region of regions) {
+ output.push(body.slice(cursor, region.start));
+ cursor = region.end;
+ if (region.pair === 0) {
try {
- const parsed = parseFactsFence(body.slice(open.start, cursor));
+ const parsed = parseFactsFence(body.slice(region.start, region.end));
if (parsed.warnings.length === 0) output.push(renderFactsTable(parsed.facts.filter(row => row.visibility === 'world' && (opts.includeWithdrawn || !row.forgotten))));
} catch {
// A protected block that cannot be parsed is omitted, never echoed.
}
}
- open = undefined;
}
- if (!open) output.push(body.slice(cursor));
+ output.push(truncatedAt === -1 ? body.slice(cursor) : body.slice(cursor, truncatedAt));
return output.join('');
}
diff --git a/src/core/takes-fence.ts b/src/core/takes-fence.ts
index 804287af7d..8e0b24347c 100644
--- a/src/core/takes-fence.ts
+++ b/src/core/takes-fence.ts
@@ -221,6 +221,7 @@ import {
stripStrikethrough,
escapeFenceCell as safeFenceCell,
} from './fence-shared.ts';
+import { indexOfOutsideCode, locateOutsideCode, protectedRegions, unclosedCodeFenceStart } from './fence-scan.ts';
function parseSinceCell(raw: string): { since?: string; until?: string } {
const trimmed = raw.trim();
@@ -238,8 +239,7 @@ function parseSinceCell(raw: string): { since?: string; until?: string } {
* Returns empty takes + empty warnings when no fence is present.
*/
export function parseTakesFence(body: string): ParseResult {
- const beginIdx = body.indexOf(TAKES_FENCE_BEGIN);
- const endIdx = body.indexOf(TAKES_FENCE_END, beginIdx + TAKES_FENCE_BEGIN.length);
+ const { beginIdx, endIdx } = locateOutsideCode(body, TAKES_FENCE_BEGIN, TAKES_FENCE_END);
const warnings: string[] = [];
if (beginIdx === -1 && endIdx === -1) {
@@ -249,7 +249,7 @@ export function parseTakesFence(body: string): ParseResult {
// `<!-- gbrain:takes:begin -->` an author or agent writes from memory —
// is a fence the author MEANT to write. Flag it instead of silently
// parsing zero takes.
- if (body.includes('gbrain:takes:begin')) {
+ if (indexOfOutsideCode(body, 'gbrain:takes:begin') !== -1) {
warnings.push(
'TAKES_FENCE_NEAR_MISS: found "gbrain:takes:begin" but not the exact ' +
`marker "${TAKES_FENCE_BEGIN}" — use the three-dash comment form`,
@@ -505,15 +505,22 @@ export function upsertTakeRow(
const newFence = renderTakesFence(allRows);
// If fence already exists, replace it. Otherwise append a Takes section.
- const beginIdx = body.indexOf(TAKES_FENCE_BEGIN);
- const endIdx = body.indexOf(TAKES_FENCE_END, beginIdx + TAKES_FENCE_BEGIN.length);
+ const { beginIdx, endIdx } = locateOutsideCode(body, TAKES_FENCE_BEGIN, TAKES_FENCE_END);
let out: string;
if (beginIdx !== -1 && endIdx !== -1) {
out = body.slice(0, beginIdx) + newFence + body.slice(endIdx + TAKES_FENCE_END.length);
} else {
- // No fence yet — append a fresh Takes section at the end.
- const sep = body.endsWith('\n') ? '\n' : '\n\n';
- out = `${body}${sep}## Takes\n\n${newFence}\n`;
+ // No fence yet — append a fresh Takes section at the end, or above an
+ // unclosed code block that runs to EOF (it would render the fence as code).
+ const codeAt = unclosedCodeFenceStart(body);
+ if (codeAt === -1) {
+ const sep = body.endsWith('\n') ? '\n' : '\n\n';
+ out = `${body}${sep}## Takes\n\n${newFence}\n`;
+ } else {
+ const head = body.slice(0, codeAt);
+ const sep = head === '' || head.endsWith('\n\n') ? '' : head.endsWith('\n') ? '\n' : '\n\n';
+ out = `${head}${sep}## Takes\n\n${newFence}\n\n${body.slice(codeAt)}`;
+ }
}
return { body: out, rowNum: nextRowNum };
}
@@ -562,8 +569,7 @@ export function supersedeRow(
void oldClaim; // Reserved for future "show what changed" diff helper.
const newFence = renderTakesFence(updatedTakes);
- const beginIdx = body.indexOf(TAKES_FENCE_BEGIN);
- const endIdx = body.indexOf(TAKES_FENCE_END, beginIdx + TAKES_FENCE_BEGIN.length);
+ const { beginIdx, endIdx } = locateOutsideCode(body, TAKES_FENCE_BEGIN, TAKES_FENCE_END);
if (beginIdx === -1 || endIdx === -1) {
throw new Error('supersedeRow: fence markers missing in body (unexpected — parseTakesFence found rows)');
}
@@ -575,16 +581,25 @@ export function supersedeRow(
* Strip the fenced takes block from the body. Used by the chunker so takes
* content lives ONLY in the takes table, not duplicated in page chunks
* (Codex P0 #3 privacy fix). When no fence is present, returns body
- * unchanged.
+ * unchanged. An unpaired begin marker strips everything after it, like
+ * sanitizeRemoteBody.
*/
export function stripTakesFence(body: string): string {
// Pages without a compiled body (e.g. metadata-only rows from a read op)
// have nothing to strip. Guard so the privacy strip is a safe no-op rather
// than crashing on `undefined.indexOf`.
if (typeof body !== 'string') return body;
- const beginIdx = body.indexOf(TAKES_FENCE_BEGIN);
- if (beginIdx === -1) return body;
- const endIdx = body.indexOf(TAKES_FENCE_END, beginIdx + TAKES_FENCE_BEGIN.length);
- if (endIdx === -1) return body;
- return body.slice(0, beginIdx) + body.slice(endIdx + TAKES_FENCE_END.length);
+ // Privacy boundary: the same regions sanitizeRemoteBody hides, including a
+ // fence quoted in a code block and an ambiguous tail (see protectedRegions).
+ const { regions, truncatedAt } = protectedRegions(body, TAKES_PAIR);
+ if (regions.length === 0 && truncatedAt === -1) return body;
+ let out = '';
+ let cursor = 0;
+ for (const region of regions) {
+ out += body.slice(cursor, region.start);
+ cursor = region.end;
+ }
+ return out + (truncatedAt === -1 ? body.slice(cursor) : body.slice(cursor, truncatedAt));
}
+
+const TAKES_PAIR = [{ begin: TAKES_FENCE_BEGIN, end: TAKES_FENCE_END }];
diff --git a/src/core/takes-write.ts b/src/core/takes-write.ts
index 6d57d7baa7..cc79322bc7 100644
--- a/src/core/takes-write.ts
+++ b/src/core/takes-write.ts
@@ -51,6 +51,7 @@ import {
type ParseResult,
type TakeQuality,
} from './takes-fence.ts';
+import { locateOutsideCode } from './fence-scan.ts';
import { withPageLock } from './page-lock.ts';
import { resolvePageFilePath, resolveSourceLocalFilePath } from './markdown.ts';
import { sanitizeRecordedSourcePath, recordedPathFromFileUri, scannerSlugRootMode } from './write-through.ts';
@@ -394,8 +395,7 @@ function assertFenceRoundTrips(parsed: ParseResult): void {
function replaceFence(body: string, rows: ParsedTake[]): string {
const newFence = renderTakesFence(rows);
- const beginIdx = body.indexOf(TAKES_FENCE_BEGIN);
- const endIdx = body.indexOf(TAKES_FENCE_END, beginIdx + TAKES_FENCE_BEGIN.length);
+ const { beginIdx, endIdx } = locateOutsideCode(body, TAKES_FENCE_BEGIN, TAKES_FENCE_END);
return body.slice(0, beginIdx) + newFence + body.slice(endIdx + TAKES_FENCE_END.length);
}
diff --git a/test/fence-marker-code-context.test.ts b/test/fence-marker-code-context.test.ts
new file mode 100644
index 0000000000..607effa01d
--- /dev/null
+++ b/test/fence-marker-code-context.test.ts
@@ -0,0 +1,461 @@
+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,
+} from '../src/core/takes-fence.ts';
+import {
+ FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, stripFactsFence,
+} from '../src/core/facts-fence.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';
+import { withdrawalFenceBlocks } from '../src/core/facts/withdrawal-overlay.ts';
+import { splitBody } from '../src/core/markdown.ts';
+import type { ParsedPage } from '../src/core/import-file.ts';
+
+const take = (claim: string) => ({ claim, kind: 'take' as const, holder: 'alice-example', weight: 0.5, active: true });
+const realTakes = (claim: string) => upsertTakeRow('', take(claim)).body;
+
+/** A doc page that documents the takes fence syntax inside a code block. */
+const takesExample = [
+ '```markdown',
+ TAKES_FENCE_BEGIN,
+ '| # | claim | kind | who | weight | since | source |',
+ '|---|---|---|---|---|---|---|',
+ '| 1 | EXAMPLE-CLAIM | take | alice-example | 0.5 | 2026-01 | docs |',
+ TAKES_FENCE_END,
+ '```',
+].join('\n');
+
+const factsExample = ['```markdown', FACTS_FENCE_BEGIN, '| 1 | EXAMPLE-FACT |', FACTS_FENCE_END, '```'].join('\n');
+
+const worldAndPrivateFacts = renderFactsTable([
+ { rowNum: 1, claim: 'WORLD-FACT', kind: 'fact', confidence: 1, visibility: 'world', notability: 'high', active: true },
+ { rowNum: 2, claim: 'PRIVATE-FACT', kind: 'fact', confidence: 1, visibility: 'private', notability: 'high', active: true },
+]);
+
+/** Every code span, rebuilt by asking codeEndAt at each offset in order. */
+function codeSlices(body: string): string[] {
+ const map = scanMarkdownCode(body);
+ const out: string[] = [];
+ for (let i = 0; i < body.length;) {
+ const end = codeEndAt(map, i);
+ if (end === -1) { i++; continue; }
+ out.push(body.slice(i, end));
+ i = end;
+ }
+ return out;
+}
+
+const page = (compiled_truth: string): ParsedPage =>
+ ({ type: 'concept', title: 't', compiled_truth, timeline: '', frontmatter: {}, tags: [] }) as ParsedPage;
+
+describe('markdown code map', () => {
+ test('closed fences and same-line inline spans are code', () => {
+ expect(codeSlices('a `x` b\n```\ncode\n```\ntail')).toEqual(['`x`', '```\ncode\n```\n']);
+ });
+
+ test('an unclosed fence anywhere means fence pairing cannot be trusted', () => {
+ // The stray ~~~ proves some fence line is mispaired, so no block is code.
+ expect(codeSlices('a `x` b\n```\ncode\n```\n~~~\nopen to EOF')).toEqual(['`x`']);
+ });
+
+ test('a longer outer fence nests an example; a same-length inner opener is a mispairing', () => {
+ const nested = '````markdown\n```ts\nx\n```\n````\n';
+ expect(codeSlices(`${nested}tail`)).toEqual([nested]);
+ // ``` then ```ts: the inner opener cannot close the block, so the first
+ // ``` must be a stray that paired with the wrong line.
+ expect(codeSlices('```\nstray\n```ts\nx\n```\ntail')).toEqual([]);
+ });
+
+ test('double-backtick spans, escaped backticks and CRLF line endings', () => {
+ const body = 'p ``a ` b`` q \\`not code` r\r\n```\r\nz\r\n```';
+ expect(codeSlices(body)).toEqual(['``a ` b``', '```\r\nz\r\n```']);
+ });
+
+ test('bare CR line endings are line breaks too', () => {
+ const body = 'a `x`\r```\rz\r```\rtail';
+ expect(codeSlices(body)).toEqual(['`x`', '```\rz\r```\r']);
+ });
+
+ test('stays linear on long pages with no backticks or line breaks to find', () => {
+ // A per-line search that runs to EOF on every line lacking a backtick is
+ // quadratic: ~200 ms per MB of plain prose. Linear is ~1 ms.
+ const prose = 'Plain prose with no code at all, just words.\n'.repeat(45_000);
+ const start = performance.now();
+ expect(scanMarkdownCode(prose).fenced).toEqual([]);
+ expect(performance.now() - start).toBeLessThan(150);
+ });
+
+ test('stays linear with thousands of quoted markers on one long line', () => {
+ // Inline spans are computed per marker line on demand; a line's spans must
+ // be computed once, not once per marker on it.
+ const line = `\`${TAKES_FENCE_BEGIN}\` `.repeat(20_000);
+ const start = performance.now();
+ expect(indexOfOutsideCode(line, TAKES_FENCE_BEGIN)).toBe(-1);
+ expect(performance.now() - start).toBeLessThan(150);
+ });
+
+ test('stays linear across many marker lines on a page with no backticks', () => {
+ // A facts/takes-heavy page without inline code: judging each marker line
+ // must not search the rest of the body for a backtick.
+ const body = `${FACTS_FENCE_BEGIN}\n${'x'.repeat(80)}\n`.repeat(20_000);
+ const start = performance.now();
+ const code = scanMarkdownCode(body);
+ let n = 0;
+ for (let at = indexOfOutsideCode(body, FACTS_FENCE_BEGIN); at !== -1; at = indexOfOutsideCode(body, FACTS_FENCE_BEGIN, at + 1, code)) n++;
+ expect(n).toBe(20_000);
+ expect(performance.now() - start).toBeLessThan(150);
+ });
+
+ test('stays linear when a lone CR sits far before many marker lines', () => {
+ // Finding a marker's line must never search toward the start of the body.
+ const body = 'head\r' + `plain line of prose here\n\`${TAKES_FENCE_BEGIN}\`\n`.repeat(20_000);
+ const start = performance.now();
+ expect(indexOfOutsideCode(body, TAKES_FENCE_BEGIN)).toBe(-1);
+ expect(performance.now() - start).toBeLessThan(150);
+ });
+
+ test('indexOfOutsideCode skips quoted occurrences and finds the live one', () => {
+ const body = `\`${TAKES_FENCE_BEGIN}\`\n${TAKES_FENCE_BEGIN}`;
+ expect(indexOfOutsideCode(body, TAKES_FENCE_BEGIN)).toBe(body.lastIndexOf(TAKES_FENCE_BEGIN));
+ expect(indexOfOutsideCode('`only quoted`', 'quoted')).toBe(-1);
+ });
+
+ test('unclosedCodeFenceStart ignores closed fences', () => {
+ expect(unclosedCodeFenceStart('a\n```\nb\n```\nc')).toBe(-1);
+ expect(unclosedCodeFenceStart('a\n```\nb\n```\n~~~\nc')).toBe('a\n```\nb\n```\n'.length);
+ });
+});
+
+describe('takes fence markers quoted in code are documentation', () => {
+ test('parse ignores a fenced example and still reads the real fence after it', () => {
+ expect(parseTakesFence(`doc\n\n${takesExample}\n`)).toEqual({ takes: [], warnings: [] });
+ const body = `doc\n\n${takesExample}\n\n${realTakes('REAL-CLAIM')}`;
+ expect(parseTakesFence(body).takes.map(t => t.claim)).toEqual(['REAL-CLAIM']);
+ });
+
+ test('an inline-code mention of the marker is neither unbalanced nor a near miss', () => {
+ const body = `The marker is \`${TAKES_FENCE_BEGIN}\` on its own line.\n\nTAIL`;
+ expect(parseTakesFence(body).warnings).toEqual([]);
+ expect(parseTakesFence(`mention \`<!-- gbrain:takes:begin -->\``).warnings).toEqual([]);
+ });
+
+ test('upsert leaves the example untouched and adds a real fence', () => {
+ const body = `doc\n\n${takesExample}\n`;
+ const out = upsertTakeRow(body, take('REAL-CLAIM')).body;
+ expect(out.startsWith(body)).toBe(true);
+ expect(parseTakesFence(out).takes.map(t => t.claim)).toEqual(['REAL-CLAIM']);
+ });
+
+ test('strip hides the example too: the privacy boundary never trusts code blocks', () => {
+ const body = `doc\n\n${takesExample}\n\n${realTakes('REAL-CLAIM')}`;
+ const out = stripTakesFence(body);
+ expect(out).not.toContain('EXAMPLE-CLAIM');
+ expect(out).not.toContain('REAL-CLAIM');
+ });
+});
+
+describe('remote privacy boundary', () => {
+ test('the boundary never hides less than the lexical scan: an inline-code marker still protects its tail', () => {
+ // Readers no longer treat the mention as a fence, but the privacy boundary
+ // only ever changes toward hiding more, so the tail stays protected.
+ const body = `intro\n\nThe marker is \`${TAKES_FENCE_BEGIN}\` on its own line.\n\nPRIVATE TAIL`;
+ expect(parseTakesFence(body)).toEqual({ takes: [], warnings: [] });
+ expect(sanitizeRemoteBody(body)).not.toContain('PRIVATE TAIL');
+ expect(stripTakesFence(body)).not.toContain('PRIVATE TAIL');
+ });
+
+ test('a real fence after a documented example is still stripped', () => {
+ const body = `doc\n\n${takesExample}\n\n${realTakes('SECRET-CLAIM')}\n\nafter`;
+ const out = sanitizeRemoteBody(body);
+ expect(out).not.toContain('EXAMPLE-CLAIM');
+ expect(out).not.toContain('SECRET-CLAIM');
+ expect(out).toContain('after');
+ });
+
+ test('fails closed: a fence after an unclosed code block is still stripped', () => {
+ const body = `doc\n\n\`\`\`text\nnever closed\n\n${realTakes('SECRET-CLAIM')}\n`;
+ expect(sanitizeRemoteBody(body)).not.toContain('SECRET-CLAIM');
+ expect(stripTakesFence(body)).not.toContain('SECRET-CLAIM');
+ });
+
+ test('every take the parser sees is hidden from remote readers', () => {
+ const bodies = [
+ realTakes('P1'),
+ `${takesExample}\n\n${realTakes('P2')}`,
+ `\`${TAKES_FENCE_BEGIN}\`\n\n${realTakes('P3')}`,
+ `\`\`\`\nunclosed\n${realTakes('P4')}`,
+ ];
+ for (const body of bodies) {
+ const claims = parseTakesFence(body).takes.map(t => t.claim);
+ expect(claims.length).toBe(1);
+ for (const claim of claims) expect(sanitizeRemoteBody(body)).not.toContain(claim);
+ }
+ });
+
+ test('private facts stay hidden when a facts example precedes the fence', () => {
+ const body = `doc\n\n${factsExample}\n\n${worldAndPrivateFacts}\n`;
+ const out = sanitizeRemoteBody(body);
+ expect(out).not.toContain('EXAMPLE-FACT');
+ expect(out).toContain('WORLD-FACT');
+ expect(out).not.toContain('PRIVATE-FACT');
+ });
+});
+
+describe('remote page replacement', () => {
+ test('a remote replacement of a page with an unpaired inline-code marker stays refused (unchanged boundary)', () => {
+ const stored = `The marker is \`${TAKES_FENCE_BEGIN}\`.\n`;
+ expect(() => preserveProtectedTakes(`${stored}edit\n`, stored)).toThrow('must be repaired');
+ });
+
+ test('two live fences in one section are still rejected', () => {
+ const twice = `${realTakes('A')}\n\n${realTakes('B')}\n`;
+ expect(() => compileCanonicalProjections(page(twice), 'docs/fences', 'default')).toThrow('at most one');
+ const strayEnd = `${realTakes('A')}\n${TAKES_FENCE_END}\n`;
+ expect(() => compileCanonicalProjections(page(strayEnd), 'docs/fences', 'default')).toThrow('at most one');
+ const bothFacts = `${worldAndPrivateFacts}\n\n${worldAndPrivateFacts}\n`;
+ expect(() => compileCanonicalProjections(page(bothFacts), 'docs/fences', 'default')).toThrow('at most one');
+ });
+
+ test('a documented example plus a real fence passes the canonical projection checks', () => {
+ const body = `doc\n\n${takesExample}\n\n${realTakes('REAL-CLAIM')}\n\n${factsExample}\n`;
+ const compiled = compileCanonicalProjections(page(body), 'docs/fences', 'default');
+ expect(compiled.takes.map(t => t.claim)).toEqual(['REAL-CLAIM']);
+ expect(compiled.quoted?.takes.has('1:EXAMPLE-CLAIM')).toBe(true);
+ });
+});
+
+describe('facts fence', () => {
+ test('parse ignores a fenced example; strip and withdrawal enumeration still cover it', () => {
+ const body = `doc\n\n${factsExample}\n\n${worldAndPrivateFacts}\n`;
+ expect(parseFactsFence(body).facts.map(f => f.claim)).toEqual(['WORLD-FACT', 'PRIVATE-FACT']);
+ expect(stripFactsFence(body)).not.toContain('EXAMPLE-FACT');
+ // Withdrawal keeps enumerating every lexical fence (privacy direction), the real one included.
+ expect(withdrawalFenceBlocks(body).at(-1)!.parsed.facts.map(f => f.claim)).toEqual(['WORLD-FACT', 'PRIVATE-FACT']);
+ });
+});
+
+describe('fence placement above an unclosed code block', () => {
+ test('a new takes fence is not written inside an unclosed code block', () => {
+ const body = 'doc\n\n```text\nnever closed\n';
+ const out = upsertTakeRow(body, take('REAL-CLAIM')).body;
+ const fenceAt = out.indexOf(TAKES_FENCE_BEGIN);
+ expect(fenceAt).toBeGreaterThan(-1);
+ expect(fenceAt).toBeLessThan(out.indexOf('```text'));
+ expect(out.endsWith('```text\nnever closed\n')).toBe(true);
+ expect(parseTakesFence(out).takes.map(t => t.claim)).toEqual(['REAL-CLAIM']);
+ });
+
+ test('a new facts fence is not written inside an unclosed code block', () => {
+ const body = 'doc\n\n```text\nnever closed\n';
+ const out = replaceOrInsertFactsFence(body, worldAndPrivateFacts);
+ expect(out.indexOf(FACTS_FENCE_BEGIN)).toBeLessThan(out.indexOf('```text'));
+ expect(out.endsWith('```text\nnever closed\n')).toBe(true);
+ });
+
+ test('without an unclosed code block the placement is unchanged', () => {
+ expect(upsertTakeRow('doc\n', take('X')).body.startsWith('doc\n\n## Takes\n\n')).toBe(true);
+ expect(replaceOrInsertFactsFence('doc\n', worldAndPrivateFacts)).toBe(`doc\n\n## Facts\n\n${worldAndPrivateFacts}\n`);
+ });
+});
+
+/**
+ * A stray ``` pairs with a later block's opener, so a real fence between them
+ * reads as the inside of a closed code block. The shapes below are the ways
+ * that happens; none may expose a protected row.
+ */
+const stray = 'doc\n\n```\nnever closed\n\n';
+const mispaired = {
+ // The later block's closer is left unpaired: an unclosed fence remains.
+ shifted: (fence: string) => `${stray}${fence}\n\n\`\`\`\ncode\n\`\`\`\n`,
+ // An info string cannot close a block, so everything pairs up and no
+ // unclosed fence is left to reveal the mispairing.
+ infoString: (fence: string) => `${stray}${fence}\n\n\`\`\`ts\ncode\n\`\`\`\n`,
+ // Deliberately wrapped in a balanced code block.
+ wrapped: (fence: string) => `doc\n\n\`\`\`\n${fence}\n\`\`\`\n`,
+};
+
+describe('mispaired code fences at the privacy boundary', () => {
+ for (const [name, shape] of Object.entries(mispaired)) {
+ test(`${name}: takes stay hidden from every boundary consumer`, () => {
+ const body = shape(realTakes('SECRET-CLAIM'));
+ expect(sanitizeRemoteBody(body)).not.toContain('SECRET-CLAIM');
+ expect(stripTakesFence(body)).not.toContain('SECRET-CLAIM');
+ });
+
+ test(`${name}: private facts stay hidden from every boundary consumer`, () => {
+ const body = shape(worldAndPrivateFacts);
+ expect(sanitizeRemoteBody(body)).not.toContain('PRIVATE-FACT');
+ expect(stripFactsFence(body)).not.toContain('PRIVATE-FACT');
+ expect(stripFactsFence(body, { keepVisibility: ['world'] })).not.toContain('PRIVATE-FACT');
+ });
+ }
+
+ test('readers see a mispaired real fence again', () => {
+ for (const shape of [mispaired.shifted, mispaired.infoString]) {
+ expect(parseTakesFence(shape(realTakes('REAL-CLAIM'))).takes.map(t => t.claim)).toEqual(['REAL-CLAIM']);
+ }
+ });
+
+ test('readers treat a deliberately wrapped fence as code', () => {
+ expect(parseTakesFence(mispaired.wrapped(realTakes('REAL-CLAIM'))).takes).toEqual([]);
+ });
+
+ test('a fence readers see stays hidden up to the end marker readers pair with it', () => {
+ // An end marker quoted in a code block inside the fence does not end it
+ // for readers, so it must not end the hidden region either.
+ const quotedEnd = ['```', TAKES_FENCE_END, '```'].join('\n');
+ const body = [
+ TAKES_FENCE_BEGIN,
+ '| # | claim | kind | who | weight | since | source |',
+ '|---|---|---|---|---|---|---|',
+ '| 1 | FIRST-SECRET | take | alice-example | 0.5 | 2026-01 | x |',
+ quotedEnd,
+ '| 2 | SECOND-SECRET | take | alice-example | 0.5 | 2026-01 | x |',
+ TAKES_FENCE_END,
+ 'after',
+ ].join('\n');
+ const claims = parseTakesFence(body).takes.map(t => t.claim);
+ expect(claims).toContain('SECOND-SECRET');
+ for (const out of [sanitizeRemoteBody(body), stripTakesFence(body)]) {
+ for (const claim of claims) expect(out).not.toContain(claim);
+ expect(out).toContain('after');
+ }
+ });
+
+ test('a remote replacement keeps a mispaired real fence', () => {
+ const stored = mispaired.shifted(realTakes('REAL-CLAIM'));
+ const incoming = `${sanitizeRemoteBody(stored).trimEnd()}\nedit\n`;
+ expect(preserveProtectedTakes(incoming, stored)).toContain('REAL-CLAIM');
+ });
+
+ test('a remote replacement of a page whose only fence is a code example is refused', () => {
+ // Re-appending the hidden example at EOF would make it a live fence.
+ const stored = `doc\n\n${takesExample}\n`;
+ const incoming = `${sanitizeRemoteBody(stored).trimEnd()}\nedit\n`;
+ expect(() => preserveProtectedTakes(incoming, stored)).toThrow('inside markdown code');
+ });
+});
+
+describe('timeline sentinel quoted in code', () => {
+ const SENTINEL = '<!-- timeline -->';
+ const entry = '- **2026-01-01** | manual — entry';
+
+ test('a sentinel inside a code block example does not split the page', () => {
+ const body = `Intro\n\n\`\`\`markdown\n${SENTINEL}\n\`\`\`\n\nMore prose.\n\n${SENTINEL}\n\n${entry}`;
+ expect(splitBody(body)).toEqual({
+ compiled_truth: `Intro\n\n\`\`\`markdown\n${SENTINEL}\n\`\`\`\n\nMore prose.\n`,
+ timeline: `\n${entry}`,
+ });
+ });
+
+ test('a legacy --- plus ## Timeline pair inside a code block does not split the page', () => {
+ const body = 'Intro\n\n```\n---\n## Timeline\n```\n\nAfter.';
+ expect(splitBody(body)).toEqual({ compiled_truth: body, timeline: '' });
+ });
+
+ test('the serializer\'s sentinel still splits when a stray fence mispairs the blocks', () => {
+ for (const opener of ['```', '```ts']) {
+ const body = `Intro\n\n\`\`\`\nstray\n\n${SENTINEL}\n\n${entry}\n\n${opener}\ncode\n\`\`\``;
+ expect(splitBody(body).timeline).toContain(entry);
+ }
+ });
+
+ test('a new facts fence lands above the real sentinel, not above a quoted one', () => {
+ const body = `doc\n\n\`\`\`markdown\n${SENTINEL}\n\`\`\`\n\nprose\n\n${SENTINEL}\n\n${entry}\n`;
+ const out = replaceOrInsertFactsFence(body, worldAndPrivateFacts);
+ expect(out.indexOf(FACTS_FENCE_BEGIN)).toBeGreaterThan(out.indexOf('prose'));
+ expect(out.indexOf(FACTS_FENCE_BEGIN)).toBeLessThan(out.lastIndexOf(SENTINEL));
+ });
+});
+
+/**
+ * Adversarial matrix for the remote privacy boundary (fix wave 10, #5397).
+ * Every stored body below holds a real takes fence with SECRET and real facts
+ * with PRIVATE-FACT next to a trap: unbalanced fences, CRLF / CR, nested
+ * backtick and tilde fences, indented code, inline-code markers, and a marker
+ * inside a quoted code block. For each one the secret must stay hidden from
+ * remote reads and chunk strips, and a remote write may neither drop the
+ * stored fence nor replace it with an attacker's fence.
+ */
+describe('adversarial fence matrix (remote privacy)', () => {
+ const SECRET = 'SECRET-TAKE-CLAIM';
+ const realFence = realTakes(SECRET);
+ const facts = worldAndPrivateFacts;
+ const fenceBody = `${realFence}\n\n${facts}`;
+ const indent = (text: string) => text.split('\n').map(l => ` ${l}`).join('\n');
+ const quote = (text: string) => text.split('\n').map(l => `> ${l}`).join('\n');
+ const traps: Record<string, string> = {
+ 'unclosed fence before': `doc\n\n\`\`\`text\nnever closed\n\n${fenceBody}\n`,
+ 'unclosed fence after': `doc\n\n${fenceBody}\n\n\`\`\`\nopen to EOF\n`,
+ 'stray closer before': `doc\n\n\`\`\`\n\n${fenceBody}\n\`\`\`\ntail\n`,
+ 'code end marker inside the real fence': `doc\n\n${realFence.replace('\n|', `\n\`${TAKES_FENCE_END}\`\n|`)}\n\n${facts}\n`,
+ 'fenced end marker inside the real fence': `doc\n\n${realFence.replace(TAKES_FENCE_END, `\`\`\`\n${TAKES_FENCE_END}\n\`\`\`\n${TAKES_FENCE_END}`)}\n\n${facts}\n`,
+ 'nested backtick in tilde wrap': `doc\n\n~~~~\n\`\`\`\n${fenceBody}\n\`\`\`\n~~~~\ntail\n`,
+ 'nested tilde in backtick wrap': `doc\n\n\`\`\`\`markdown\n~~~\n${fenceBody}\n~~~\n\`\`\`\`\ntail\n`,
+ 'mismatched fence chars': `doc\n\n\`\`\`\n${fenceBody}\n~~~\ntail\n`,
+ 'indented code block': `doc\n\n${indent(fenceBody)}\n\ntail\n`,
+ 'inline begin before the real fence': `doc \`${TAKES_FENCE_BEGIN}\` and \`${FACTS_FENCE_BEGIN}\`\n\n${fenceBody}\n`,
+ 'inline end before the real fence': `doc \`${TAKES_FENCE_END}\` and \`${FACTS_FENCE_END}\`\n\n${fenceBody}\n`,
+ 'marker in a quoted code block': `doc\n\n${quote(`\`\`\`markdown\n${fenceBody}\n\`\`\``)}\n\ntail\n`,
+ 'quoted code block then real fence': `doc\n\n${quote(`\`\`\`markdown\n${TAKES_FENCE_BEGIN}\n\`\`\``)}\n\n${fenceBody}\n`,
+ };
+ const variants: Array<[string, string]> = Object.entries(traps).flatMap(([name, body]) => [
+ [name, body], [`${name} (CRLF)`, body.replace(/\n/g, '\r\n')], [`${name} (CR)`, body.replace(/\n/g, '\r')],
+ ]);
+
+ for (const [name, body] of variants) {
+ test(`${name}: hidden from remote reads and chunk strips`, () => {
+ for (const out of [sanitizeRemoteBody(body), stripFactsFence(stripTakesFence(body)), stripFactsFence(stripTakesFence(body), { keepVisibility: ['world'] })]) {
+ expect(out).not.toContain(SECRET);
+ expect(out).not.toContain('PRIVATE-FACT');
+ }
+ });
+
+ test(`${name}: a remote round trip never drops the stored fence`, () => {
+ const incoming = `${sanitizeRemoteBody(body).trimEnd()}\nedit\n`;
+ let out: string | undefined;
+ try { out = preserveProtectedTakes(incoming, body); } catch (e) { expect((e as Error).name).toBe('OperationError'); return; }
+ expect(out).toContain(SECRET);
+ });
+
+ for (const [how, fake] of [
+ ['plain', realTakes('ATTACKER-CLAIM')],
+ ['in a code block', `\`\`\`\n${realTakes('ATTACKER-CLAIM')}\n\`\`\``],
+ ['in inline code', `\`${TAKES_FENCE_BEGIN}\` ATTACKER-CLAIM \`${TAKES_FENCE_END}\``],
+ ['as a bare begin', `${TAKES_FENCE_BEGIN}\n| 1 | ATTACKER-CLAIM |`],
+ ] as const) {
+ test(`${name}: a remote fake fence (${how}) cannot overwrite the stored take`, () => {
+ const incoming = `${sanitizeRemoteBody(body).trimEnd()}\n\n${fake}\n`;
+ let out: string | undefined;
+ try { out = preserveProtectedTakes(incoming, body); } catch (e) { expect((e as Error).name).toBe('OperationError'); return; }
+ // Accepted only when the fake was no fence at all: the stored fence is
+ // kept verbatim and no attacker row reaches the readers.
+ expect(out).toContain(SECRET);
+ expect(parseTakesFence(out).takes.map(t => t.claim)).not.toContain('ATTACKER-CLAIM');
+ });
+ }
+ }
+
+ test('every boundary refusal renders the agent contract without echoing page text', async () => {
+ const { renderCliError } = await import('../src/core/agent-output.ts');
+ const errors: unknown[] = [];
+ for (const [stored, incoming] of [
+ [`doc\n\n${TAKES_FENCE_BEGIN}\n| 1 | ${SECRET} |\n`, 'x\n'],
+ [`doc\n\n${takesExample}\n`, 'doc\nedit\n'],
+ [`doc\n\n${realFence}\n`, `doc\n\n${realTakes('ATTACKER-CLAIM')}\n`],
+ ] as const) {
+ try { preserveProtectedTakes(incoming, stored); } catch (e) { errors.push(e); }
+ }
+ expect(errors).toHaveLength(3);
+ for (const e of errors) {
+ const env = JSON.parse(renderCliError(e, { json: true, command: 'put', tty: false }).stdout!);
+ expect(['invalid_params', 'permission_denied']).toContain(env.code);
+ expect(env.message).toBeTruthy();
+ expect(env.suggestion).toBeTruthy();
+ expect(JSON.stringify(env)).not.toContain(SECRET);
+ expect(JSON.stringify(env)).not.toContain('ATTACKER-CLAIM');
+ }
+ });
+});
diff --git a/test/fence-marker-projection.test.ts b/test/fence-marker-projection.test.ts
new file mode 100644
index 0000000000..35196d287e
--- /dev/null
+++ b/test/fence-marker-projection.test.ts
@@ -0,0 +1,107 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { renderFactsTable } from '../src/core/facts-fence.ts';
+import { renderTakesFence } from '../src/core/takes-fence.ts';
+
+/**
+ * The canonical projection mirrors the body's fences into the takes and facts
+ * tables, deleting or expiring rows the body no longer holds. Readers skip a
+ * fence inside a code block, so without a guard a real fence wrapped in one
+ * would silently drop its rows.
+ */
+let engine: PGLiteEngine;
+let ctx: OperationContext;
+const root = mkdtempSync(join(tmpdir(), 'gbrain-fence-projection-'));
+const sourceId = 'fence-projection-test';
+
+const takes = (claim: string) => renderTakesFence([{ rowNum: 1, claim, kind: 'take', holder: 'world', weight: 0.7, active: true }]);
+const facts = (claim: string) => renderFactsTable([{ rowNum: 1, claim, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true }]);
+const fences = (take: string, fact: string) => `## Takes\n\n${takes(take)}\n\n## Facts\n\n${facts(fact)}\n`;
+const example = `\`\`\`\`markdown\n${takes('Doc example belief')}\n${facts('Doc example fact')}\n\`\`\`\`\n`;
+
+async function put(slug: string, body: string) {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });
+ return submitPageMutation(ctx, { operation: 'put_page', params: {
+ request_id: randomUUID(), slug, content: `---\ntype: note\ntitle: ${slug}\n---\n${body}`,
+ ...(snapshot ? { expected_revision: snapshot.revision } : {}),
+ } });
+}
+
+async function rows(slug: string) {
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ const [t] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int n FROM takes WHERE page_id=$1', [snapshot.page.id]);
+ const [f] = await engine.executeRaw<{ n: number }>(
+ 'SELECT count(*)::int n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND expired_at IS NULL', [sourceId, slug]);
+ return { takes: t!.n, facts: f!.n };
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ ctx = { engine, config: { engine: 'pglite' }, sourceId, remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } } as OperationContext;
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+}, 120_000);
+
+afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+ rmSync(root, { recursive: true, force: true });
+});
+
+test('wrapping a real fence in a code block is refused instead of dropping its rows', async () => {
+ await put('wrapped', `Intro\n\n${fences('Example belief', 'Example fact')}`);
+ expect(await rows('wrapped')).toEqual({ takes: 1, facts: 1 });
+ await expect(put('wrapped', `Intro\n\n\`\`\`\n${fences('Example belief', 'Example fact')}\`\`\`\n`)).rejects.toThrow('inside markdown code');
+ expect(await rows('wrapped')).toEqual({ takes: 1, facts: 1 });
+});
+
+test('a stray fence before the real fence keeps its rows', async () => {
+ const shapes = [
+ (f: string) => `Intro\n\n\`\`\`\nstray never closed\n\n${f}`,
+ (f: string) => `Intro\n\n\`\`\`\nstray\n\n${f}\n\`\`\`\ncode\n\`\`\`\n`,
+ (f: string) => `Intro\n\n\`\`\`\nstray\n\n${f}\n\`\`\`ts\ncode\n\`\`\`\n`,
+ ];
+ for (const [i, shape] of shapes.entries()) {
+ const slug = `stray-${i}`;
+ await put(slug, `Intro\n\n${fences('Example belief', 'Example fact')}`);
+ await put(slug, shape(fences('Example belief', 'Example fact')));
+ expect(await rows(slug)).toEqual({ takes: 1, facts: 1 });
+ }
+});
+
+test('a code example beside the real fence does not block ordinary writes', async () => {
+ await put('example-only', example);
+ expect(await rows('example-only')).toEqual({ takes: 0, facts: 0 });
+
+ await put('edited', `${example}\n${fences('Example belief', 'Example fact')}`);
+ await put('edited', `${example}\n${fences('Edited belief', 'Edited fact')}`);
+ expect(await rows('edited')).toEqual({ takes: 1, facts: 1 });
+
+ await put('deleted', `${example}\n${fences('Example belief', 'Example fact')}`);
+ await put('deleted', example);
+ expect(await rows('deleted')).toEqual({ takes: 0, facts: 0 });
+});
+
+test('every way of quoting a real fence in code is refused instead of dropping its rows', async () => {
+ const wraps = [
+ (f: string) => `Intro\n\n~~~~\n${f}~~~~\n`,
+ (f: string) => `Intro\n\n\`\`\`\`markdown\n~~~\n${f}~~~\n\`\`\`\`\n`,
+ (f: string) => `Intro\n\n${f.replace(/<!--- gbrain:(takes|facts):begin -->/g, m => `\`${m}\``)}`,
+ (f: string) => `Intro\r\n\r\n\`\`\`\r\n${f.replace(/\n/g, '\r\n')}\`\`\`\r\n`,
+ ];
+ for (const [i, wrap] of wraps.entries()) {
+ const slug = `quoted-${i}`;
+ await put(slug, `Intro\n\n${fences('Example belief', 'Example fact')}`);
+ // Refused either as a quoted fence or as an unbalanced one; the rows are kept both ways.
+ await expect(put(slug, wrap(fences('Example belief', 'Example fact')))).rejects.toThrow(/inside markdown code|cannot be parsed losslessly/);
+ expect(await rows(slug)).toEqual({ takes: 1, facts: 1 });
+ }
+});