Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(fences): repair prose-quoted fence markers by wrapping them in backticks (#8059)
garrytan0d160ec860e0
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex c1109ee612..84ae528276 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2235,7 +2235,7 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| A facts or takes fence in the page cannot be imported without dropping or guessing rows, so the page (or the file) was not written. | Facts and takes fences are the page's structured rows. Importing a fence that does not parse, repeats a marker or reuses a row number would silently drop or renumber rows, so coordinated writers refuse it and managed sync holds the one file while the rest of the source syncs. | A refused write: fix the fence the message names (fence, section and rows; the reason says what is wrong) and send the page again with a new request_id, or write rows with remember / takes_add. A held file or stored page: the maintenance run repairs it; preview it now with gbrain repair fences --source <id> on the brain host. | agent | `repeat the read that failed` | 1 | no |-Reasons: `header_unmapped`, `no_header`, `row_before_header`, `short_row`, `extra_cells`, `claim_split`, `holder_unresolved`, `missing_begin`, `split_rows`, `unclosed_trailing_content`, `unclosed_ambiguous_tail`, `tail_exposure_approval`, `marker_near_miss`, `repeated_marker`, `takes_in_facts`, `superseded_ambiguous`, `enum_unmapped`, `weight_missing`, `holder_missing`, `confidence_out_of_range`, `claim_value_invalid`, `takes_kind_unsupported`, `unparseable`, `row_collision`, `quoted_fence_rows`, `stored_row_collision`, `withdrawn_claim_in_malformed_fence`, `target_fence_malformed`, `prepare_time`, `normalizer_failed`, `llm_unavailable`, `llm_empty`, `llm_refused`, `llm_malformed`, `llm_truncated`, `llm_declined`, `llm_disabled`, `no_measured_model`, `budget_exhausted`, `no_pricing`, `ledger_unavailable`, `owner_unavailable`, `owner_cli_required`, `host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`, `sync_in_progress`, `time_budget`, `changed_since_read`, `changed_since_preview`, `still_invalid`, `claim_changed`, `row_number_changed`, `visibility_loosened`, `row_count_changed`, `cell_changed`, `protection_loosened`.+Reasons: `header_unmapped`, `no_header`, `row_before_header`, `short_row`, `extra_cells`, `claim_split`, `holder_unresolved`, `missing_begin`, `split_rows`, `unclosed_trailing_content`, `unclosed_ambiguous_tail`, `tail_exposure_approval`, `quoted_marker`, `marker_near_miss`, `repeated_marker`, `takes_in_facts`, `superseded_ambiguous`, `enum_unmapped`, `weight_missing`, `holder_missing`, `confidence_out_of_range`, `claim_value_invalid`, `takes_kind_unsupported`, `unparseable`, `row_collision`, `quoted_fence_rows`, `stored_row_collision`, `withdrawn_claim_in_malformed_fence`, `target_fence_malformed`, `prepare_time`, `normalizer_failed`, `llm_unavailable`, `llm_empty`, `llm_refused`, `llm_malformed`, `llm_truncated`, `llm_declined`, `llm_disabled`, `no_measured_model`, `budget_exhausted`, `no_pricing`, `ledger_unavailable`, `owner_unavailable`, `owner_cli_required`, `host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`, `sync_in_progress`, `time_budget`, `changed_since_read`, `changed_since_preview`, `still_invalid`, `claim_changed`, `row_number_changed`, `visibility_loosened`, `row_count_changed`, `cell_changed`, `protection_loosened`.More: [docs/guides/write-refusals.md#invalid_fence](../../docs/guides/write-refusals.md#invalid_fence)diff --git a/docs/guides/fence-format.md b/docs/guides/fence-format.mdindex 9bddff0271..e99ef2c904 100644--- a/docs/guides/fence-format.md+++ b/docs/guides/fence-format.md@@ -189,6 +189,7 @@ These rules run on every write path for free. They edit or move cell text and ne| `holder_alias` | Takes holder `system`, `assistant`, `ai`, `agent`, `gbrain`, `model` (any case) → `brain`. || `confidence_format` | A percent or a number with stray spaces in `confidence` or `weight` becomes a decimal: `85%` → `0.85`, `0. 8` → `0.8`. A number outside 0 to 1 is `confidence_out_of_range`. || `holder_verified` | Tier 2, not Tier 1: a takes holder written as a name becomes the one `people/` or `companies/` page it resolves to exactly. On a world-visible page a private page never matches. Anything less certain stays `holder_unresolved`. |+| `quote_marker` | Repair only (`gbrain repair fences` and the content-repair lane), never on a write: a facts or takes marker quoted in prose (text follows it on its line, or it sits on a blockquote line, outside code and table lines, and it begins or ends no fence that holds rows) is wrapped in backticks, so readers see an example rather than a fence. The edit is kept only when every row of every fence stays where it was and the privacy boundary hides at least what it hid. A page whose only problem is such a mention reads `quoted_marker`. |<a id="header-spellings"></a>### Header spellingsdiff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 37aec25d0c..ac89f14174 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -3023,7 +3023,7 @@ Each candidate gets the cheapest tier that repairs it exactly:| Tier | What it does | Cost || --- | --- | --- |-| `deterministic` | The lossless rules every write already runs (missing end marker, stray empty cells with one valid removal, row numbers, header aliases and order, enum and kind synonyms, assistant holders, percent confidences). | Free. |+| `deterministic` | The lossless rules every write already runs (missing end marker, stray empty cells with one valid removal, row numbers, header aliases and order, enum and kind synonyms, assistant holders, percent confidences), plus one only the repair runs: a fence marker quoted in prose (`quoted_marker`) is wrapped in backticks, kept only when every fence row stays put and nothing hidden becomes visible. | Free. || `resolver` | A holder written as a display name becomes the `people/` or `companies/` page it names, only on an exact match (slug, unique slug basename or alias; never a guess, never a private page on a world-visible page). | Free. || `llm` | Rows only a rewrite can realign (no header, a header column with no canonical name, rows above the header, short rows). The repair model sees only the fence header and those rows, never valid rows of a row-level problem and never the rest of the page, with no tools, and answers HOLD instead of guessing when a row has two readings. | Paid, within `fences.repair.max_usd_per_page` ($0.30) and `fences.repair.max_usd_per_day` ($1.00). || `manual` | Anything gbrain never guesses (a stray end marker, an unknown takes kind, a weight out of range, a holder no page matches, extra cells that removing empty cells cannot line up, a sentence in the facts `kind` column). The preview names the exact edit. | Your edit. |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex a918b2cda4..401a0051f7 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -440,6 +440,7 @@ clears or retries it with no one acting.| <a id="fence-unclosed_trailing_content"></a>`unclosed_trailing_content` | A fence has no end marker and lines holding a pipe follow its table, so the rules cannot tell table rows from prose. | `llm` | yes | The maintenance run asks the repair model whether the tail is prose; a prose tail closes the fence after its last row (on a private page by itself; on a world-visible page after the user approves the lines it shows, see `tail_exposure_approval`). A tail of plain prose with no pipe never reaches the model: it closes by itself on a private page and waits for approval on a world page. By hand: add the end marker directly after the last table row. Format: [markers](fence-format.md#markers). || <a id="fence-unclosed_ambiguous_tail"></a>`unclosed_ambiguous_tail` | A fence has no end marker and the lines after its table are not plain prose: a row written without pipes, a mention of a fence marker, or a tail the repair model read as rows or could not classify. | `manual` | no | Add the end marker directly after the last table row and fix the rows below it, or wrap a marker mention in backticks; gbrain does not guess where the fence ends. Format: [markers](fence-format.md#markers). || <a id="fence-tail_exposure_approval"></a>`tail_exposure_approval` | A fence on a world-visible page has no end marker and prose follows its table; gbrain can close it after the last row, but the lines after the table would then be visible to readers of the page, so the close waits for the user. | `deterministic` | no | `gbrain repair fences --source <source> --only <path>` previews the close and prints the lines that would become visible with the apply command (`--apply --expect <hash>`); run it once the user agrees. Unattended runs never close it. Format: [markers](fence-format.md#markers). |+| <a id="fence-quoted_marker"></a>`quoted_marker` | A line quotes a facts or takes fence marker in prose (text follows the marker on its line, or the line is a blockquote), so the section reads as having a repeated or unclosed fence. | `deterministic` | yes | `gbrain repair fences --source <source> --only <path>` previews wrapping each mention in backticks and prints the apply command; `gbrain sync unblock --source <source> --apply` and the maintenance run apply it, with a receipt per file. Or wrap the mention in backticks yourself. Format: [markers](fence-format.md#markers). || <a id="fence-marker_near_miss"></a>`marker_near_miss` | A line uses the two-dash takes marker (`<!-- gbrain:takes:begin -->`) or mentions it with no takes table after it. Two-dash markers directly above a takes table are rewritten by themselves. | `manual` | no | Use the exact three-dash markers around the takes table, or wrap a mere mention in backticks. Format: [markers](fence-format.md#markers). || <a id="fence-repeated_marker"></a>`repeated_marker` | A body or timeline section has a second begin or end marker for the same fence outside code. Two or more fences that each have both markers, the same canonical header and nothing but table lines inside are merged by themselves (`merge_fences`: later rows appended, exact duplicates dropped, colliding numbers renumbered, a repeated section heading removed). | `manual` | no | Give the extra fence both markers and the first fence's header and move any other text out of it, so the next write or maintenance run merges them; or merge by hand, keeping one begin and one end marker per fence in that section with every row in one table. Format: [markers](fence-format.md#markers), [what gbrain rewrites](fence-format.md#normalized). || <a id="fence-takes_in_facts"></a>`takes_in_facts` | A facts fence holds a takes table. | `manual` | no | Move the rows into a takes fence (or add them with `takes_add`), or rewrite them as facts rows. Format: [takes](fence-format.md#takes-columns). |diff --git a/scripts/build-fence-format.ts b/scripts/build-fence-format.tsindex bca636787d..5a824a1e1f 100644--- a/scripts/build-fence-format.ts+++ b/scripts/build-fence-format.ts@@ -209,6 +209,7 @@ function normalizedTable(): string {holder_alias: `Takes holder ${codes(brainWords)} (any case) → \`brain\`.`,confidence_format: `A percent or a number with stray spaces in \`confidence\` or \`weight\` becomes a decimal: \`85%\` → ${code(confidenceFormat('85%')!)}, \`0. 8\` → ${code(confidenceFormat('0. 8')!)}. A number outside 0 to 1 is \`confidence_out_of_range\`.`,holder_verified: 'Tier 2, not Tier 1: a takes holder written as a name becomes the one `people/` or `companies/` page it resolves to exactly. On a world-visible page a private page never matches. Anything less certain stays `holder_unresolved`.',+ quote_marker: 'Repair only (`gbrain repair fences` and the content-repair lane), never on a write: a facts or takes marker quoted in prose (text follows it on its line, or it sits on a blockquote line, outside code and table lines, and it begins or ends no fence that holds rows) is wrapped in backticks, so readers see an example rather than a fence. The edit is kept only when every row of every fence stays where it was and the privacy boundary hides at least what it hid. A page whose only problem is such a mention reads `quoted_marker`.',} satisfies Record<FixClass, string>;const rows = Object.entries(text).map(([cls, what]) => `| ${code(cls)} | ${what} |`);return ['| Class | What it rewrites |', '| --- | --- |', ...rows].join('\n');diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex a834798000..578e61c529 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1372,6 +1372,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.514.0', id: 'storage_ignored_dirs_8015', text: 'When gbrain.yml lists a deprecated `supabase_only` next to canonical keys (which ignores it), a managed sync now holds only the missing-file pages under the ignored directories `db_only` does not already cover, and deletes other missing-file pages as usual; it used to hold every missing-file page of the source. `gbrain storage status` now names those directories, and the deprecation warning no longer points to a `gbrain doctor --fix` rename that does not exist. A `db_only` or `supabase_only` line whose inline value the parser refuses (a missing comma, a nested list, a bare scalar) now counts as unresolved even when another key resolves, so missing-file pages are held rather than deleted.' },{ since: '0.60.514.0', id: 'company_db_only_keep_8014', text: 'A company-brain source now keeps a live page under a declared `storage.db_only` directory when its file is not in the approved manifest, and keeps every such page while its gbrain.yml storage section is invalid, as other managed sources do; it used to delete them. The decision reads gbrain.yml at the approved commit, never the working tree.' },{ since: '0.60.514.0', id: 'redaction_marker_not_credential_7997', text: 'The transcript `labeled_credential` detector no longer reads an importer redaction marker (`login **<REDACTED:user-pattern>**`) as a typed user/password pair, so a correctly redacted page clears `gbrain transcripts audit-secrets`; a password written beside a marker is still found. The audit detector version moves to 3, so `gbrain doctor` asks for a fresh audit once.' },+ { since: '0.60.516.0', id: 'quoted_fence_marker_8059', text: 'A page that quotes a facts or takes fence marker in prose (text after the marker on its line, or a blockquote line) is now held or refused with the fence reason `quoted_marker` instead of `repeated_marker` or `unclosed_ambiguous_tail`, and `gbrain repair fences`, `gbrain repair content`, `gbrain sync unblock --apply` and the maintenance run repair it by wrapping each mention in backticks, with a receipt per file; readers count fence lines exactly as before. The edit is kept only when every fence row stays where it was and nothing the privacy boundary hid becomes visible. Existing `invalid_fence` holds are screened once more on the next sync. `forget` now locates the facts fence it rewrites with the parser\'s code-aware search, so a marker quoted in code above the fence no longer moves the rewrite.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/facts/forget.ts b/src/core/facts/forget.tsindex af11556e2e..21184359d5 100644--- a/src/core/facts/forget.ts+++ b/src/core/facts/forget.ts@@ -19,6 +19,7 @@ import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesyimport { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';import { parseFactsFence, renderFactsTable, type ParsedFact } from '../facts-fence.ts';import { contentHash } from '../utils.ts';+import { locateOutsideCode } from '../fence-scan.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';import { rewriteLiveSegmentedFences } from '../page-body/segment-rewrite.ts';import type { BodyRegion } from '../page-body/types.ts';@@ -90,8 +91,8 @@ export function strikeFenceRow(body: string, rowNum: number, strike: (fact: Parsconst target = parsed.facts.find(f => f.rowNum === rowNum);if (!target) return null;const updated: ParsedFact[] = parsed.facts.map(f => f.rowNum === rowNum ? strike(f) : f);- const begin = body.indexOf(FENCE_BEGIN);- const end = body.indexOf(FENCE_END, begin + 1);+ // The splice uses the parser's own code-aware locator: a marker quoted in code (an inline span) above the fence is not it (#8059).+ const { beginIdx: begin, endIdx: end } = locateOutsideCode(body, FENCE_BEGIN, FENCE_END);if (begin === -1 || end === -1) return null;return body.slice(0, begin) + renderFactsTable(updated) + body.slice(end + FENCE_END.length);}diff --git a/src/core/fence-repair/normalize.ts b/src/core/fence-repair/normalize.tsindex 84786ab612..a6a7f29571 100644--- a/src/core/fence-repair/normalize.ts+++ b/src/core/fence-repair/normalize.ts@@ -83,7 +83,7 @@ function failedIssues(page: FencePage): FenceIssue[] {return issues.length ? issues : [{ fence: 'facts', section: 'body', row: null, column: null, line: null, reason: 'normalizer_failed' }];}-function withSections<T extends FencePage>(page: T, texts: Record<FenceSection, string>): T {+export function withSections<T extends FencePage>(page: T, texts: Record<FenceSection, string>): T {const sameBody = texts.body === (page.compiled_truth ?? '');const sameTimeline = texts.timeline === (page.timeline ?? '');if (sameBody && sameTimeline) return page;diff --git a/src/core/fence-repair/quote-markers.ts b/src/core/fence-repair/quote-markers.tsnew file mode 100644index 0000000000..ae334ccad1--- /dev/null+++ b/src/core/fence-repair/quote-markers.ts@@ -0,0 +1,175 @@+/**+ * #8059 prose-quoted fence markers: the repair-only `quote_marker` edit.+ *+ * A page that quotes a facts or takes marker in prose (a transcript about+ * gbrain, a note on the format) fails the strict fence gate. This module+ * finds such mentions and wraps each in backticks, which every reader already+ * treats as code. It changes no reader's fence rule (#8020): it only edits+ * the page, and only the fences repair kind applies the edit, after the+ * validator's gates read the result against the original bytes.+ *+ * A marker is prose-quoted when it is one of the four exact tokens, sits+ * outside markdown code (the readers' own code map), is not on a table line,+ * and either has text after it on its line or sits on a blockquote line. Text+ * only before a marker ("Facts: <marker>") is not a mention: readers accept+ * that line as a fence. A marker next to a backtick is left alone. On every+ * line it touches, the inline code spans after the edit are exactly the old+ * spans plus the new ones, so no existing span re-pairs; a line where that+ * fails keeps its markers. Two shapes are real markers, never mentions,+ * because readers pair a marker with trailing text exactly as one alone on its+ * line (#8020): an end that closes a fence holding rows (in the raw-row+ * extraction), and a begin whose next non-blank line is a table line.+ *+ * `quoteMarkerStep` keeps the edit only when it proves, against the bytes as+ * read: every data row of every fence (primary or repeat) sits in a fence+ * after, at the same line, of the same kind; and every byte the privacy+ * boundary (`protectedRegions`) hid before is still hidden after, mapped+ * through the inserted backticks. The validator's primary-fence pairing+ * cannot judge this edit (it changes which fence is primary), so the rest of+ * the analysis is validated against the quoted page.+ *+ * Pure: no I/O. Fixes are location-only (fence, section, line).+ */+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';+import { codeEndAt, inlineCodeSpans, protectedRegions, scanMarkdownCode, type FencePair } from '../fence-scan.ts';+import { hasFenceText, withSections } from './normalize.ts';+import { sectionsOf } from './page-checks.ts';+import { extractRawRows } from './raw-rows.ts';+import type { FenceFix, FenceKind, FencePage, FenceSection } from './types.ts';++/** Bump when the mention rule changes: an `invalid_fence` hold screened under an older rule is screened once more (sync-holds.ts). */+export const QUOTE_SCREEN_VERSION = 1;++const PAIRS: readonly FencePair[] = [{ begin: FACTS_FENCE_BEGIN, end: FACTS_FENCE_END }, { begin: TAKES_FENCE_BEGIN, end: TAKES_FENCE_END }];++const MARKERS: ReadonlyArray<{ token: string; fence: FenceKind }> = [+ { token: FACTS_FENCE_BEGIN, fence: 'facts' }, { token: FACTS_FENCE_END, fence: 'facts' },+ { token: TAKES_FENCE_BEGIN, fence: 'takes' }, { token: TAKES_FENCE_END, fence: 'takes' },+];++interface Mention { fence: FenceKind; at: number; length: number; lineStart: number; lineEnd: number; line: number }++function lineBounds(text: string, at: number): [number, number] {+ const start = text.lastIndexOf('\n', at - 1) + 1;+ let end = text.indexOf('\n', at);+ if (end === -1) end = text.length;+ if (text[end - 1] === '\r') end--;+ return [start, end];+}++/** The next non-blank line after the line ending at `lineEnd`, or ''. */+function nextLine(text: string, lineEnd: number): string {+ for (let at = text.indexOf('\n', lineEnd); at !== -1 && at < text.length;) {+ const [start, end] = lineBounds(text, at + 1);+ if (text.slice(start, end).trim()) return text.slice(start, end);+ at = text.indexOf('\n', end);+ }+ return '';+}++/** The prose-quoted marker mentions of one section, in text order. */+function mentions(text: string, section: FenceSection): Mention[] {+ if (!hasFenceText(text)) return [];+ const code = scanMarkdownCode(text);+ const closesRows = new Set(extractRawRows(text, section).fences.filter(f => f.rows.length && f.end).map(f => f.end!.start));+ const found: Mention[] = [];+ for (const { token, fence } of MARKERS) {+ for (let at = text.indexOf(token); at !== -1; at = text.indexOf(token, at + token.length)) {+ if (closesRows.has(at) || codeEndAt(code, at) !== -1 || text[at - 1] === '`' || text[at + token.length] === '`') continue;+ const [lineStart, lineEnd] = lineBounds(text, at);+ if (token.endsWith('begin -->') && /^\s*\|/.test(nextLine(text, lineEnd))) continue;+ const line = text.slice(lineStart, lineEnd);+ if (/^\s*\|/.test(line)) continue;+ if (!text.slice(at + token.length, lineEnd).trim() && !/^ {0,3}>/.test(line)) continue;+ found.push({ fence, at, length: token.length, lineStart, lineEnd, line: text.slice(0, at).split('\n').length });+ }+ }+ return found.sort((a, b) => a.at - b.at);+}++/** One line with its mentions wrapped, or null when the line's code spans would change beyond the new ones. */+function wrapLine(line: string, offsets: ReadonlyArray<{ at: number; length: number }>): string | null {+ let out = '';+ let from = 0;+ for (const { at, length } of offsets) {+ out += `${line.slice(from, at)}\`${line.slice(at, at + length)}\``;+ from = at + length;+ }+ out += line.slice(from);+ const shift = (pos: number) => pos + 2 * offsets.filter(o => o.at < pos).length;+ const expected = [+ ...inlineCodeSpans(line).map(([s, e]) => [shift(s), shift(e)] as [number, number]),+ ...offsets.map(o => [shift(o.at), shift(o.at) + o.length + 2] as [number, number]),+ ].sort((a, b) => a[0] - b[0]);+ const actual = inlineCodeSpans(out);+ return actual.length === expected.length && actual.every(([s, e], i) => s === expected[i]![0] && e === expected[i]![1]) ? out : null;+}++/** Where the edit inserted a backtick, in before offsets (one before and one after each wrapped marker). */+type Inserts = number[];++function quoteSection(text: string, section: FenceSection): { text: string; fixes: FenceFix[]; inserts: Inserts } {+ const byLine = new Map<number, Mention[]>();+ for (const m of mentions(text, section)) byLine.set(m.lineStart, [...(byLine.get(m.lineStart) ?? []), m]);+ const inserts: Inserts = [];+ if (!byLine.size) return { text, fixes: [], inserts };+ let out = '';+ let from = 0;+ const fixes: FenceFix[] = [];+ for (const [lineStart, group] of byLine) {+ const lineEnd = group[0]!.lineEnd;+ const wrapped = wrapLine(text.slice(lineStart, lineEnd), group.map(m => ({ at: m.at - lineStart, length: m.length })));+ if (wrapped === null) continue;+ out += text.slice(from, lineStart) + wrapped;+ from = lineEnd;+ for (const m of group) {+ inserts.push(m.at, m.at + m.length);+ fixes.push({ fence: m.fence, section, row: null, column: null, line: m.line, class: 'quote_marker' });+ }+ }+ return { text: out + text.slice(from), fixes, inserts };+}++/** Every data row of every fence, as `kind:line:text`. */+function rowKeys(text: string, section: FenceSection): string[] {+ return extractRawRows(text, section).fences.flatMap(f => f.rows.map(r => `${f.kind}:${r.line}:${text.slice(r.start, r.end)}`)).sort();+}++/** Bytes the privacy boundary hides: every protected region, and everything from an ambiguous tail on. */+function hiddenBytes(text: string): Uint8Array {+ const hidden = new Uint8Array(text.length);+ const { regions, truncatedAt } = protectedRegions(text, PAIRS);+ for (const r of regions) hidden.fill(1, r.start, r.end);+ if (truncatedAt !== -1) hidden.fill(1, truncatedAt);+ return hidden;+}++/** The edit drops, moves or re-kinds no row, and hides at least what the bytes as read hid. */+function quoteEditHolds(before: string, after: string, inserts: Inserts, section: FenceSection): boolean {+ const rowsBefore = rowKeys(before, section), rowsAfter = rowKeys(after, section);+ if (rowsBefore.length !== rowsAfter.length || rowsBefore.some((key, i) => key !== rowsAfter[i])) return false;+ const was = hiddenBytes(before), now = hiddenBytes(after);+ const sorted = [...inserts].sort((a, b) => a - b);+ for (let p = 0, k = 0; p < before.length; p++) {+ while (k < sorted.length && sorted[k]! <= p) k++;+ if (was[p] && !now[p + k]) return false;+ }+ return true;+}++/**+ * The page with every prose-quoted marker wrapped in backticks, and one `quote_marker` fix per wrapped marker; the page+ * unchanged with no fixes when there is no mention, or when the edit fails its row or privacy proof in either section.+ */+export function quoteMarkerStep<T extends FencePage>(page: T): { page: T; fixes: FenceFix[] } {+ const texts: Record<FenceSection, string> = { body: '', timeline: '' };+ const fixes: FenceFix[] = [];+ for (const [section, text] of sectionsOf(page)) {+ const quoted = quoteSection(text, section);+ if (quoted.fixes.length && !quoteEditHolds(text, quoted.text, quoted.inserts, section)) return { page, fixes: [] };+ texts[section] = quoted.text;+ fixes.push(...quoted.fixes);+ }+ return fixes.length ? { page: withSections(page, texts), fixes } : { page, fixes };+}diff --git a/src/core/fence-repair/reasons.ts b/src/core/fence-repair/reasons.tsindex 652f80e987..06e2b62ad9 100644--- a/src/core/fence-repair/reasons.ts+++ b/src/core/fence-repair/reasons.ts@@ -64,6 +64,7 @@ const SPECS: Record<FenceReason, Omit<FenceReasonSpec, 'docs'>> = {unclosed_trailing_content: entry(tier3, 'The {fence} fence that begins at line {line} in the {section} has no end marker and lines holding a pipe follow its table, so the rules cannot tell rows from prose. The repair model classifies the tail; a prose tail closes the fence after its last row (on a world-visible page after the user approves the lines it shows). ' + REPAIR),unclosed_ambiguous_tail: entry({ ...manual, stage: 'repair' }, 'The {fence} fence that begins at line {line} in the {section} has no end marker, and the lines after its table are not plain prose (a row written without pipes, a marker mention, or a tail the repair model could not classify). Add the end marker directly after the last table row and fix the rows below it, or wrap a marker mention in backticks; gbrain does not guess where the fence ends.'),tail_exposure_approval: entry({ stage: 'screen', tier: 'deterministic', manualOnly: false, autoRetry: false }, 'The {fence} fence that begins at line {line} in the {section} has no end marker; gbrain can close it after its last table row, but the lines after the table would then be visible to readers of this world-visible page. Preview the close with `gbrain repair fences` (read-only: it prints those lines and the apply command with --expect <hash>), and run that command once the user approves.', { actor: 'user' }),+ quoted_marker: entry({ stage: 'screen', tier: 'deterministic', manualOnly: false, autoRetry: true }, 'Line {line} of the {section} quotes a {fence} fence marker in prose, so the page reads as having a repeated or unclosed fence. Wrap the mention in backticks; `gbrain repair fences` (read-only) previews exactly that edit and prints the apply command.'),marker_near_miss: entry(manual, 'Line {line} of the {section} mentions the takes begin marker but is not a fence followed by a table. Wrap the mention in backticks, or use the exact three-dash marker above a takes table.'),repeated_marker: entry(manual, 'The {section} repeats a {fence} fence marker (line {line}); a section holds at most one facts fence and one takes fence. gbrain merges the fences itself when each has a begin and an end marker, the same canonical header and nothing but table lines inside (`merge_fences`: later rows appended, exact duplicates dropped, colliding numbers renumbered). Otherwise, give the fence at line {line} both markers, the same header as the first fence, and move any other text out of it, or delete the extra marker.'),takes_in_facts: entry(manual, 'The {fence} fence in the {section} at line {line} holds a takes table. Move the rows into a takes fence (or use `takes_add`), or rewrite them as facts rows.'),diff --git a/src/core/fence-repair/repair-tiers.ts b/src/core/fence-repair/repair-tiers.tsindex dbc7662a3f..15e94a0d67 100644--- a/src/core/fence-repair/repair-tiers.ts+++ b/src/core/fence-repair/repair-tiers.ts@@ -29,6 +29,7 @@ import { extractRawRows } from './raw-rows.ts';import { scanCanonicalFences } from './refusal.ts';import { GATE_REASONS, renderFenceFix, type FenceMessageLocation } from './reasons.ts';import { residualLocation } from './tier1.ts';+import { quoteMarkerStep } from './quote-markers.ts';import { validateFenceRepair } from './validate.ts';import { callTier3, FENCE_REPAIR_PROMPT_VERSION, spliceTier3, tier3Requests, tier3TokenBudget, TIER3_REASONS, type Tier3Request, type Tier3Table } from './llm.ts';import { callTailClassifier, TAIL_PROMPT_VERSION, tailRequest, tailTokenBudget, type TailRequest } from './llm-tail.ts';@@ -92,7 +93,20 @@ export interface AnalyzeOpts {}export async function analyzeFences(engine: BrainEngine, target: FenceTarget, opts: AnalyzeOpts): Promise<FenceAnalysis> {- const page = target.page;+ const plain = await analyzePage(engine, target, target.page, opts);+ if (plain.status === 'clean' || plain.status === 'proposal') return plain;+ // #8059: a page held for a marker quoted in prose is analyzed again with the mentions wrapped in backticks. The quote edit+ // carries its own row and privacy proof (quote-markers.ts), the rest is validated against the quoted page, and only a+ // free proposal replaces the plain verdict: a page that would still need a person or the model keeps it.+ const quoted = quoteMarkerStep(target.page);+ if (!quoted.fixes.length) return plain;+ const rest = await analyzePage(engine, target, quoted.page, opts);+ if (rest.status === 'proposal') return { ...rest, fixes: [...quoted.fixes, ...rest.fixes] };+ const ctx = { ...target.ctx, ...(opts.approveTailExposure ? { approveTailExposure: true } : {}) };+ return rest.status === 'clean' && settled(quoted.page, ctx) ? { status: 'proposal', tier: 'deterministic', after: quoted.page, fixes: quoted.fixes, ctx } : plain;+}++async function analyzePage(engine: BrainEngine, target: FenceTarget, page: FencePage, opts: AnalyzeOpts): Promise<FenceAnalysis> {if (!scanCanonicalFences(page).defects.length) return { status: 'clean' };let ctx: FenceCtx = { ...target.ctx, ...(opts.approveTailExposure ? { approveTailExposure: true } : {}), ...(opts.tailProse ? { tailProse: opts.tailProse } : {}) };let base = safeNormalizeFences(page, ctx);diff --git a/src/core/fence-repair/tier1.ts b/src/core/fence-repair/tier1.tsindex 9d7720ca16..2b4cc446b1 100644--- a/src/core/fence-repair/tier1.ts+++ b/src/core/fence-repair/tier1.ts@@ -19,6 +19,7 @@ import { hasFenceText, safeNormalizeFences } from './normalize.ts';import { scanCanonicalFences, FENCE_ROWS_MAX } from './refusal.ts';import { issueLocation, type FenceMessageLocation } from './reasons.ts';import { validateFenceRepair } from './validate.ts';+import { quoteMarkerStep } from './quote-markers.ts';import type { FenceCtx, FenceFix, FenceIssue, FenceKind, FencePage, FenceReason, FenceSection, FixClass } from './types.ts';export type FenceStep<T extends FencePage> =@@ -49,6 +50,17 @@ export function pageHasFenceText(page: FencePage): boolean {}export function fenceStep<T extends FencePage>(page: T, ctx: FenceCtx, opts: { normalize: boolean }): FenceStep<T> {+ const step = plainStep(page, ctx, opts);+ if (step.status !== 'residual') return step;+ // #8059: classification only, never an edit on a write path: when wrapping the page's prose-quoted markers in backticks+ // (the fences repair kind's `quote_marker`) leaves nothing residual, the residual says so and names the first mention.+ const quoted = quoteMarkerStep(page);+ if (!quoted.fixes.length || plainStep(quoted.page, ctx, opts).status === 'residual') return step;+ const first = quoted.fixes[0]!;+ return residual([{ fence: first.fence, section: first.section, row: null, column: null, line: first.line, reason: 'quoted_marker' }]);+}++function plainStep<T extends FencePage>(page: T, ctx: FenceCtx, opts: { normalize: boolean }): FenceStep<T> {if (!pageHasFenceText(page)) return { status: 'clean' };const defects = scanCanonicalFences(page).defects;if (!defects.length) return { status: 'clean' };diff --git a/src/core/fence-repair/types.ts b/src/core/fence-repair/types.tsindex 1487fe1edf..036bf6a1c1 100644--- a/src/core/fence-repair/types.ts+++ b/src/core/fence-repair/types.ts@@ -35,12 +35,16 @@ export type FixClass =| 'kind_map'| 'holder_alias'| 'confidence_format'- | 'holder_verified';+ | 'holder_verified'+ /** #8059: a facts or takes marker quoted in prose, wrapped in backticks (repair only; never on a write path). */+ | 'quote_marker';/** Every fence reason; `FENCE_REASONS` (reasons.ts) holds one entry per code. */export type FenceReason =// Screen residual, Tier 3 (`unclosed_trailing_content`: the tail classifier, #6377).| 'header_unmapped' | 'no_header' | 'row_before_header' | 'short_row' | 'unclosed_trailing_content'+ // Screen residual, deterministic repair only (#8059: the fences repair kind wraps prose-quoted markers in backticks).+ | 'quoted_marker'// Screen residual, Tier 2 then manual.| 'holder_unresolved'// Screen residual, manual only.diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 523f8a8ca4..69fb62c3d5 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -40,6 +40,7 @@ import { ORIGIN_TWINS_AUTO_RESOLVE_KEY, originTwinsPreviewArgv, type OriginConflimport { FENCE_REASONS, type FenceMessageLocation } from '../fence-repair/reasons.ts';import type { FenceReason, FenceTier, GateLetter } from '../fence-repair/types.ts';import { FENCE_VERSION } from '../fence-repair/refusal.ts';+import { QUOTE_SCREEN_VERSION } from '../fence-repair/quote-markers.ts';import { fenceHoldFix, fenceHoldLocation, fencePreviewArgv, readFenceAutoRepair, type FenceAutoRepair, type FenceHoldLocation } from '../fence-repair/hold-fix.ts';import { contentHoldDocs, contentHoldFix } from '../content-repair/hold-fix.ts';import { classicRenameHoldFix } from '../classic-rename-holds.ts';@@ -136,6 +137,8 @@ export interface GitHoldMeta {fence?: FenceMessageLocation;/** #6188: the fence screen version that held it; an older one is re-screened by a newer gbrain. */fence_version?: number;+ /** #8059: the quoted-marker screen version that held it (`QUOTE_SCREEN_VERSION`); an older one is re-screened once, without touching the parser version. */+ quote_version?: number;/** Git-mode holds: the pinned blob, so discovery re-checks every hold with one `ls-tree`. */blob_oid?: string;/** The held bytes came from the working tree, not the pinned commit. */@@ -610,6 +613,7 @@ export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, re|| (record.code === 'managed_image_sync_unsupported' && isMultimodalEnabled())|| record.meta.recovery_version < RECOVERY_VERSION|| (record.code === 'invalid_fence' && (record.meta.fence_version ?? 0) < FENCE_VERSION)+ || (record.code === 'invalid_fence' && (record.meta.quote_version ?? 0) < QUOTE_SCREEN_VERSION)// GBRA-133: an unknown-side drift held before #7340's baseline rule (a Git edit to a page with no import record) imports// now when the page still holds its file at the baseline commit, so it is screened once more.|| (record.code === 'file_drift' && fileDriftSide(record.meta) === 'unknown' && (record.meta.drift_version ?? 0) < FILE_DRIFT_VERSION)diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.tsindex f2dcad868f..addaa43e5f 100644--- a/src/core/persistence/sync-screen.ts+++ b/src/core/persistence/sync-screen.ts@@ -24,6 +24,7 @@ import type { FenceFix } from '../fence-repair/types.ts';import { parseMarkdown, RECOVERY_VERSION, type IntendedRefusal } from '../markdown.ts';import { fenceMessage, type FenceMessageLocation } from '../fence-repair/reasons.ts';import { completeFenceLocation, FENCE_VERSION, type ReceiptFenceLocation } from '../fence-repair/refusal.ts';+import { QUOTE_SCREEN_VERSION } from '../fence-repair/quote-markers.ts';import { fenceFileLine } from '../fence-repair/hold-fix.ts';import { slugConflictHoldMessage } from '../import-file.ts';import { isImageFilePath, isMultimodalEnabled, resolveSlugForPath } from '../sync.ts';@@ -147,7 +148,7 @@ function heldEntry(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'rreturn { path: entry.path, source_path: entry.sourcePath, slug, page_id: pageId, code: refusal.code, message: refusal.message,upstream_version: content === null ? null : sha256(content),meta: { ...(refusal.reason ? { reason: refusal.reason } : {}), ...(refusal.key ? { key: refusal.key } : {}), ...(line !== undefined ? { line } : {}),- recovery_version: RECOVERY_VERSION, ...(refusal.fence ? { fence: refusal.fence, fence_version: FENCE_VERSION } : {}),+ recovery_version: RECOVERY_VERSION, ...(refusal.fence ? { fence: refusal.fence, fence_version: FENCE_VERSION, quote_version: QUOTE_SCREEN_VERSION } : {}),...(blob ? { blob_oid: blob.oid } : {}), ...(entry.working ? { working: true } : {}),...(entry.renameFrom ?? entry.renameHeld ? { rename_from: entry.renameFrom ?? entry.renameHeld } : {}) } };}diff --git a/test/fence-hold-surfaces.test.ts b/test/fence-hold-surfaces.test.tsindex 07a9ee3083..e1ef2ab700 100644--- a/test/fence-hold-surfaces.test.ts+++ b/test/fence-hold-surfaces.test.ts@@ -30,6 +30,7 @@ import { holdLine } from '../src/commands/sync-diagnostics.ts';import { deriveNext, renderAction, type Action } from '../src/core/agent-output.ts';import { fenceMessage } from '../src/core/fence-repair/reasons.ts';import { FENCE_VERSION } from '../src/core/fence-repair/refusal.ts';+import { QUOTE_SCREEN_VERSION } from '../src/core/fence-repair/quote-markers.ts';import { fenceFileLine, fenceHoldStatus, type FenceAutoRepair } from '../src/core/fence-repair/hold-fix.ts';import { parseMarkdown, RECOVERY_VERSION } from '../src/core/markdown.ts';@@ -38,7 +39,7 @@ const fenceHold = (extra: Partial<GitHoldRecord> = {}): GitHoldRecord => ({version: 1, source_id: 'notes-example', incarnation: 'inc', path: 'people/alice-example.md', source_path: 'people/alice-example.md', slug: 'people/alice-example', page_id: 12,code: 'invalid_fence', message: fenceMessage({ ...location, rows: [...location.rows], columns: [...location.columns] }), upstream_version: 'sha', observed_at: '2026-10-01T00:00:00.000Z',held_at: '2026-10-01T00:00:00.000Z', updated_at: '2026-10-01T00:00:00.000Z', run_id: 'run', mode: 'managed',- meta: { reason: 'holder_unresolved', line: 12, recovery_version: RECOVERY_VERSION, fence: { ...location, rows: [...location.rows], columns: [...location.columns] }, fence_version: FENCE_VERSION },+ meta: { reason: 'holder_unresolved', line: 12, recovery_version: RECOVERY_VERSION, fence: { ...location, rows: [...location.rows], columns: [...location.columns] }, fence_version: FENCE_VERSION, quote_version: QUOTE_SCREEN_VERSION },...extra,});const withMeta = (meta: Partial<GitHoldRecord['meta']>) => fenceHold({ meta: { ...fenceHold().meta, ...meta } });@@ -163,6 +164,7 @@ describe('structured location (D16)', () => {expect(holdRescreenDue(fenceHold(), true)).toBe(true);expect(holdRescreenDue(withMeta({ fence_version: FENCE_VERSION - 1 }), false)).toBe(true);expect(holdRescreenDue(withMeta({ fence_version: undefined }), false)).toBe(true);+ expect(holdRescreenDue(withMeta({ quote_version: undefined }), false)).toBe(true);expect(holdRescreenDue({ ...frontmatterHold(), code: 'frontmatter_slug_conflict' }, false)).toBe(true);});});diff --git a/test/fence-repair-quote-markers.test.ts b/test/fence-repair-quote-markers.test.tsnew file mode 100644index 0000000000..ac34f7d2c0--- /dev/null+++ b/test/fence-repair-quote-markers.test.ts@@ -0,0 +1,111 @@+/**+ * #8059 prose-quoted fence markers (src/core/fence-repair/quote-markers.ts) and the screen reason `quoted_marker`.+ *+ * 1. Protects: a facts or takes marker quoted in prose (text after it on its line, or a blockquote line; outside code and+ * table lines; beginning or ending no fence that holds rows) is wrapped in backticks, and only then; every fence row+ * stays put; the privacy boundary hides at least what it hid; the edit is a fixed point; the write-path screen names+ * `quoted_marker` only when the wrap alone would clear the page, and never edits it.+ * 2. Fails when: a real marker is wrapped (rows lost), an existing code span re-pairs, a wrap would show text the+ * boundary hid, or the screen keeps `repeated_marker` for a page the repair clears.+ * 3. Pure; no engine.+ */+import { describe, expect, test } from 'bun:test';+import { FACTS_FENCE_BEGIN as B, FACTS_FENCE_END as E } from '../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN as TB, TAKES_FENCE_END as TE } from '../src/core/takes-fence.ts';+import { quoteMarkerStep } from '../src/core/fence-repair/quote-markers.ts';+import { fenceStep } from '../src/core/fence-repair/tier1.ts';+import { scanCanonicalFences } from '../src/core/fence-repair/refusal.ts';+import { extractRawRows } from '../src/core/fence-repair/raw-rows.ts';+import { FENCE_REASONS } from '../src/core/fence-repair/reasons.ts';+import type { FenceCtx } from '../src/core/fence-repair/types.ts';++const tick = (m: string) => `\`${m}\``;+const HEADER = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |';+const SEP = '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|';+const row = (n: number) => `| ${n} | Acme Example claim ${n} | fact | 0.9 | private | medium | 2024-01-01 | | note | ctx |`;+const FENCE = [B, HEADER, SEP, row(1), row(2), E].join('\n');+const TAKES = [TB, '| # | claim | kind | who | weight | since | source |', '|---|---|---|---|---|---|---|', '| 1 | A synthetic take | take | brain | 0.7 | 2026-01 | chat |', TE].join('\n');+const ctx: FenceCtx = { pageVisibility: 'private' };+const page = (body: string, timeline = '') => ({ compiled_truth: body, timeline });+const rowLines = (text: string) => extractRawRows(text).fences.flatMap(f => f.rows.map(r => text.slice(r.start, r.end)));++describe('quoteMarkerStep', () => {+ test('a prose-quoted begin and end above a real fence are wrapped; the real fence and its rows stay; the page compiles', () => {+ const before = page(`We said ${B} starts a fence and ${E} ends it.\n\n${FENCE}\n`);+ expect(scanCanonicalFences(before).defects.map(d => d.reason)).toEqual(['repeated_marker']);+ const step = quoteMarkerStep(before);+ expect(step.page.compiled_truth).toBe(`We said ${tick(B)} starts a fence and ${tick(E)} ends it.\n\n${FENCE}\n`);+ expect(step.fixes).toEqual([+ { fence: 'facts', section: 'body', row: null, column: null, line: 1, class: 'quote_marker' },+ { fence: 'facts', section: 'body', row: null, column: null, line: 1, class: 'quote_marker' },+ ]);+ expect(scanCanonicalFences(step.page).defects).toEqual([]);+ expect(rowLines(step.page.compiled_truth)).toEqual([row(1), row(2)]);+ expect(quoteMarkerStep(step.page).fixes).toEqual([]);+ });++ test('a blockquote line and the timeline section are mentions; CRLF lines keep their terminators', () => {+ const step = quoteMarkerStep(page(`> ${E}\r\n> quoted\r\n\r\n${FENCE.replaceAll('\n', '\r\n')}\r\n`, `- 2026-01-01: noted that ${TB} opens takes\n`));+ expect(step.page.compiled_truth.startsWith(`> ${tick(E)}\r\n> quoted\r\n`)).toBe(true);+ expect(step.page.timeline).toBe(`- 2026-01-01: noted that ${tick(TB)} opens takes\n`);+ expect(step.fixes.map(f => [f.fence, f.section, f.line])).toEqual([['facts', 'body', 1], ['takes', 'timeline', 1]]);+ });++ test('not mentions: text only before the marker, a table line, inline code, a fenced code block, a backtick neighbour', () => {+ for (const body of [+ `Facts: ${FENCE}\n`,+ `${FENCE}\n\n| 3 | ${B} in a cell | fact |\n`,+ `Use ${tick(B)} and more.\n\n${FENCE}\n`,+ `\`\`\`md\nWe said ${B} here\n\`\`\`\n\n${FENCE}\n`,+ `x\`${B} y\n`,+ ]) expect(quoteMarkerStep(page(body)).fixes).toEqual([]);+ });++ test('a line whose existing code spans would re-pair keeps its marker; double-backtick and escaped-backtick spans are kept', () => {+ expect(quoteMarkerStep(page(`odd \` tick ${B} here\n`)).fixes).toEqual([]);+ const kept = quoteMarkerStep(page(`see \`\`a\`b\`\` and \\\` then ${E} here\n`));+ expect(kept.page.compiled_truth).toBe(`see \`\`a\`b\`\` and \\\` then ${tick(E)} here\n`);+ });++ test('a marker that begins or ends a fence holding rows is real, even with text after it: only the prose mention is wrapped', () => {+ const before = page(`${FENCE.replace(E, `${E}Next paragraph`)}\nLater: see ${B} docs.\n`);+ const step = quoteMarkerStep(before);+ expect(step.page.compiled_truth).toBe(`${FENCE.replace(E, `${E}Next paragraph`)}\nLater: see ${tick(B)} docs.\n`);+ expect(rowLines(step.page.compiled_truth)).toEqual([row(1), row(2)]);+ const realBegin = page(`${B} the table below\n${HEADER}\n${SEP}\n${row(1)}\n${E}\n`);+ expect(quoteMarkerStep(realBegin).fixes).toEqual([]);+ });++ test('a wrap that would show text the privacy boundary hid is not made (a begin followed by an end already quoted in code)', () => {+ const before = page(`Prose ${B} opens.\nMiddle line.\nThen ${tick(E)} quoted.\nTail text.\n`);+ expect(quoteMarkerStep(before)).toEqual({ page: before, fixes: [] });+ });++ test('takes markers are mentions too', () => {+ const step = quoteMarkerStep(page(`The ${TB} and ${TE} markers.\n\n${TAKES}\n`));+ expect(step.fixes.map(f => f.fence)).toEqual(['takes', 'takes']);+ expect(scanCanonicalFences(step.page).defects).toEqual([]);+ });+});++describe('the screen reason', () => {+ test('quoted_marker is a deterministic, auto-retried screen reason', () => {+ expect(FENCE_REASONS.quoted_marker).toMatchObject({ stage: 'screen', tier: 'deterministic', manualOnly: false, autoRetry: true });+ });++ test('fenceStep names quoted_marker when the wrap alone clears the page, and never edits it', () => {+ const before = page(`We said ${B} starts a fence.\n\n${FENCE}\n`);+ const step = fenceStep(before, ctx, { normalize: true });+ expect(step.status).toBe('residual');+ if (step.status !== 'residual') return;+ expect(step.issues).toEqual([{ fence: 'facts', section: 'body', row: null, column: null, line: 1, reason: 'quoted_marker' }]);+ expect(step.location).toMatchObject({ reason: 'quoted_marker', fence: 'facts', section: 'body', line: 1 });+ });++ test('fenceStep keeps the plain reason when the wrap would not clear the page', () => {+ const bad = FENCE.replace(row(2), '| 2 | Acme Example claim 2 | fact | 0.9 | sideways | medium | 2024-01-01 | | note | ctx |');+ const step = fenceStep(page(`We said ${B} starts a fence.\n\n${bad}\n`), ctx, { normalize: true });+ expect(step.status).toBe('residual');+ if (step.status === 'residual') expect(step.issues.map(i => i.reason)).not.toContain('quoted_marker');+ });+});diff --git a/test/fence-repair-reasons.test.ts b/test/fence-repair-reasons.test.tsindex d82992f08a..39c6e84245 100644--- a/test/fence-repair-reasons.test.ts+++ b/test/fence-repair-reasons.test.ts@@ -24,6 +24,8 @@ const EVAL_MANUAL: FenceReason[] = ['extra_cells', 'claim_split'];const SPEC_TIER3: FenceReason[] = ['header_unmapped', 'no_header', 'row_before_header', 'short_row', 'unclosed_trailing_content'];/** #6377: the user's hash-bound approval to close a fence ahead of trailing text on a world-visible page; nothing retries it by itself. */const APPROVAL: FenceReason[] = ['tail_exposure_approval'];+/** #8059: a marker quoted in prose; the fences repair kind wraps it in backticks with no one acting. */+const QUOTED: FenceReason[] = ['quoted_marker'];/** #6278: the owner conditions the `owner_unavailable` reasons matrix names (persistence/owner-refusal.ts); `owner_unavailable` stays the generic fallback. */const OWNER_CONDITIONS: FenceReason[] = ['host_mismatch', 'transfer_in_progress', 'clone_in_progress', 'incarnation_changed', 'local_path_missing', 'coordination_path_missing'];const SPEC_OTHERS: FenceReason[] = [@@ -38,7 +40,7 @@ const SPEC_OTHERS: FenceReason[] = [describe('FENCE_REASONS', () => {test('holds exactly the reasons the spec names (plus the documented additions)', () => {- expect([...FENCE_REASON_CODES].sort()).toEqual([...SPEC_MANUAL, ...ADDED_MANUAL, ...EVAL_MANUAL, ...SPEC_TIER3, ...APPROVAL, ...OWNER_CONDITIONS, ...SPEC_OTHERS].sort());+ expect([...FENCE_REASON_CODES].sort()).toEqual([...SPEC_MANUAL, ...ADDED_MANUAL, ...EVAL_MANUAL, ...SPEC_TIER3, ...APPROVAL, ...QUOTED, ...OWNER_CONDITIONS, ...SPEC_OTHERS].sort());});test('owner conditions match the owner_unavailable reasons matrix: host_admin acts, only the in-progress ones retry by themselves', () => {diff --git a/test/forget-strike-quoted-marker-8059.test.ts b/test/forget-strike-quoted-marker-8059.test.tsnew file mode 100644index 0000000000..b13ae5eae7--- /dev/null+++ b/test/forget-strike-quoted-marker-8059.test.ts@@ -0,0 +1,25 @@+/**+ * #8059: `strikeFenceRow` splices at the parser's own code-aware locator.+ *+ * 1. Protects: on a page whose prose quotes the facts begin marker in an inline code span above the real fence (the+ * shape the `quote_marker` repair writes), striking a row rewrites only the real fence; the prose above it stays.+ * 2. Fails when: the splice finds the begin marker by a raw indexOf, so everything from the quoted mention to the real+ * fence is replaced by the table (#8020's forget item).+ * 3. Pure.+ */+import { expect, test } from 'bun:test';+import { FACTS_FENCE_BEGIN as B, FACTS_FENCE_END as E, parseFactsFence } from '../src/core/facts-fence.ts';+import { strikeFenceRow } from '../src/core/facts/forget.ts';++const HEADER = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |';+const SEP = '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|';+const row = (n: number) => `| ${n} | Acme Example claim ${n} | fact | 0.9 | private | medium | 2024-01-01 | | note | ctx |`;++test('a row strike on a page that quotes the begin marker in code above the fence keeps the prose', () => {+ const prose = `I typed \`${B}\` into my note.\n\nA second paragraph about it.\n\n`;+ const body = `${prose}${[B, HEADER, SEP, row(1), row(2), E].join('\n')}\n`;+ const struck = strikeFenceRow(body, 2, fact => ({ ...fact, validUntil: '2026-01-01' }));+ expect(struck).not.toBeNull();+ expect(struck!.startsWith(`${prose}${B}`)).toBe(true);+ expect(parseFactsFence(struck!).facts.map(f => f.rowNum)).toEqual([1, 2]);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 2341121142..fd2ea6437a 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -441,6 +441,7 @@ test/repair-file-drift-provenance-gbra133.test.tstest/repair-frontmatter-keys-sweep-6454.test.tstest/repair-frontmatter.test.tstest/repair-ghost-database-ahead-gbra133.test.ts+test/repair-quoted-markers-8059.test.tstest/repair-receipt-compaction.test.tstest/repair-rename-identity-6729.test.tstest/retrieval-coverage-notices.test.tsdiff --git a/test/repair-quoted-markers-8059.test.ts b/test/repair-quoted-markers-8059.test.tsnew file mode 100644index 0000000000..201c547dd0--- /dev/null+++ b/test/repair-quoted-markers-8059.test.ts@@ -0,0 +1,138 @@+/**+ * #8059 end to end: the content-repair lane wraps prose-quoted fence markers, on a managed Git source and on a+ * repo-less brain, through the real `fences` kind.+ *+ * 1. Protects: a committed transcript that quotes the facts markers in prose above a real fence is held `invalid_fence`+ * with reason `quoted_marker` (not a person's `repeated_marker`), listed as repairable; `sync unblock --apply`+ * wraps the mentions in backticks through the managed write-back with a receipt, and the next sync imports the page+ * with its real fence. A hold an older gbrain screened (no `quote_version`) is screened once more, without moving the+ * parser version. On a brain with no repository, `repair content` previews the stored page as `quote_marker` and+ * `--apply --expect` rewrites it in the database; the real fence's rows land.+ * 2. Fails when: the hold stays manual, unblock refuses it, the edit drops a row or misses the receipt, or the db path+ * does not repair.+ * 3. PGLite, and PostgreSQL when DATABASE_URL is set.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readSyncStatus, unblockSync } from '../src/core/persistence/sync-status.ts';+import { holdRescreenDue, readGitHold, SYNC_IMPORT_PARSER_VERSION } from '../src/core/persistence/sync-holds.ts';+import { RECOVERY_VERSION } from '../src/core/markdown.ts';+import { FENCE_VERSION } from '../src/core/fence-repair/refusal.ts';+import { QUOTE_SCREEN_VERSION } from '../src/core/fence-repair/quote-markers.ts';+import { FACTS_FENCE_BEGIN as B, FACTS_FENCE_END as E } from '../src/core/facts-fence.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import type { RepairResult } from '../src/core/repair/core.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-8059-'));+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_FENCE_REPAIR_SCAN_MS: '60000', OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_API_KEY: undefined };+const backends = testBackends();+const engines: Array<{ kind: string; engine: BrainEngine }> = [];+const repoless: Array<{ kind: string; engine: BrainEngine }> = [];+const closers: Array<() => Promise<void>> = [];+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };+const tick = (m: string) => `\`${m}\``;+const HEADER = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |';+const SEP = '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|';+const row = (n: number) => `| ${n} | Acme Example claim ${n} | fact | 0.9 | world | medium | 2024-01-01 | | note | ctx |`;+const FENCE = [B, HEADER, SEP, row(1), row(2), E].join('\n');+const PROSE = (b: string, e: string) => `In the call we said ${b} starts a fence and ${e} ends it.\n\n`;+const md = (body: string) => `---\ntitle: Transcript\ntype: note\n---\n${body}`;++beforeAll(async () => {+ for (const into of [engines, repoless]) {+ if (backends.includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); into.push({ kind: 'pglite', engine: lite }); }+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); into.push({ kind: 'postgres', engine: pg.engine }); closers.push(pg.close); }+ }+}, 180_000);+afterAll(async () => {+ await withEnv(env, async () => { for (const { engine } of [...engines, ...repoless]) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });+ for (const close of closers) await close();+ rmSync(home, { recursive: true, force: true });+});++async function managedSource(engine: BrainEngine, files: Record<string, string>) {+ const id = `q-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);+ mkdirSync(root); git(root, 'init', '-q');+ for (const [path, body] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), body); }+ commit(root, 'fixture');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } };+}++async function cli(engine: BrainEngine, args: string[]): Promise<string> {+ const out: string[] = [];+ const log = console.log;+ console.log = (...parts: unknown[]) => { out.push(parts.join(' ')); };+ try { await runRepairCommand(engine, args); } finally { console.log = log; }+ return out.join('\n');+}++test('a transcript that quotes the markers in prose is held quoted_marker, and sync unblock --apply wraps them with a receipt', async () => withEnv(env, async () => {+ for (const { kind, engine } of engines) {+ const f = await managedSource(engine, { 'notes/plain.md': md('Plain.\n') });+ await performManagedSync(engine, f.opts);+ writeFileSync(join(f.root, 'notes/transcript.md'), md(`${PROSE(B, E)}${FENCE}\n`));+ commit(f.root, 'transcript');+ expect((await performManagedSync(engine, f.opts)).held?.map(h => h.path), kind).toEqual(['notes/transcript.md']);+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [f.id]);+ const hold = await readGitHold(engine, f.id, source!.incarnation, 'notes/transcript.md');+ expect(hold?.meta.fence?.reason, kind).toBe('quoted_marker');+ expect(hold?.meta.quote_version, kind).toBe(QUOTE_SCREEN_VERSION);+ expect((await readSyncStatus(engine, f.id)).holds.find(h => h.path === 'notes/transcript.md')?.needs_human, kind).toBe(false);++ const applied = await unblockSync(engine, f.id, { apply: true, noLlm: true });+ expect(applied.refused, kind).toEqual([]);+ expect(applied.applied.find(entry => entry.path === 'notes/transcript.md'), kind).toMatchObject({ action: 'repair',+ repair: { kind: 'fences', outcome: 'repaired', tier: 'deterministic', receipt: { mode: 'managed', path: 'notes/transcript.md', classes: 'quote_marker', hold_cleared: true } } });+ expect(readFileSync(join(f.root, 'notes/transcript.md'), 'utf8'), kind).toBe(md(`${PROSE(tick(B), tick(E))}${FENCE}\n`));++ await performManagedSync(engine, f.opts);+ expect(await readGitHold(engine, f.id, source!.incarnation, 'notes/transcript.md'), kind).toBeNull();+ const page = await engine.getPage('notes/transcript', { sourceId: f.id });+ expect(page?.compiled_truth, kind).toContain(tick(B));+ const facts = await engine.executeRaw<{ row_num: number }>('SELECT row_num FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY row_num', [f.id, 'notes/transcript']);+ expect(facts.map(r => Number(r.row_num)), kind).toEqual([1, 2]);+ }+}), 240_000);++test('an invalid_fence hold an older gbrain screened is screened once more, and the parser version does not move', () => {+ const meta = { recovery_version: RECOVERY_VERSION, fence_version: FENCE_VERSION };+ expect(holdRescreenDue({ code: 'invalid_fence', meta }, false)).toBe(true);+ expect(holdRescreenDue({ code: 'invalid_fence', meta: { ...meta, quote_version: QUOTE_SCREEN_VERSION } }, false)).toBe(false);+ expect(SYNC_IMPORT_PARSER_VERSION).toBe(`import=1;frontmatter=${RECOVERY_VERSION};fence=${FENCE_VERSION}`);+});++test('a brain with no repository: repair content previews the deterministic repair of the stored page and --apply --expect rewrites it in the database', async () => withEnv(env, async () => {+ for (const { kind, engine } of repoless) {+ const sourceId = `d-${randomUUID().replace(/-/g, '').slice(0, 20)}`;+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES($1,$1,'{}')", [sourceId]);+ await engine.putPage('notes/db-transcript', { type: 'note', title: 'Transcript', compiled_truth: `${PROSE(B, E)}${FENCE}\n`, timeline: '' }, { sourceId });+ const preview = JSON.parse(await cli(engine, ['content', '--source', sourceId, '--json'])) as { preview_hashes: Record<string, string | null>; results: RepairResult[] };+ const fences = preview.results.find(r => r.kind === 'fences')!;+ expect(fences.listing?.map(entry => [entry.item, entry.class]), kind).toEqual([[`${sourceId}:notes/db-transcript`, 'deterministic']]);+ const hashes = [preview.preview_hashes.fences, preview.preview_hashes['slug-conflicts']].join(',');+ const applied = JSON.parse(await cli(engine, ['content', '--source', sourceId, '--apply', '--expect', hashes, '--json'])) as { results: RepairResult[] };+ expect(applied.results.find(r => r.kind === 'fences'), kind).toMatchObject({ mode: 'apply', applied: 1, outcomes: { repaired: 1 } });+ expect(applied.results.find(r => r.kind === 'fences')!.outcome_items![0], kind).toMatchObject({ outcome: 'repaired', detail: { tier: 'deterministic', classes: 'quote_marker', mode: 'db' } });+ const page = await engine.getPage('notes/db-transcript', { sourceId });+ expect(page?.compiled_truth.trimEnd(), kind).toBe(`${PROSE(tick(B), tick(E))}${FENCE}`);+ const facts = await engine.executeRaw<{ row_num: number }>('SELECT row_num FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY row_num', [sourceId, 'notes/db-transcript']);+ expect(facts.map(r => Number(r.row_num)), kind).toEqual([1, 2]);+ }+}), 240_000);