Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(fences): typed invalid_fence refusals at every fence refusal site (#6188)
garrytan2e348b3cbadc
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 036b05750c..4643e946af 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -16,6 +16,7 @@ Under contract v1 an `error` value never changes. Where a surface sends a legacy| `error` (frozen) | `code` (canonical) | Meaning ||---|---|---|| `permission_denied` | `insufficient_scope` | The connection lacks the OAuth scope the operation requires. |+| `invalid_params` | `invalid_fence` | 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. || `invalid_params` | `not_found` | The requested resource does not exist or is not visible to this caller. || `page_identity_changed` | `page_not_found` | No page with that slug exists in the selected source. || `permission_denied` | `trusted_local_only` | The operation runs only from the trusted local CLI on the brain host; no MCP connection can call it. |@@ -1285,6 +1286,18 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| Invalid connector text. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### invalid_fence++<a id="invalid_fence"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| 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. | Fix the fence the message names (fence, section and rows; the reason says what is wrong), then write the page again or commit the file and sync. | agent | `repeat the read that failed` | 1 | no |++Reasons: `header_unmapped`, `no_header`, `row_before_header`, `short_row`, `extra_cells`, `holder_unresolved`, `missing_begin`, `split_rows`, `unclosed_trailing_content`, `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_disabled`, `budget_exhausted`, `no_pricing`, `ledger_unavailable`, `owner_unavailable`, `owner_cli_required`, `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)+### invalid_frontmatter<a id="invalid_frontmatter"></a>diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex c50ca99842..d40ecdf45e 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -153,6 +153,71 @@ with each file and fix the ones that need no guessing."*| <a id="sync_parser_regression"></a>`sync_parser_regression` | Sync stopped without advancing because it would hold a file whose exact bytes imported before (default `sync.parser_regression=stop`). This is a gbrain bug, not a content problem. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then `gbrain sync --source <source> --no-pull --retry-failed`. To keep syncing meanwhile, `gbrain config set sync.parser_regression hold` (ask the user). || <a id="changed_since_preview"></a>`changed_since_preview` | A `gbrain repair frontmatter --apply` found a file, its proposed change or its page different from what the preview showed, so that file was not written. | Preview again, show the user the new diff and approve its new hash. |+<a id="invalid_fence"></a>+### Fence holds (`invalid_fence`)++A page's facts and takes fences are its structured rows. A coordinated write+(managed sync, managed `gbrain import`, `put_page` on a managed brain, managed+file repair) refuses a fence it cannot import without dropping or guessing+rows: code `invalid_fence`, wire `error` `invalid_params` (`take_row_collision`+for a stored-row collision). During managed sync the file is **held** instead+and the rest of the source syncs. The message reads+`Fence <reason>: in the <facts|takes> fence (<body|timeline>), row(s) N, column(s) C, at line L.`+(the parts that apply; the line counts within the section), then the fix. It+names fence, section, row numbers, column names and lines only, never a claim,+holder or cell. Holds carry the same location as+`fence: { reason, fence, section, rows, columns, line }`; a failed receipt+keeps it in `write_error_detail.fence` (row numbers stay on the brain host).++Legacy (unmanaged) sync, `importFromFile` and legacy `put_page` still import+such a page as before (bad rows skipped) and never hold it. Two documented+exceptions keep blocking with the typed refusal instead of holding:+`sync.holds=fail`, and company-brain sources, which never hold and never+rewrite repository files (fix the fence in the repository and commit).++**Say to your agent:** *"Sync held a page because of its facts table. Show me+which rows are wrong and fix them."*++Fix: read the page (`gbrain get --source <source> -- <slug>`), edit only the+named fence in the file (never the frontmatter), commit, then+`gbrain sync --source <source> --no-pull`. `gbrain sources status <source>`+lists every fence hold with its location. To add rows without hand-editing a+table, use `remember` (facts) or `takes_add` (takes).++| `invalid_fence` reason | What it means | Recovery |+| --- | --- | --- |+| <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. | Keep one begin and one end marker per fence in that section, with every row in one table. |+| <a id="fence-missing_begin"></a>`missing_begin` | An end marker has no begin marker before it. | Add the begin marker above the table, or delete the stray end marker. |+| <a id="fence-marker_near_miss"></a>`marker_near_miss` | A takes marker uses the two-dash form (`<!-- gbrain:takes:begin -->`) instead of the three-dash marker, or a line mentions it outside a fence. | Use the exact three-dash markers around the takes table, or wrap a mere mention in backticks. |+| <a id="fence-unparseable"></a>`unparseable` | The fence does not parse cleanly: most often it has no end marker, or a row number is not a positive whole number (`column #`). | Add the end marker directly after the last table row, or fix the named row number. |+| <a id="fence-no_header"></a>`no_header` | The fence has table rows but no header row naming `claim` and `kind`. | Add the canonical header (below) as the first table line. |+| <a id="fence-row_before_header"></a>`row_before_header` | Rows sit above the header row. | Move them below the header. |+| <a id="fence-short_row"></a>`short_row` | A row has too few cells, so its columns are ambiguous. | Add the missing cells so every column lines up. |+| <a id="fence-extra_cells"></a>`extra_cells` | A row has more cells than the header, often an unescaped `\|` in a cell. | Escape the pipe as `\|` or remove the extra cell. |+| <a id="fence-enum_unmapped"></a>`enum_unmapped` | A facts `kind`, `visibility` or `notability` cell holds a value outside the allowed list (the message names the column and the allowed values). | Use one of the allowed values. |+| <a id="fence-takes_kind_unsupported"></a>`takes_kind_unsupported` | A takes `kind` is not fact, take, bet or hunch. gbrain never chooses a takes kind for you. | Use one of the four kinds. |+| <a id="fence-confidence_out_of_range"></a>`confidence_out_of_range` | A facts `confidence` is not a number from 0 to 1. | Write it as a decimal such as 0.8. |+| <a id="fence-claim_value_invalid"></a>`claim_value_invalid` | A facts `claim_value` is not a number. | Write a number (1,234 separators and a k/M/B suffix are allowed) or leave it empty. |+| <a id="fence-weight_missing"></a>`weight_missing` | A takes `weight` is missing or not a number. Takes have no default weight. | Add a weight from 0 to 1. |+| <a id="fence-holder_unresolved"></a>`holder_unresolved` | A takes `who` cell is not `world`, `brain`, `people/<slug>` or `companies/<slug>`. | Write one of those forms. |+| <a id="fence-row_collision"></a>`row_collision` | Two rows of the same fence kind share a row number, in one fence or across the body and timeline (`rows` lists the numbers). | Give one row a new number above every number used on the page. |+| <a id="fence-quoted_fence_rows"></a>`quoted_fence_rows` | A fence sits inside a code block or inline code span, so readers treat it as an example and importing would remove the stored rows it holds. | Move the fence out of the code, or delete the fence to remove its rows. |+| <a id="fence-stored_row_collision"></a>`stored_row_collision` | A new takes row's number already names a different stored take that is not in the page's fence (wire `take_row_collision`). | Renumber the new row, or add the stored take back to the fence. |+| <a id="fence-withdrawn_claim_in_malformed_fence"></a>`withdrawn_claim_in_malformed_fence` | A facts fence that does not parse holds a claim the user withdrew, so gbrain cannot tell whether the row should stay withdrawn. | Repair the fence so it parses; the withdrawn row then stays withdrawn. |+| <a id="fence-prepare_time"></a>`prepare_time` | Hold only: the file passed the content screen, but its fence was refused while it was prepared against the stored page (a stored-row collision, a withdrawn claim, rows quoted in code). `fence.reason` names which. Managed sync holds it in the same run instead of blocking. | Fix it as its `fence.reason` says. After a database-side fix (for example removing the conflicting take), `gbrain sources retry-held <source>` re-checks the file. |++Fence format. Markers are `<!--- gbrain:facts:begin -->` / `<!--- gbrain:facts:end -->`+and `<!--- gbrain:takes:begin -->` / `<!--- gbrain:takes:end -->` (three dashes).+The first table row is a header naming `claim` and `kind`.++- Facts rows: `| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |` (10 cells; 9 when the trailing context is empty; 14 with `claim_metric`, `claim_value`, `claim_unit`, `claim_period`). `kind` is event, preference, commitment, belief, fact or idea; `visibility` private or world; `notability` high, medium or low; `confidence` a number from 0 to 1.+- Takes rows: `| # | claim | kind | who | weight | since | source |` (7 cells; 6 without source; 13 with `resolved`, `quality`, `evidence`, `value`, `unit`, `by`). `kind` is fact, take, bet or hunch; `who` is world, brain, `people/<slug>` or `companies/<slug>`; `weight` a number.+- Row numbers are positive whole numbers, unique per fence kind across the whole page.++A managed source a fence refusal blocked before this release recovers on its+next sync with no command: the file is held and the rest imports+(`gbrain sync --source <source> --no-pull` does it now).+A source that a gbrain older than v0.60.47.0 blocked on one of these refusalsrecovers on its next sync (scheduled or manual) with no ledger surgery: the blocked request isconverted in place and reported as `converted_from_failed`. To do it now rundiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex a758f8f959..778190dbaa 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -13,6 +13,7 @@* `docs/guides/error-codes.md#<code>`.*/import type { Action, Actor, Effect, ErrorClass } from './agent-output.ts';+import { FENCE_REASON_CODES } from './fence-repair/reasons.ts';export interface CodeEntry {class: ErrorClass;@@ -194,6 +195,7 @@ export const CODES = {invalid_acknowledgment: { class: 'caller', summary: "The shared-skills delivery acknowledgment does not match a batch issued to this enrollment.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },invalid_client: { class: 'caller', summary: "Google connect credential error: invalid client.", docs: 'docs/guides/google-connect.md#troubleshooting' },invalid_connector_text: { class: 'caller', summary: "Invalid connector text." },+ invalid_fence: { class: 'caller', summary: "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.", why: "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.", reasons: FENCE_REASON_CODES, legacy_error: 'invalid_params', docs: 'docs/guides/write-refusals.md#invalid_fence', suggestion: 'Fix the fence the message names (fence, section and rows; the reason says what is wrong), then write the page again or commit the file and sync.' },invalid_frontmatter: { class: 'caller', summary: "The file's YAML frontmatter cannot be read without guessing, so it was not imported.", why: "gbrain imports frontmatter it can read exactly (quoting an unquoted value at most). Guessing could store a wrong title, merge a duplicate, or read a protected key such as `visibility` as a broader value.", reasons: ['yaml_parse', 'needs_interpretation', 'ambiguous_identity_key', 'ambiguous_protected_key'], suggestion: 'Fix the named line in the file (one line per key, the whole value quoted), then commit and sync or import again.' },invalid_grant_clock_skew: { class: 'caller', summary: "Google connect credential error: invalid grant clock skew.", docs: 'docs/guides/google-connect.md#troubleshooting' },invalid_grant_revoked: { class: 'caller', summary: "Google connect credential error: invalid grant revoked.", docs: 'docs/guides/google-connect.md#troubleshooting' },diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.tsindex 3976e66947..79152161d0 100644--- a/src/core/facts/withdrawal.ts+++ b/src/core/facts/withdrawal.ts@@ -1,6 +1,7 @@import type { BrainEngine } from '../engine.ts';import { renderFactsTable, type ParsedFact } from '../facts-fence.ts';import { OperationError } from '../ops/contract.ts';+import { fenceOperationError } from '../fence-repair/refusal.ts';import { withdrawnFact, withdrawalFenceBlocks } from './withdrawal-overlay.ts';import { ambiguousFenceClaims, discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';@@ -162,8 +163,9 @@ export async function assertPreparedFactWithdrawals(engine: BrainEngine, sourceI'Read the current page revision, then submit the updated import with a new request_id.');}if (blocked) {- throw new OperationError('invalid_params', 'A malformed fact fence contains a withdrawn claim.',- 'Repair the matching fence row, then retry the import.');+ // Typed invalid_fence, wire invalid_params (E6): a managed sync holds this file instead of blocking.+ const section = await ambiguousFenceMatchesWithdrawal(engine, sourceId, [body], subject ?? null) ? 'body' : 'timeline';+ throw fenceOperationError({ reason: 'withdrawn_claim_in_malformed_fence', fence: 'facts', section, rows: [], columns: [], line: null }, subject, sourceId);}}diff --git a/src/core/fence-repair/refusal.ts b/src/core/fence-repair/refusal.tsnew file mode 100644index 0000000000..d8ec1710f1--- /dev/null+++ b/src/core/fence-repair/refusal.ts@@ -0,0 +1,287 @@+/**+ * #6188: the one fence check every coordinated writer shares. `scanCanonicalFences`+ * decides what the canonical projection refuses (a repeated marker outside code,+ * any strict-parser warning, a row number used twice on the page); the content+ * screen (`fences: 'coordinated'`) and `compileCanonicalProjections` both call it,+ * so a file is held at the screen exactly when preparation would refuse it.+ *+ * The decision comes from the strict parsers; the location (reason, rows,+ * columns, section line) comes from the raw-row view (`raw-rows.ts`), never from+ * parser warning strings, which embed row text. Messages are `fenceMessage`+ * (`reasons.ts`): fence, section, row numbers, column names and lines only, so+ * receipts, holds and logs may keep them. A stored receipt's message, or the+ * versioned `error_detail.fence` that survives receipt compaction, is read back+ * into the same location by `fenceReceiptLocation`.+ */+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, type ParsedFact } from '../facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence, type ParsedTake } from '../takes-fence.ts';+import { codeEndAt, indexOfOutsideCode, scanMarkdownCode, type MarkdownCodeMap } from '../fence-scan.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { FENCE_REASONS, fenceMessage, issueLocation, renderFenceFix, type FenceMessageLocation } from './reasons.ts';+import { extractRawRows, primaryFence, rowNumOf, type RawSection } from './raw-rows.ts';+import { ALLOWED, cellValid } from './schema.ts';+import type { FenceIssue, FenceKind, FenceReason, FenceSection } from './types.ts';++/** Bumped when the fence screen changes what it refuses; an older `invalid_fence` hold is re-screened. */+export const FENCE_VERSION = 1;+/** Row numbers a location carries at most. */+export const FENCE_ROWS_MAX = 20;++const MARKERS: ReadonlyArray<readonly [FenceKind, string]> = [['facts', FACTS_FENCE_BEGIN], ['facts', FACTS_FENCE_END], ['takes', TAKES_FENCE_BEGIN], ['takes', TAKES_FENCE_END]];+const KINDS: readonly FenceKind[] = ['facts', 'takes'];+const SECTIONS: readonly FenceSection[] = ['body', 'timeline'];++/** The `ContentRefusal` the coordinated screen returns. */+export interface FenceRefusal { code: 'invalid_fence'; reason: FenceReason; message: string; fence: FenceMessageLocation }++/** A location read back from a stored receipt: an older gbrain's message never named the fence or section. */+export type ReceiptFenceLocation = Omit<FenceMessageLocation, 'fence' | 'section'> & { fence?: FenceKind; section?: FenceSection };++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;+}++function quotesMarker(body: string, code: MarkdownCodeMap): boolean {+ for (const [, marker] of 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;+}++const at = (reason: FenceReason, fence: FenceKind, section: FenceSection, line: number | null, rows: number[] = [], columns: string[] = []): FenceMessageLocation =>+ ({ reason, fence, section, rows: rows.slice(0, FENCE_ROWS_MAX), columns, line });++/** The column a data row is refused for, in the strict parser's check order, and the reason it carries. */+const CELL_CHECKS: Record<FenceKind, ReadonlyArray<readonly [column: string, reason: FenceReason]>> = {+ facts: [['kind', 'enum_unmapped'], ['visibility', 'enum_unmapped'], ['notability', 'enum_unmapped'], ['confidence', 'confidence_out_of_range'], ['claim_value', 'claim_value_invalid']],+ takes: [['kind', 'takes_kind_unsupported'], ['weight', 'weight_missing']],+};++/**+ * Location-only issues of one fence kind in one section, from the raw-row view:+ * marker problems, header and row-shape problems, and per data row the first+ * cell the strict parser refuses (or a holder it warns about).+ */+function rawIssues(raw: RawSection, fence: FenceKind): FenceIssue[] {+ const primary = primaryFence(raw, fence);+ const issues = [...raw.issues.filter(issue => issue.fence === fence), ...(primary?.issues.filter(issue => issue.reason !== 'repeated_marker') ?? [])];+ if (!primary) return issues;+ const fenceIssue = (reason: FenceReason, line: number): FenceIssue => ({ fence, section: raw.section, row: null, column: null, line, reason });+ // The strict parser reads no row of a fence whose markers it does not pair, so the marker is the problem to name.+ const nearMiss = primary.begin.nearMiss ? primary.begin : primary.end?.nearMiss ? primary.end : null;+ if (nearMiss) return [fenceIssue('marker_near_miss', nearMiss.line), ...issues];+ if (!primary.end) return [fenceIssue('unparseable', primary.begin.line), ...issues];+ const seen = new Set<number>();+ for (const row of primary.rows) {+ if (row.beforeHeader || row.shape !== 'ok') continue;+ const issue = (reason: FenceReason, column: string | null, rowNum: number | null): FenceIssue => ({ fence, section: raw.section, row: rowNum, column, line: row.line, reason,+ ...(column && ALLOWED[fence][column] && (reason === 'enum_unmapped' || reason === 'takes_kind_unsupported') ? { allowed: ALLOWED[fence][column] } : {}) });+ const rowNum = rowNumOf(primary, row);+ if (rowNum === null) { issues.push(issue('unparseable', '#', null)); continue; }+ if (seen.has(rowNum)) { issues.push(issue('row_collision', null, rowNum)); continue; }+ seen.add(rowNum);+ const failed = CELL_CHECKS[fence].find(([column]) => !cellValid(fence, column, row.byColumn.get(column)?.text ?? ''));+ if (failed) { issues.push(issue(failed[1], failed[0], rowNum)); continue; }+ if (fence === 'takes' && !cellValid('takes', 'who', row.byColumn.get('who')?.text ?? '')) issues.push(issue('holder_unresolved', 'who', rowNum));+ }+ return issues;+}++/**+ * The reasons a strict-parser warning can be located as, read from its code and+ * fixed wording only (warning strings embed row text, which is never copied).+ */+function warningReasons(warning: string): readonly FenceReason[] {+ const split = warning.indexOf(': ');+ const code = split === -1 ? warning : warning.slice(0, split);+ const rest = split === -1 ? '' : warning.slice(split + 2);+ if (/_FENCE_UNBALANCED$/.test(code)) return ['missing_begin', 'marker_near_miss', 'unparseable'];+ if (code === 'TAKES_FENCE_NEAR_MISS') return ['marker_near_miss'];+ if (/_ROW_NUM_COLLISION$/.test(code)) return ['row_collision'];+ if (code === 'TAKES_HOLDER_INVALID') return ['holder_unresolved'];+ if (rest.startsWith('row before header')) return ['row_before_header'];+ if (rest.startsWith('pipe-rows present but no recognizable header')) return ['no_header'];+ if (rest.startsWith('only ')) return ['short_row'];+ if (rest.startsWith('unknown kind')) return ['enum_unmapped', 'takes_kind_unsupported'];+ if (rest.startsWith('unknown visibility') || rest.startsWith('unknown notability')) return ['enum_unmapped'];+ if (rest.startsWith('non-numeric confidence') || rest.startsWith('confidence ')) return ['confidence_out_of_range'];+ if (rest.startsWith('non-numeric claim_value')) return ['claim_value_invalid'];+ if (rest.startsWith('non-numeric weight')) return ['weight_missing'];+ return ['unparseable'];+}++/** The refusal location for a fence the strict parser warns about: its first raw issue a warning accounts for, with every row of that reason. */+function warningLocation(raw: RawSection, fence: FenceKind, section: FenceSection, warnings: string[]): FenceMessageLocation {+ const expected = new Set(warnings.flatMap(warningReasons));+ const issues = rawIssues(raw, fence).filter(issue => expected.has(issue.reason));+ const first = issues[0];+ if (first) {+ const rows = [...new Set(issues.filter(issue => issue.reason === first.reason && issue.row !== null).map(issue => issue.row!))];+ return { ...issueLocation(first), rows: rows.slice(0, FENCE_ROWS_MAX) };+ }+ // The raw view found nothing to name: say which fence, and the duplicated numbers the warnings report as integers.+ const duplicates = [...new Set(warnings.flatMap(w => { const n = /^(?:FACTS|TAKES)_ROW_NUM_COLLISION: duplicate row_num (\d+)$/.exec(w)?.[1]; return n ? [Number(n)] : []; }))];+ return at(duplicates.length === warnings.length ? 'row_collision' : 'unparseable', fence, section, primaryFence(raw, fence)?.begin.line ?? null, duplicates);+}++export interface CanonicalFenceScan {+ /** In the order the projection refuses them: repeated markers, parse problems, then page-wide row collisions. */+ defects: FenceMessageLocation[];+ facts: ParsedFact[];+ takes: ParsedTake[];+ /** Some fence marker sits in markdown code (a quoted fence holds rows readers never see). */+ quoting: boolean;+ /** The section each parsed row came from, for locating a later stored-row refusal. */+ sections: { facts: Map<number, FenceSection>; takes: Map<number, FenceSection> };+}++/** Parse both canonical sections once and list every reason the projection would refuse them. */+export function scanCanonicalFences(page: { compiled_truth: string; timeline?: string | null }): CanonicalFenceScan {+ const fields: Array<[FenceSection, string]> = [['body', page.compiled_truth ?? ''], ['timeline', page.timeline ?? '']];+ const empty: CanonicalFenceScan = { defects: [], facts: [], takes: [], quoting: false, sections: { facts: new Map(), takes: new Map() } };+ // No marker text at all: nothing to parse or refuse (the parsers return nothing either).+ if (!fields.some(([, field]) => field.includes('gbrain:facts:') || field.includes('gbrain:takes:'))) return empty;+ const raws = new Map<FenceSection, RawSection>();+ const rawOf = (section: FenceSection, field: string) => raws.get(section) ?? raws.set(section, extractRawRows(field, section)).get(section)!;+ const defects: FenceMessageLocation[] = [];+ let quoting = false;+ for (const [section, field] of fields) {+ if (!MARKERS.some(([, marker]) => field.includes(marker))) continue;+ // One code scan per section serves every marker check; an example quoted in code is not a second fence.+ const code = scanMarkdownCode(field);+ for (const fence of KINDS) {+ if (!MARKERS.some(([kind, marker]) => kind === fence && repeatsOutsideCode(field, marker, code))) continue;+ const repeat = primaryFence(rawOf(section, field), fence)?.issues.find(issue => issue.reason === 'repeated_marker');+ defects.push(at('repeated_marker', fence, section, repeat?.line ?? null));+ }+ quoting ||= quotesMarker(field, code);+ }+ const parsed = fields.map(([section, field]) => ({ section, field, facts: parseFactsFence(field), takes: parseTakesFence(field) }));+ for (const { section, field, facts, takes } of parsed) {+ for (const [fence, warnings] of [['facts', facts.warnings], ['takes', takes.warnings]] as const) {+ if (warnings.length) defects.push(warningLocation(rawOf(section, field), fence, section, warnings));+ }+ }+ const sections = { facts: new Map<number, FenceSection>(), takes: new Map<number, FenceSection>() };+ for (const fence of KINDS) {+ const duplicates: number[] = [];+ for (const { section, facts, takes } of parsed) {+ for (const row of fence === 'facts' ? facts.facts : takes.takes) {+ if (sections[fence].has(row.rowNum)) duplicates.push(row.rowNum); else sections[fence].set(row.rowNum, section);+ }+ }+ if (duplicates.length) defects.push(at('row_collision', fence, 'timeline', null, [...new Set(duplicates)]));+ }+ return { defects, facts: parsed.flatMap(p => p.facts.facts), takes: parsed.flatMap(p => p.takes.takes), quoting, sections };+}++export function fenceRefusal(location: FenceMessageLocation): FenceRefusal {+ return { code: 'invalid_fence', reason: location.reason, message: fenceMessage(location), fence: location };+}++/**+ * A fence location as prose, in `fenceMessage`'s order: "the takes fence (body), row 2, column who, at line 6"+ * ("a facts or takes fence" when an older receipt never named it).+ */+export function fenceWhere(location: Partial<Pick<ReceiptFenceLocation, 'fence' | 'section' | 'rows' | 'columns' | 'line'>> | undefined): string {+ if (!location?.fence) return 'a facts or takes fence';+ const rows = location.rows ?? [], columns = location.columns ?? [];+ return [`the ${location.fence} fence${location.section ? ` (${location.section})` : ''}`,+ ...(rows.length ? [`${rows.length > 1 ? 'rows' : 'row'} ${rows.join(', ')}`] : []),+ ...(columns.length ? [`${columns.length > 1 ? 'columns' : 'column'} ${columns.join(', ')}`] : []),+ ...(location.line != null ? [`at line ${location.line}`] : [])].join(', ');+}++/** The fix sentence for a location: the reason's template when fence and section are known. */+export function fenceFixText(location: ReceiptFenceLocation): string {+ return location.fence && location.section ? renderFenceFix(location as FenceMessageLocation) : `Fix ${fenceWhere(location)} on this page.`;+}++const MESSAGE = /^Fence ([a-z_]{1,60}): in the (facts|takes) fence \((body|timeline)\)(?:, rows? (\d{1,9}(?:, \d{1,9}){0,49}))?(?:, columns? ([#a-z_]{1,40}(?:, [#a-z_]{1,40}){0,20}))?(?:, at line (\d{1,9}))?\. /;++/** The location a `fenceMessage` names, or null for any other message. */+export function parseFenceMessage(message: string | null | undefined): FenceMessageLocation | null {+ const match = typeof message === 'string' ? MESSAGE.exec(message) : null;+ if (!match || !(match[1]! in FENCE_REASONS)) return null;+ return { reason: match[1] as FenceReason, fence: match[2] as FenceKind, section: match[3] as FenceSection,+ rows: match[4] ? match[4].split(', ').map(Number).slice(0, FENCE_ROWS_MAX) : [], columns: match[5] ? match[5].split(', ') : [],+ line: match[6] ? Number(match[6]) : null };+}++/** The exact messages older gbrain versions stored for the same fence refusals; they named no section. */+const LEGACY_MESSAGES: ReadonlyArray<readonly [code: string, pattern: RegExp, reason: FenceReason, fence?: FenceKind]> = [+ ['invalid_params', /^Each canonical body section must contain at most one facts fence and one takes fence\.$/, 'repeated_marker'],+ ['invalid_params', /^A canonical facts or takes fence cannot be parsed losslessly\.$/, 'unparseable'],+ ['invalid_params', /^Canonical row numbers must be unique across the entire page\.$/, 'row_collision'],+ ['invalid_params', /^A takes or facts fence sits inside markdown code, so this write would remove the rows it holds\.$/, 'quoted_fence_rows'],+ ['invalid_params', /^A malformed fact fence contains a withdrawn claim\.$/, 'withdrawn_claim_in_malformed_fence', 'facts'],+ ['take_row_collision', /^A takes fence row number is already used by a different take that is not in this page's canonical fence\.$/, 'stored_row_collision', 'takes'],+];++/** The wire codes a fence refusal is stored under: `invalid_params` (E3) and `take_row_collision` for stored-row collisions. */+const FENCE_WIRE_CODES = new Set(['invalid_params', 'take_row_collision', 'invalid_fence']);++/** The location in a stored receipt's code and message (current grammar or a legacy message), or null. */+export function fenceLocationFromMessage(code: string | null | undefined, message: string | null | undefined): ReceiptFenceLocation | null {+ if (!code || !FENCE_WIRE_CODES.has(code)) return null;+ const parsed = parseFenceMessage(message);+ if (parsed) return parsed;+ const legacy = LEGACY_MESSAGES.find(([legacyCode, pattern]) => legacyCode === code && pattern.test(message ?? ''));+ return legacy ? { reason: legacy[2], ...(legacy[3] ? { fence: legacy[3] } : {}), rows: [], columns: [], line: null } : null;+}++export const FENCE_DETAIL_VERSION = 1;+/** The bounded, versioned `error_detail` a fence refusal stores; it outlives receipt compaction (which drops the message). */+export interface FenceFailureDetail { origin: 'fence'; fence: FenceMessageLocation & { version: typeof FENCE_DETAIL_VERSION } }++/** The durable detail of a typed fence refusal, or undefined for any other error. */+export function fenceFailureDetail(error: Pick<OperationError, 'canonicalCode' | 'message'>): FenceFailureDetail | undefined {+ if (error.canonicalCode !== 'invalid_fence') return undefined;+ const location = parseFenceMessage(error.message);+ return location ? { origin: 'fence', fence: { version: FENCE_DETAIL_VERSION, ...location } } : undefined;+}++/** The location a stored `error_detail` carries, validated field by field, or null. */+export function fenceLocationFromDetail(detail: unknown): FenceMessageLocation | null {+ if (!detail || typeof detail !== 'object' || (detail as { origin?: unknown }).origin !== 'fence') return null;+ const fence = (detail as { fence?: Record<string, unknown> }).fence;+ if (!fence || fence.version !== FENCE_DETAIL_VERSION || typeof fence.reason !== 'string' || !(fence.reason in FENCE_REASONS)) return null;+ if (!KINDS.includes(fence.fence as FenceKind) || !SECTIONS.includes(fence.section as FenceSection)) return null;+ const rows = Array.isArray(fence.rows) ? fence.rows.filter((n): n is number => Number.isInteger(n) && (n as number) > 0).slice(0, FENCE_ROWS_MAX) : [];+ const columns = Array.isArray(fence.columns) ? fence.columns.filter((c): c is string => typeof c === 'string' && /^[#a-z_]{1,40}$/.test(c)).slice(0, 20) : [];+ return { reason: fence.reason as FenceReason, fence: fence.fence as FenceKind, section: fence.section as FenceSection, rows, columns,+ line: Number.isInteger(fence.line) && (fence.line as number) > 0 ? fence.line as number : null };+}++/** The fence location of a failed write receipt: its durable detail first, then its message. */+export function fenceReceiptLocation(row: { error_code?: string | null; error_message?: string | null; error_detail?: unknown }): ReceiptFenceLocation | null {+ return fenceLocationFromDetail(row.error_detail) ?? fenceLocationFromMessage(row.error_code, row.error_message);+}++/**+ * A receipt location completed from the bytes it refused: an older gbrain's+ * message named no section (and for some reasons no fence), so take the first+ * section that holds a fence of that kind, else the body.+ */+export function completeFenceLocation(location: ReceiptFenceLocation, page: { compiled_truth: string; timeline?: string | null }): FenceMessageLocation {+ if (location.fence && location.section) return location as FenceMessageLocation;+ const fields: Array<[FenceSection, string]> = [['body', page.compiled_truth ?? ''], ['timeline', page.timeline ?? '']];+ const has = (kind: FenceKind, field: string) => field.includes(kind === 'facts' ? 'gbrain:facts:' : 'gbrain:takes:');+ const fence = location.fence ?? KINDS.find(kind => fields.some(([, field]) => has(kind, field))) ?? 'facts';+ const section = location.section ?? fields.find(([, field]) => has(fence, field))?.[0] ?? 'body';+ return { ...location, fence, section };+}++/**+ * The typed refusal a coordinated writer throws. The wire `error` stays+ * `invalid_params` (E3), or `take_row_collision` for a stored-row collision,+ * so connector item holds and older receipt readers keep classifying it.+ */+export function fenceOperationError(location: FenceMessageLocation, slug: string | undefined, sourceId: string, opts: { legacy_error?: string } = {}): OperationError {+ return opError('invalid_fence', fenceMessage(location),+ `${slug ? `Page ${slug}` : 'The page'} in source ${sourceId} was not written. Fix the fence the message names in the page body, then write the page again with a new request_id.`,+ { legacy_error: opts.legacy_error ?? 'invalid_params', reason: location.reason,+ ...(slug ? { fix: readFix(`Shows page ${slug} with its fences, read-only.`, { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] }) } : {}) });+}diff --git a/src/core/import-screen.ts b/src/core/import-screen.tsindex 13bf9dbbaf..1fb4fb1563 100644--- a/src/core/import-screen.ts+++ b/src/core/import-screen.ts@@ -2,9 +2,10 @@* #5988: the one content screen every ingestion path shares. It decides,* without preparing or writing anything, whether content is importable or a* deterministic content refusal (size, unreadable or ambiguous frontmatter,- * a frontmatter slug that names another page, a content-sanity reject).- * Managed sync freezes, managed sync and import publication, and- * `importFromContent` (put_page, capture, legacy import) all call it, so a+ * a frontmatter slug that names another page, a content-sanity reject, and on+ * coordinated paths a facts or takes fence the canonical projection would+ * refuse, #6188). Managed sync freezes, managed sync and import publication,+ * and `importFromContent` (put_page, capture, legacy import) all call it, so a* file is held or refused for the same reason everywhere.*/import type { BrainEngine } from './engine.ts';@@ -15,6 +16,9 @@ import { classifyImportHold, contentSizeHold, parseMarkdown, type ContentHold, timport { isCodeFilePath } from './sync.ts';import { opError, type OperationError } from './ops/contract.ts';import type { Action } from './agent-output.ts';+import { fenceFixText, fenceLocationFromMessage, fenceRefusal, scanCanonicalFences } from './fence-repair/refusal.ts';+import type { FenceMessageLocation } from './fence-repair/reasons.ts';+import type { FenceReason } from './fence-repair/types.ts';export const MAX_FILE_SIZE = 5_000_000; // 5MB@@ -66,9 +70,15 @@ export function assessImportSanity(page: Pick<ParsedMarkdown, 'compiled_truth' |});}-/** A refusal the screen returns: a hold code, or `content_rejected` for an operator-configured sanity reject. */-export interface ContentRefusal extends Omit<ContentHold, 'code'> {- code: ContentHold['code'] | 'content_rejected';+/**+ * A refusal the screen returns: a hold code, `content_rejected` for an+ * operator-configured sanity reject, or `invalid_fence` (coordinated paths)+ * with its location-only `fence`.+ */+export interface ContentRefusal extends Omit<ContentHold, 'code' | 'reason'> {+ code: ContentHold['code'] | 'content_rejected' | 'invalid_fence';+ reason?: ContentHold['reason'] | FenceReason;+ fence?: FenceMessageLocation;}export interface ImportScreenInput {@@ -90,6 +100,14 @@ export interface ImportScreenInput {published?: () => boolean;/** Pre-loaded config: a junk hit under `junk_disposition: reject` refuses as `content_rejected`. */sanity?: ImportSanityConfig;+ /**+ * #6188 (E8): `coordinated` writers (managed sync, managed import, managed+ * file repair) refuse a fence the canonical projection would refuse as+ * `invalid_fence`; `lenient` (the default: legacy sync, `importFromFile`,+ * put_page) screens no fence. Coordinated put_page refuses the same fence+ * typed at its projection, after the remote hidden-row merge.+ */+ fences?: 'coordinated' | 'lenient';}export type ImportScreenResult =@@ -106,6 +124,10 @@ export function screenImportContent(input: ImportScreenInput): ImportScreenResulconst parsed = parseMarkdown(input.content, input.path, { validate: true, ...(input.activePack ? { activePack: input.activePack } : {}) });const hold = classifyImportHold(parsed, { expectedSlug: input.expectedSlug, slugExempt: input.slugExempt, slugConflictMessage: input.slugConflictMessage });if (hold) return { status: 'refused', refusal: hold };+ if (input.fences === 'coordinated') {+ const [defect] = scanCanonicalFences(parsed).defects;+ if (defect) return { status: 'refused', refusal: fenceRefusal(defect) };+ }if (input.sanity && !input.sanity.disabled && input.sanity.junkDisposition === 'reject') {const result = assessImportSanity(parsed, input.sanity);if (result.shouldQuarantine) return { status: 'refused', refusal: { code: 'content_rejected', message: `Content rejected by sanity gate: ${result.reason_messages.join('; ')}` } };@@ -133,6 +155,9 @@ export function contentRefusalError(refusal: ContentRefusal, suggestion: string,export function contentRefusalFromReceipt(code: string | null | undefined, message: string | null | undefined): (Omit<ContentRefusal, 'message'> & { suggestion: string }) | null {if (!isContentRefusal(code, message)) return null;const text = message ?? '';+ const fence = fenceLocationFromMessage(code, text);+ if (fence) return { code: 'invalid_fence', reason: fence.reason, ...(fence.fence && fence.section ? { fence: fence as FenceMessageLocation } : {}),+ suggestion: `The content itself was refused, so resubmitting it unchanged refuses again. ${fenceFixText(fence)} Then submit the corrected content with a new request_id.` };const key = /key "([^"\n]{1,200})"/.exec(text)?.[1];const lineText = /\bat line (\d+)/.exec(text)?.[1];const line = lineText === undefined ? undefined : Number(lineText);@@ -166,14 +191,16 @@ const LEGACY_CONTENT_MESSAGES: Array<[code: string, pattern: RegExp]> = [/*** True when a stored refusal (receipt `error_code` + `error_message`) is a- * deterministic content refusal no retry can fix: the new typed codes, and- * the exact strings older gbrain versions stored for the same causes.- * Cursor-size and admission-capacity `request_too_large`, and every transient- * or conflict code, never match.+ * deterministic content refusal no retry can fix: the new typed codes, the+ * #6188 fence grammar (`Fence <reason>: ...` under wire `invalid_params` or+ * `take_row_collision`), and the exact strings older gbrain versions stored+ * for the same causes. Cursor-size and admission-capacity+ * `request_too_large`, every transient or conflict code, and any other+ * `invalid_params` message never match.*/export function isContentRefusal(code: string | null | undefined, message: string | null | undefined): boolean {if (!code) return false;if (CONTENT_REFUSAL_CODES.has(code)) return true;const text = message ?? '';- return LEGACY_CONTENT_MESSAGES.some(([legacy, pattern]) => legacy === code && pattern.test(text));+ return LEGACY_CONTENT_MESSAGES.some(([legacy, pattern]) => legacy === code && pattern.test(text)) || fenceLocationFromMessage(code, text) !== null;}diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex e5976a1d53..3380eef18c 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -11,39 +11,26 @@ import { extractTimelineFromContent, type ExtractedTimelineEntry } from '../timeimport { sanitizeRemoteBody } from '../remote-body.ts';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';+import type { OperationError } from '../ops/contract.ts';+import { protectedRegions } from '../fence-scan.ts';+import { FENCE_ROWS_MAX, fenceOperationError, scanCanonicalFences } from '../fence-repair/refusal.ts';+import type { FenceSection } from '../fence-repair/types.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`.+ * Rows held by fences whose begin sits in markdown code, keyed `row_num:text`,+ * with the section each sits in. 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.*/-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) {+function quotedFenceRows(fields:Array<[FenceSection,string]>):{facts:Map<string,FenceSection>,takes:Map<string,FenceSection>} {+ const facts=new Map<string,FenceSection>(),takes=new Map<string,FenceSection>();+ for(const [section,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}`);+ if(region.pair===0) for(const f of parseFactsFence(text).facts) facts.set(`${f.rowNum}:${f.claim}`,section);+ else for(const t of parseTakesFence(text).takes) takes.set(`${t.rowNum}:${t.claim}`,section);}return {facts,takes};}@@ -252,29 +239,16 @@ function canonicalTakeRows(body: CanonicalBody): Set<number> {return new Set([body.compiled_truth, body.timeline ?? ''].flatMap(field => parseTakesFence(field).takes.map(t => t.rowNum)));}-/** Validate a canonical body and compile its provider-free projections. */-function fenceError(message: string, slug: string, sourceId: string, what: string) {- return opError('invalid_params', message, `${what} on page ${slug} in source ${sourceId}, so it was not written. Fix the fence in the page body, then write the page again.`,- { fix: readFix(`Shows page ${slug} with its fences, read-only.`, { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] }) });-}-+/**+ * Validate a canonical body and compile its provider-free projections. A fence+ * the shared scan refuses throws typed `invalid_fence` (wire `invalid_params`)+ * naming the first defect's fence, section and reason.+ */export function compileCanonicalProjections(page: ParsedPage, slug: string, sourceId: string) {- const fields=[page.compiled_truth,page.timeline ?? ''];- 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');- const facts=factSets.flatMap(set=>set.facts),takes=takeSets.flatMap(set=>set.takes);- 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, quoted: quoting ? quotedFenceRows(fields) : null };+ const scan=scanCanonicalFences(page);+ if(scan.defects.length) throw fenceOperationError(scan.defects[0]!, slug, sourceId);+ const fields:Array<[FenceSection,string]>=[['body',page.compiled_truth],['timeline',page.timeline ?? '']];+ return { factRows: extractFactsFromFenceText(scan.facts,slug,sourceId), takes: scan.takes, sections: scan.sections, quoted: scan.quoting ? quotedFenceRows(fields) : null };}/**@@ -282,25 +256,29 @@ export function compileCanonicalProjections(page: ParsedPage, slug: string, sour* 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> },+async function refuseQuotedFenceLoss(tx: BrainEngine, pageId: number, quoted: { facts: Map<string, FenceSection>; takes: Map<string, FenceSection> },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');+ const refuse = (fence: 'facts' | 'takes', lost: Array<{ row_num: number; section: FenceSection }>) => fenceOperationError({ reason: 'quoted_fence_rows', fence,+ section: lost[0]!.section, rows: [...new Set(lost.map(r => Number(r.row_num)))].slice(0, FENCE_ROWS_MAX), columns: [], line: null }, slug, sourceId);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();+ const lost = gone.flatMap(r => { const section = quoted.takes.get(`${r.row_num}:${r.claim}`); return section ? [{ row_num: r.row_num, section }] : []; });+ if (lost.length) throw refuse('takes', lost);}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 factsWHERE 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();+ const lost = live.flatMap(r => { const section = kept.has(`${r.row_num}:${r.fact}:${r.visibility}`) ? undefined : quoted.facts.get(`${r.row_num}:${r.fact}`);+ return section ? [{ row_num: r.row_num, section }] : []; });+ if (lost.length) throw refuse('facts', lost);}}-function takeCollision(): OperationError {- return new OperationError('take_row_collision', 'A takes fence row number is already used by a different take that is not in this page\'s canonical fence.',- 'Renumber the new takes row, or add the existing take to the fence with a revision-bound put_page.');+/** A new fence row's number already names a different stored take: typed `invalid_fence`, wire `take_row_collision` (E4). */+function takeCollision(rows: number[], sections: Map<number, FenceSection>, slug: string, sourceId: string): OperationError {+ return fenceOperationError({ reason: 'stored_row_collision', fence: 'takes', section: sections.get(rows[0]!) ?? 'body', rows: rows.slice(0, FENCE_ROWS_MAX), columns: [], line: null },+ slug, sourceId, { legacy_error: 'take_row_collision' });}/**@@ -311,7 +289,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, quoted } = compileCanonicalProjections(page, slug, sourceId);+ const { factRows, takes, quoted, sections } = 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')@@ -322,10 +300,14 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Parconst priorTakes = prior ? canonicalTakeRows(prior.page) : new Set<number>();const newTakes = JSON.stringify(takes.filter(t => !priorTakes.has(t.rowNum)).map(t => ({ row_num: t.rowNum, claim: t.claim, kind: t.kind, holder: t.holder })));const takeRowsGone = [...priorTakes].filter(n => !takes.some(t => t.rowNum === n));- const collides = async (db: BrainEngine, pageId: number) => (await db.executeRaw(`SELECT 1 FROM takes k+ const collisions = async (db: BrainEngine, pageId: number) => (await db.executeRaw<{ row_num: number }>(`SELECT k.row_num FROM takes kJOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num- WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) LIMIT 1`, [pageId, newTakes])).length > 0;- if (prior && await collides(engine, prior.page.id)) throw takeCollision();+ WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3`, [pageId, newTakes, FENCE_ROWS_MAX])).map(r => Number(r.row_num));+ const refuseCollisions = async (db: BrainEngine, pageId: number) => {+ const rows = await collisions(db, pageId);+ if (rows.length) throw takeCollision(rows, sections.takes, slug, sourceId);+ };+ if (prior) await refuseCollisions(engine, prior.page.id);// #5984: `pageId` is the caller's own read of the page in this transaction. The// statements are issued as pipelines; an engine call that sends more than one// statement (insertFacts, addTakesBatch) ends one, so order is kept.@@ -352,7 +334,7 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par[sourceId, slug, fact.row_num, fact.kind, fact.notability, fact.context, fact.valid_from?.toISOString() ?? null,fact.valid_until?.toISOString() ?? null, fact.expired_at?.toISOString() ?? null, fact.source, fact.confidence,fact.claim_metric ?? null, fact.claim_value ?? null, fact.claim_unit ?? null, fact.claim_period ?? null, fact.attributed_to ?? null]));- const checkTakes = async () => { if (await collides(tx, id)) throw takeCollision(); };+ const checkTakes = () => refuseCollisions(tx, id);const dropTakes = () => tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])', [id, takeRowsGone]);// Full canonical versions include resolution fields; a revert restores those// fields from Markdown too, without the ordinary immutable-resolution API.diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex a47ccbbae8..e0edbaa6d6 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -32,6 +32,7 @@ import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, pubimport { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';import { databaseRefusal, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';+import { fenceFailureDetail } from '../fence-repair/refusal.ts';import { faultPoint, withFaultPoints } from './fault-points.ts';interface PreparedMutationBase {@@ -112,7 +113,11 @@ function publishFile(file: PageMutationFile, stagingPath?: string, afterStagingF// its own recovery record and native root capability.export { fileHash as persistenceFileHash, publishFile as publishPersistenceFile };function requestError(error: unknown): PublicationFailure {- if (error instanceof OperationError) return { code: error.code, message: error.message };+ if (error instanceof OperationError) {+ // #6188: a typed fence refusal keeps its location in the bounded detail, which outlives receipt compaction.+ const fence = fenceFailureDetail(error);+ return { code: error.code, message: error.message, ...(fence ? { detail: fence } : {}) };+ }const refusal = databaseRefusal(error);if (refusal) return refusal;const code = (error as { code?: string })?.code;diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.tsindex 9642088062..3af427a869 100644--- a/src/core/persistence/diagnostics.ts+++ b/src/core/persistence/diagnostics.ts@@ -76,7 +76,7 @@ export async function readWriterDiagnostics(engine: BrainEngine) {const failures = await engine.executeRaw<{ request_id: string; operation: string; source_id: string; state: WriteRequestState;error_code: string | null; error_detail: Record<string, unknown>; completed_at: Date | string | null }>(`SELECT request_id,operation,source_id,state,error_code,error_detail,completed_at FROM persistence_requests- WHERE error_detail IS NOT NULL ORDER BY sequence DESC LIMIT 20`);+ WHERE error_detail IS NOT NULL AND COALESCE(error_detail->>'origin','')<>'fence' ORDER BY sequence DESC LIMIT 20`);const limits = await readJournalLimits(engine);const { persistenceConsumerStatus } = await import('./service.ts');// C-NEW-4: the consumer is per process, so this is the answering process's own ingress, never proof the brain's owner is down.diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex de5c0ae792..e2e0a4b946 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -1,5 +1,6 @@import { OperationError } from '../ops/contract.ts';import { writerStamp } from './writer-versions.ts';+import type { FenceFailureDetail } from '../fence-repair/refusal.ts';/*** #5974: a database refusal during preparation or publication becomes a@@ -22,7 +23,9 @@ export interface PublicationFailureDetail {/** Owner-only: the build and host that executed the failed attempt. */attempt?: { consumer_version: string; consumer_host_id: string | null };}-export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail }+/** #6188: a typed fence refusal's location (`fence-repair/refusal.ts`), plus the attempt stamp. */+export type FenceRefusalDetail = FenceFailureDetail & Pick<PublicationFailureDetail, 'stage' | 'attempt'>;+export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail }const IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;const ident = (value: unknown) => typeof value === 'string' && IDENT.test(value) ? value : undefined;@@ -76,9 +79,18 @@ export function withAttempt(failure: PublicationFailure, stage: PublicationStagereturn { ...failure, detail: { ...failure.detail, stage, attempt: { consumer_version: stamp.version, consumer_host_id: stamp.hostId } } };}-/** The receipt view any caller may read: fixed enums only, no source identifiers, host or build. */+/**+ * The receipt view any caller may read: fixed enums only, no source+ * identifiers, host or build. A fence location keeps its fence, section,+ * reason and problem classes; its row numbers stay owner-side (they can+ * number rows a remote caller never saw).+ */export function publicFailureDetail(detail: unknown): Record<string, unknown> | undefined {if (!detail || typeof detail !== 'object' || Array.isArray(detail)) return undefined;const { sources: _sources, attempt: _attempt, ...rest } = detail as PublicationFailureDetail;+ if ((rest as { origin?: unknown }).origin === 'fence') {+ const { rows: _rows, ...fence } = ((rest as unknown as FenceFailureDetail).fence ?? {}) as FenceFailureDetail['fence'];+ return { ...rest, fence } as unknown as Record<string, unknown>;+ }return rest as unknown as Record<string, unknown>;}diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 08873ec04a..2514390859 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -24,6 +24,7 @@ import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';import type { ContentRefusal } from '../import-screen.ts';import type { InvalidFrontmatterReason } from '../markdown.ts';+import type { FenceReason } from '../fence-repair/types.ts';import type { SyncRename } from './sync-discovery.ts';export const GIT_HOLD_OP = 'sync-hold';@@ -44,7 +45,7 @@ export const GIT_HOLD_ESCALATE_MIN_SCREENED = 40;type Exec = Pick<BrainEngine, 'executeRaw'>;export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported';-export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed';+export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed' | FenceReason;export interface GitHoldMeta {reason?: GitHoldReason;diff --git a/test/connector-item-holds.test.ts b/test/connector-item-holds.test.tsindex 0258b068d4..d38c8400b8 100644--- a/test/connector-item-holds.test.ts+++ b/test/connector-item-holds.test.ts@@ -3,6 +3,7 @@* classification table, circuit breaker, backoff schedule, cap and legacy* carry-over, with an injected clock. Pure logic; no engine.*/+import { fenceOperationError } from '../src/core/fence-repair/refusal.ts';import { describe, expect, test } from 'bun:test';import { CredentialError } from '../src/core/creds/errors.ts';import { OperationError } from '../src/core/ops/contract.ts';@@ -66,6 +67,18 @@ describe('classifyConnectorError (the one classification table)', () => {});});+describe('fence refusals (#6188)', () => {+ test('a typed fence refusal keeps its wire code, so a connector item hold classifies it as content', () => {+ const location = { reason: 'enum_unmapped', fence: 'facts', section: 'body', rows: [1], columns: ['kind'], line: 4 } as const;+ const unparseable = fenceOperationError({ ...location, rows: [1], columns: ['kind'] }, 'notes/example', 'default');+ const stored = fenceOperationError({ ...location, reason: 'stored_row_collision', fence: 'takes', rows: [2], columns: [] }, 'notes/example', 'default', { legacy_error: 'take_row_collision' });+ for (const [error, code] of [[unparseable, 'invalid_params'], [stored, 'take_row_collision']] as const) {+ expect(error.canonicalCode).toBe('invalid_fence');+ expect(classifyConnectorError(error)).toMatchObject({ code, scope: 'item', class: 'content' });+ }+ });+});+describe('ItemHoldsRun counting', () => {test('a singleton item failing transiently is held after 3 attempted runs, then skipped', () => {const c = clock();diff --git a/test/facts-withdrawal-fingerprint-once.test.ts b/test/facts-withdrawal-fingerprint-once.test.tsindex 09e7a7294c..09ed5a87b2 100644--- a/test/facts-withdrawal-fingerprint-once.test.ts+++ b/test/facts-withdrawal-fingerprint-once.test.ts@@ -65,7 +65,9 @@ for (const backend of testBackends()) {`| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n` +`|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n` +`| 1 | Prefers email | preference | 1.0 | ${visibility} | medium | 2026-01-01 | | chat | |\n`;- await expect(assertPreparedFactWithdrawals(engine, 'default', unbalanced('world'), '', SUBJECT)).rejects.toMatchObject({ code: 'invalid_params' });+ // #6188 (E6): the wire code stays invalid_params; the canonical code is the typed fence refusal.+ await expect(assertPreparedFactWithdrawals(engine, 'default', unbalanced('world'), '', SUBJECT)).rejects.toMatchObject({ code: 'invalid_params', canonical: 'invalid_fence',+ reason: 'withdrawn_claim_in_malformed_fence' });await expect(assertPreparedFactWithdrawals(engine, 'default', unbalanced('private'), '', SUBJECT)).resolves.toBeUndefined();await expect(assertPreparedFactWithdrawals(engine, 'default', unbalanced('world'), '', 'people/bob-example')).resolves.toBeUndefined();} finally { await close(); }diff --git a/test/fence-marker-projection.test.ts b/test/fence-marker-projection.test.tsindex 35196d287e..bed1643f09 100644--- a/test/fence-marker-projection.test.ts+++ b/test/fence-marker-projection.test.ts@@ -100,8 +100,8 @@ test('every way of quoting a real fence in code is refused instead of dropping ifor (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/);+ // Refused either as a quoted fence or as an unbalanced one (#6188 typed reasons); the rows are kept both ways.+ await expect(put(slug, wrap(fences('Example belief', 'Example fact')))).rejects.toThrow(/^Fence (quoted_fence_rows|missing_begin|unparseable): in the (facts|takes) fence \((body|timeline)\)/);expect(await rows(slug)).toEqual({ takes: 1, facts: 1 });}});diff --git a/test/fence-refusal.test.ts b/test/fence-refusal.test.tsnew file mode 100644index 0000000000..4fd3972958--- /dev/null+++ b/test/fence-refusal.test.ts@@ -0,0 +1,149 @@+/**+ * #6188 PR1: the shared fence check, its typed refusal and the receipt grammar.+ * A coordinated screen refuses exactly what the canonical projection refuses,+ * the location comes from the raw-row view (never a parser warning string),+ * and a stored receipt (current grammar, a legacy message, or the durable+ * detail that outlives compaction) reads back into the same location, while an+ * arbitrary `invalid_params` never does. Synthetic content only.+ */+import { describe, expect, test } from 'bun:test';+import { compileCanonicalProjections } from '../src/core/persistence/canonical-projections.ts';+import { screenImportContent, isContentRefusal, contentRefusalFromReceipt } from '../src/core/import-screen.ts';+import { fenceMessage, FENCE_REASON_CODES } from '../src/core/fence-repair/reasons.ts';+import { CODES } from '../src/core/error-registry.ts';+import { completeFenceLocation, fenceFailureDetail, fenceLocationFromDetail, fenceLocationFromMessage, fenceOperationError, fenceReceiptLocation,+ parseFenceMessage, scanCanonicalFences } from '../src/core/fence-repair/refusal.ts';+import { publicFailureDetail } from '../src/core/persistence/publication-failure.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import type { ParsedPage } from '../src/core/import-file.ts';++const F = '<!--- gbrain:facts:begin -->', FE = '<!--- gbrain:facts:end -->', T = '<!--- gbrain:takes:begin -->', TE = '<!--- gbrain:takes:end -->';+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';+const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';+// Unique strings that must never leave the page: a claim, a holder and a kind.+const CLAIM = 'Sentinelclaimzq7 ships quarterly', HOLDER = 'Sentinelholderzq7 Example', KIND = 'sentinelkindzq7';+const fact = (n: number | string, kind = 'fact', claim = CLAIM) => `| ${n} | ${claim} | ${kind} | 1.0 | private | medium | 2026-01-01 | | chat | |`;+const take = (n: number | string, who = 'brain', kind = 'take', claim = CLAIM) => `| ${n} | ${claim} | ${kind} | ${who} | 0.7 | 2026-01 | chat |`;+const facts = (...rows: string[]) => `${F}\n${FH}\n${rows.join('\n')}\n${FE}`;+const takes = (...rows: string[]) => `${T}\n${TH}\n${rows.join('\n')}\n${TE}`;+const page = (body: string, timeline = ''): ParsedPage => ({ compiled_truth: body, timeline } as ParsedPage);+const file = (body: string) => `---\ntitle: Example page\n---\n${body}\n`;++const cases: Array<[name: string, body: string, timeline: string, expected: Record<string, unknown>]> = [+ ['missing end marker', `Intro\n\n${F}\n${FH}\n${fact(1)}\n`, '', { reason: 'unparseable', fence: 'facts', section: 'body', line: 3 }],+ ['two-dash takes markers', `<!-- gbrain:takes:begin -->\n${TH}\n${take(1)}\n<!-- gbrain:takes:end -->`, '', { reason: 'marker_near_miss', fence: 'takes', line: 1 }],+ ['repeated marker', `${facts(fact(1))}\n\n${facts(fact(2))}`, '', { reason: 'repeated_marker', fence: 'facts', section: 'body' }],+ ['unknown facts kind', facts(fact(1, KIND)), '', { reason: 'enum_unmapped', fence: 'facts', rows: [1], columns: ['kind'], line: 4 }],+ ['unknown takes kind', takes(take(2, 'brain', KIND)), '', { reason: 'takes_kind_unsupported', fence: 'takes', rows: [2], columns: ['kind'] }],+ ['invalid holder', takes(take(3, HOLDER)), '', { reason: 'holder_unresolved', fence: 'takes', rows: [3], columns: ['who'] }],+ ['short row', facts(`| 4 | ${CLAIM} | fact |`), '', { reason: 'short_row', fence: 'facts', rows: [4] }],+ ['duplicate row in one fence', takes(take(5), take(5, 'world')), '', { reason: 'row_collision', fence: 'takes', rows: [5] }],+ ['duplicate row across sections', facts(fact(6)), facts(fact(6)), { reason: 'row_collision', fence: 'facts', section: 'timeline', rows: [6] }],+];++describe('the shared fence check', () => {+ test('a clean page, a page without fences, a fence quoted in code and a lone end marker (the projection reads none) pass the check', () => {+ for (const body of ['No fences here.', facts(fact(1)), takes(take(1)), `Example:\n\n\`\`\`\n${facts(fact(9, KIND))}\n\`\`\`\n`, `Intro\n\n${FE}\n`]) {+ expect(scanCanonicalFences(page(body)).defects).toEqual([]);+ expect(() => compileCanonicalProjections(page(body), 'notes/example', 'default')).not.toThrow();+ }+ });++ for (const [name, body, timeline, expected] of cases) {+ test(`${name}: the screen and the projection refuse it with the same typed location`, () => {+ const [defect] = scanCanonicalFences(page(body, timeline)).defects;+ expect(defect).toMatchObject(expected);+ let thrown: unknown;+ try { compileCanonicalProjections(page(body, timeline), 'notes/example', 'default'); } catch (error) { thrown = error; }+ expect(thrown).toBeInstanceOf(OperationError);+ const error = thrown as OperationError;+ // E3: wire error stays invalid_params; the canonical code and reason are typed.+ expect({ code: error.code, canonical: error.canonicalCode, reason: error.reason }).toEqual({ code: 'invalid_params', canonical: 'invalid_fence', reason: expected.reason as string });+ expect(error.message).toBe(fenceMessage(defect!));+ expect(error.fix?.argv).toEqual(['gbrain', 'get', '--source', 'default', '--', 'notes/example']);+ for (const secret of [CLAIM, HOLDER, KIND, 'Sentinel']) expect(error.message).not.toContain(secret);++ const coordinated = screenImportContent({ content: file(timeline ? `${body}\n\n<!-- timeline -->\n\n${timeline}` : body), path: 'notes/example.md', fences: 'coordinated' });+ expect(coordinated.status).toBe('refused');+ if (coordinated.status === 'refused') {+ expect(coordinated.refusal).toMatchObject({ code: 'invalid_fence', reason: expected.reason, fence: { reason: expected.reason, fence: expected.fence } });+ expect(JSON.stringify(coordinated.refusal)).not.toMatch(/Sentinel|sentinel/);+ }+ // T5: legacy (lenient, the default) paths import it as before.+ expect(screenImportContent({ content: file(body), path: 'notes/example.md' }).status).toBe('importable');+ });+ }++ test('a stored-row collision keeps its own wire code', () => {+ const error = fenceOperationError({ reason: 'stored_row_collision', fence: 'takes', section: 'body', rows: [2], columns: [], line: null }, 'notes/example', 'default',+ { legacy_error: 'take_row_collision' });+ expect({ code: error.code, canonical: error.canonicalCode, reason: error.reason }).toEqual({ code: 'take_row_collision', canonical: 'invalid_fence', reason: 'stored_row_collision' });+ });++ test('the registry entry lists every reason of the shared table and keeps the frozen wire value', () => {+ expect(CODES.invalid_fence).toMatchObject({ class: 'caller', legacy_error: 'invalid_params', reasons: FENCE_REASON_CODES });+ });+});++describe('the receipt grammar', () => {+ const locations = [+ { reason: 'enum_unmapped', fence: 'facts', section: 'body', rows: [1, 3], columns: ['kind'], line: 6 },+ { reason: 'row_collision', fence: 'takes', section: 'timeline', rows: [4], columns: [], line: null },+ { reason: 'repeated_marker', fence: 'facts', section: 'body', rows: [], columns: [], line: 12 },+ { reason: 'stored_row_collision', fence: 'takes', section: 'body', rows: [2], columns: [], line: null },+ ] as const;++ test('every message reads back into its location, from the message and from the durable detail', () => {+ for (const location of locations) {+ const message = fenceMessage({ ...location, rows: [...location.rows], columns: [...location.columns] });+ expect(parseFenceMessage(message)).toEqual({ ...location, rows: [...location.rows], columns: [...location.columns] });+ const wire = location.reason === 'stored_row_collision' ? 'take_row_collision' : 'invalid_params';+ expect(isContentRefusal(wire, message)).toBe(true);+ expect(contentRefusalFromReceipt(wire, message)).toMatchObject({ code: 'invalid_fence', reason: location.reason, fence: { fence: location.fence, section: location.section } });+ const error = fenceOperationError({ ...location, rows: [...location.rows], columns: [...location.columns] }, 'notes/example', 'default', { legacy_error: wire });+ const detail = fenceFailureDetail(error)!;+ expect(detail).toMatchObject({ origin: 'fence', fence: { version: 1, reason: location.reason } });+ // Compaction drops the message; the detail alone still names the location.+ expect(fenceReceiptLocation({ error_code: wire, error_message: null, error_detail: detail })).toEqual({ ...location, rows: [...location.rows], columns: [...location.columns] });+ }+ });++ test('the messages older releases stored convert to the typed reason; an arbitrary invalid_params never does', () => {+ const legacy: Array<[string, string, string]> = [+ ['invalid_params', 'Each canonical body section must contain at most one facts fence and one takes fence.', 'repeated_marker'],+ ['invalid_params', 'A canonical facts or takes fence cannot be parsed losslessly.', 'unparseable'],+ ['invalid_params', 'Canonical row numbers must be unique across the entire page.', 'row_collision'],+ ['invalid_params', 'A takes or facts fence sits inside markdown code, so this write would remove the rows it holds.', 'quoted_fence_rows'],+ ['invalid_params', 'A malformed fact fence contains a withdrawn claim.', 'withdrawn_claim_in_malformed_fence'],+ ['take_row_collision', "A takes fence row number is already used by a different take that is not in this page's canonical fence.", 'stored_row_collision'],+ ];+ for (const [code, message, reason] of legacy) {+ expect(fenceLocationFromMessage(code, message)?.reason as string | undefined).toBe(reason);+ expect(isContentRefusal(code, message)).toBe(true);+ expect(contentRefusalFromReceipt(code, message)).toMatchObject({ code: 'invalid_fence', reason });+ }+ for (const [code, message] of [['invalid_params', 'The value is invalid.'], ['invalid_params', 'Fence not_a_reason: in the facts fence (body). x'],+ ['storage_error', 'A canonical facts or takes fence cannot be parsed losslessly.'], ['invalid_params', null]] as const) {+ expect(fenceLocationFromMessage(code, message)).toBeNull();+ expect(isContentRefusal(code, message)).toBe(false);+ }+ expect(fenceReceiptLocation({ error_code: 'invalid_params', error_message: null, error_detail: null })).toBeNull();+ });++ test('a tampered or foreign detail is never read as a fence location, and the public view drops row numbers', () => {+ expect(fenceLocationFromDetail({ origin: 'database_guard', sqlstate: 'P0001' })).toBeNull();+ expect(fenceLocationFromDetail({ origin: 'fence', fence: { version: 2, reason: 'unparseable', fence: 'facts', section: 'body' } })).toBeNull();+ expect(fenceLocationFromDetail({ origin: 'fence', fence: { version: 1, reason: 'not_a_reason', fence: 'facts', section: 'body' } })).toBeNull();+ expect(fenceLocationFromDetail({ origin: 'fence', fence: { version: 1, reason: 'enum_unmapped', fence: 'facts', section: 'body', rows: [1, 'x', -2], columns: ['kind', 'Bad Col'], line: 'x' } }))+ .toEqual({ reason: 'enum_unmapped', fence: 'facts', section: 'body', rows: [1], columns: ['kind'], line: null });+ const stored = { origin: 'fence', fence: { version: 1, reason: 'row_collision', fence: 'takes', section: 'body', rows: [7], columns: [], line: null }, attempt: { consumer_version: 'x', consumer_host_id: null } };+ expect(publicFailureDetail(stored)).toEqual({ origin: 'fence', fence: { version: 1, reason: 'row_collision', fence: 'takes', section: 'body', columns: [], line: null } });+ });++ test('a receipt an older release stored names its section from the refused bytes', () => {+ expect(completeFenceLocation({ reason: 'stored_row_collision', fence: 'takes', rows: [], columns: [], line: null }, page('Intro.', takes(take(1)))))+ .toMatchObject({ fence: 'takes', section: 'timeline' });+ expect(completeFenceLocation({ reason: 'quoted_fence_rows', rows: [], columns: [], line: null }, page(facts(fact(1)))))+ .toMatchObject({ fence: 'facts', section: 'body' });+ });+});