Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(fences): strict facts headers and fence rewriters refuse unparsed input (#6385, R12)
time-attack5080104ae55e
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 965c9b0d88..75e28e05dd 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -40,7 +40,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/dream-breaker.ts` — dream paid-loop circuit breaker. `countDeadDreamSubmissions` is the one counting rule shared by synthesize, patterns, `gbrain dream reset-key` and the `dream_paid_loop` doctor check: dead `subagent` rows finished in the last 24 h (partial index `idx_minion_jobs_dead_subagent_finished`, migration 173), keyed by the live or released idempotency key with the `:c<i>of<n>` chunk suffix stripped, counted as distinct queues (one per run), ignoring deaths before the key's persisted reset (`dream.breaker.resets` config JSON, database clock). A key at `dream.breaker.max_dead_submissions` (default 3; 0 disables) is refused before synthesis submission; a failed count leaves the breaker off for that run with a warning. Completed jobs, including legitimate zero-write completions, never count. Growing transcripts change their content-hashed key and unkeyed patterns runs are not covered. Contained cycle-phase failures after paid model calls (`recordContainedPaidFailure`, `dream.breaker.contained_failures` config JSON, 24 h window, database clock) are counted under `dream:phase:<phase>:<source>` keys; the breaker never refuses those phases, doctor reports them and `gbrain dream reset-key` clears them. Tests: `test/dream-breaker.test.ts`, `test/cycle-synthesize-breaker.test.ts`, `test/e2e/dream-breaker-postgres.test.ts`. Patterns rows count under the per-source key `dream:patterns:source:<data.source_id or default>` (never their content key), and a patterns child `cancelled` with recorded tokens counts as a death; `patternsBreakerSkip` returns the phase skip (`dream_breaker_tripped`, paid reset `fix`, read-only `--list --json` verify) and `clearPatternsSourceDeaths` resets the source after a completed child (`test/dream-breaker-patterns-source.test.ts`).-- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1). Only fence rows migrate, so the residue gate also counts the page's timeline text, any `timeline_entries` row, and frontmatter keys beyond `title`/`type`/`tags`; any residue = not a phantom. Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match; a fuzzy hit needs a 0.1 margin over the runner-up) → `findPrefixCandidates` ambiguity check (a canonical that is not the single prefix candidate is ambiguous too) → `fenceDbDrift` bi-directional check → dry-run early exit → canonical file resolved through `resolvePageWriteTarget` (recorded `source_path`, own-`local_path` roots; only a brain with no configured root falls back to `brainDir`) → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to that file with `(claim, valid_from)` dedup-guard, numbering past both the file's and the DB's highest row number and rewriting `superseded by #N` to the new numbers → `engine.refreshPageBody` → move the phantom's fact withdrawals to the canonical subject → move every phantom fact row by id (a row takes its on-disk canonical row number unless the canonical index already holds it; history, duplicates and rows absent from the fence move expired and detached, never deleted) → move the phantom's links to the canonical page id (skipping duplicates and self-links) → `recordRenameAlias` (phantom → canonical in `slug_aliases`) → `engine.softDeletePage` + unlink. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append. `mergePhantomFenceRows` (pure body merge), `movePhantomFacts` (row move inside the caller's transaction) and `mergePhantomLinks` are shared with `phantom-redirect-managed.ts`, which a managed brain uses instead of the file-first commit phase.+- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1). Only fence rows migrate, so the residue gate also counts the page's timeline text, any `timeline_entries` row, and frontmatter keys beyond `title`/`type`/`tags`; any residue = not a phantom. Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match; a fuzzy hit needs a 0.1 margin over the runner-up) → `findPrefixCandidates` ambiguity check (a canonical that is not the single prefix candidate is ambiguous too) → `fenceDbDrift` bi-directional check → a phantom fence that parses with warnings is `drift` (its skipped rows would go with the deleted phantom, #6385 R12) → dry-run early exit → canonical file resolved through `resolvePageWriteTarget` (recorded `source_path`, own-`local_path` roots; only a brain with no configured root falls back to `brainDir`) → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to that file with `(claim, valid_from)` dedup-guard, numbering past both the file's and the DB's highest row number and rewriting `superseded by #N` to the new numbers → `engine.refreshPageBody` → move the phantom's fact withdrawals to the canonical subject → move every phantom fact row by id (a row takes its on-disk canonical row number unless the canonical index already holds it; history, duplicates and rows absent from the fence move expired and detached, never deleted) → move the phantom's links to the canonical page id (skipping duplicates and self-links) → `recordRenameAlias` (phantom → canonical in `slug_aliases`) → `engine.softDeletePage` + unlink. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append. `mergePhantomFenceRows` (pure body merge; throws `FenceRewriteRefusal` on a canonical fence that parses with warnings, which the pass records as `drift`), `movePhantomFacts` (row move inside the caller's transaction) and `mergePhantomLinks` are shared with `phantom-redirect-managed.ts`, which a managed brain uses instead of the file-first commit phase.- `src/core/cycle/phantom-redirect-managed.ts` — managed-brain phantom redirect (#5280). After the same gates, `redirectManagedPhantom` runs `maintenancePreflight`, renders the canonical body with the phantom's fence rows appended and submits `managed_maintenance_phantom_merge` on the canonical page (keyed by its intent): `preparePhantomMerge` rechecks the phantom's id and revision, and its publication moves withdrawals, the phantom's fact rows by id, links and the rename alias in the canonical page's publication transaction. It then submits `managed_maintenance_phantom_delete` on the phantom, bound to the merged revision: `preparePhantomDelete` holds both page keys, moves any edge added to the phantom since the merge, defers if timeline rows appeared, then soft-deletes and removes the file. A missing canonical page or a changed phantom is reported as `drift`. Tests: `test/managed-facts-writers.test.ts`.diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex c024308c82..ac04263035 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -6,8 +6,8 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies`, so on owner start) touches only interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command), which the refusal hints point at. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts`; while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.-- `src/core/fence-repair/refusal.ts` — #6188 the one fence check coordinated writers share. `scanCanonicalFences` decides from the strict parsers what the canonical projection refuses (a repeated marker outside code, any parser warning, a row number used twice on the page) and locates each defect from the raw-row view (`raw-rows.ts`, `schema.ts`), never from parser warning strings, which embed row text; reasons and messages come from `reasons.ts` (`FENCE_REASONS`, `fenceMessage`, `issueLocation`). `fenceOperationError` is the typed refusal (`invalid_fence`, wire `invalid_params`, or `take_row_collision` for a stored-row collision). `fenceFailureDetail` is the bounded, versioned `error_detail.fence` a failed receipt keeps through compaction; `fenceReceiptLocation` reads a receipt back from that detail, the message grammar or an older release's exact message, and never from an arbitrary `invalid_params`. `completeFenceLocation` names the section of a legacy receipt from the refused bytes. Tests: `test/fence-refusal.test.ts`, `test/fence-hold-surfaces.test.ts`, `test/persistence-sync-fence-holds.test.ts` (PGLite and Postgres).-- `src/core/fence-repair/{types,schema,raw-rows,reasons}.ts` — #6188 the shared fence vocabulary, all location-only. `types.ts`: `FenceIssue`, `FenceFix`, `FenceCtx`, `FenceReason`, `FixClass`. `schema.ts`: canonical columns, accepted widths (facts 9/10/14, takes 6/7/13), header aliases, enum and kind synonym tables (exported for the format reference), cell validity. `raw-rows.ts`: `extractRawRows` reads each fence leniently (markers outside code, header map or positional fallback, cells with source spans, a row's identity is its ordinal); a row is `accepted` exactly when the strict parser returns it. `reasons.ts`: `FENCE_REASONS` (tier, auto-retry, actor, fix template, docs anchor per reason; the registry's `invalid_fence.reasons`; templates a repair can clear name the read-only `gbrain repair fences` preview) and `fenceMessage`. Tests: `test/fence-repair-raw-rows.test.ts`, `test/fence-repair-reasons.test.ts`.+- `src/core/fence-repair/refusal.ts` — #6188 the one fence check coordinated writers share. `scanCanonicalFences` decides from the strict parsers what the canonical projection refuses (a repeated marker outside code, any parser warning, a row number used twice on the page) and locates each defect from the raw-row view (`raw-rows.ts`, `schema.ts`), never from parser warning strings, which embed row text; reasons and messages come from `reasons.ts` (`FENCE_REASONS`, `fenceMessage`, `issueLocation`). `fenceOperationError` is the typed refusal (`invalid_fence`, wire `invalid_params`, or `take_row_collision` for a stored-row collision). `fenceFailureDetail` is the bounded, versioned `error_detail.fence` a failed receipt keeps through compaction; `fenceReceiptLocation` reads a receipt back from that detail, the message grammar or an older release's exact message, and never from an arbitrary `invalid_params`. `completeFenceLocation` names the section of a legacy receipt from the refused bytes. `unparsedFenceRefusal` / `refuseUnparsedRewrite` (#6385 R12) turn a primitive's `FenceRewriteRefusal` into the typed `target_fence_malformed` located from the page, for the coordinated fact appends (`facts-prepare.ts`, `memory-prepare.ts`, `relink-publish.ts`) and the classic `writeFactsToFence` result. Tests: `test/fence-refusal.test.ts`, `test/fence-hold-surfaces.test.ts`, `test/persistence-sync-fence-holds.test.ts` (PGLite and Postgres).+- `src/core/fence-repair/{types,schema,raw-rows,reasons}.ts` — #6188 the shared fence vocabulary, all location-only. `types.ts`: `FenceIssue`, `FenceFix`, `FenceCtx`, `FenceReason`, `FixClass`. `schema.ts`: canonical columns (facts include `attributed_to`, #6385), accepted widths (facts 9/10/14/15, takes 6/7/13; `WIDE_WIDTH` is the typed layout, the 15-column `CANONICAL_HEADER.facts.attributed` the header rewrite emits when a header names `attributed_to`), header aliases, enum and kind synonym tables (exported for the format reference), cell validity. `raw-rows.ts`: `extractRawRows` reads each fence leniently (markers outside code, header map or positional fallback, cells with source spans, a row's identity is its ordinal); a row is `accepted` exactly when the strict parser returns it. `reasons.ts`: `FENCE_REASONS` (tier, auto-retry, actor, fix template, docs anchor per reason; the registry's `invalid_fence.reasons`; templates a repair can clear name the read-only `gbrain repair fences` preview) and `fenceMessage`. Tests: `test/fence-repair-raw-rows.test.ts`, `test/fence-repair-reasons.test.ts`.- `scripts/build-fence-format.ts` — #6188 renders the generated region of `docs/guides/fence-format.md` (between `BEGIN/END GENERATED fence-format`) from the fence constants: markers, the column tables and layouts from `schema.ts` (`COLUMNS`, `BASE_WIDTH`, `MIN_CELLS`, `CANONICAL_HEADER`, `ALLOWED`, `COLUMN_DEFAULTS`, `NAMED_COLUMNS`, `TOLERATED_TRAILING`, `HEADER_ALIASES`), holder outcomes computed with `isValidHolder`/`holderAlias`, the Tier 1 rule table from the synonym tables (bound to `FixClass` by `satisfies`), screen reasons grouped by tier and the gate table from `reasons.ts`. It parses both synthetic examples with the strict parsers and throws on any warning. `--check` exits 1 when the committed region is stale. Drift test: `test/fence-format-reference.test.ts` (the region, the examples, the reference's links, and one `fence-<reason>` row per reason in `write-refusals.md` with the reason table's tier and auto-retry and a link into the reference).- `src/core/fence-repair/{normalize,structure,content,rules,merge}.ts` — #6188 Tier 1. `normalizeFences(page, ctx)` returns a page that compiles plus location-only fixes and residual issues; a page whose fences compile comes back as the same object, and only edited cells, markers and headers change (no table is re-rendered). `structure.ts` merges first (below), closes a fence only when nothing but blank lines follows its last row and fixes two-dash takes markers; `content.ts` rewrites headers into canonical order with header-level defaults and renumbers prior-aware across both sections (`nextFreeRowNum`: above every fence and stored number; hidden rows never move); `rules.ts` holds the cell rules (kind map with the original word kept in `context`, enum and holder synonyms, percent confidence). `merge.ts` (#6377, `merge_fences`, clears `repeated_marker`): `mergePlan(raw, kind)` admits a section's N > 1 fences of a kind only when each is balanced with no near-miss marker, every header maps to the same canonical columns in the same order, every marker stands alone on its line, no row sits above a header and nothing but table lines sits inside any fence region (exactly N begin and N end markers outside code); it maps every before row (fence index, occurrence) to a merged occurrence or marks it `duplicateOf` a kept row when every cell but `#` is byte-equal as written (`rowKey`; only later fences' rows are dropped). `mergeEdits` appends the kept later rows after the primary's last table line, removes each later fence's marker lines and table, a heading line directly above it that repeats an earlier heading of the section, and collapses the blank lines around the block to one; the edit is kept only when `exposedLines` is empty. `mergeOrigins` tells the content pass each merged row's origin fence and before line (fixes and issues are reported at before-page lines, `beforeLine`), so `renumber` resolves a merged row's `superseded by #N` to its own before fence's row N (kept, or the kept row a dropped duplicate N equalled) and rewrites the reference to that row's final number (`renumber` fix on `context`/`source`); a reference from outside a merged fence keeps today's rule (any shared number it names is `superseded_ambiguous`). `mergePlans`/`mergedReceipt` re-derive the mapping from the before page for the validator and the receipt's `merged` entries. `safeNormalizeFences` turns a throw into residual `normalizer_failed`. Tests: `test/fence-repair-normalize.test.ts`, `test/fence-repair-fixtures.test.ts`, `test/fence-repair-merge.test.ts`.- `src/core/fence-repair/{validate,validate-cells,page-checks}.ts` — #6188 the one gate every tier's output passes before a write: (a) compiles, (e) row count and containment, (b) claims, (c) existing row numbers, (d) visibility only tightens, (f) per-row cell preservation with rule-produced changes only, (g) nothing the privacy boundary hid is shown; gates (b), (c), (e) and (f) read the raw-row view. Before rows pair with after rows by primary-fence occurrence; when `ctx.issues` carries a `merge_fences` fix for a section and kind (#6377) the pairing is the merge mapping re-derived from the before page (`mergePlans`; a named merge the before page does not admit fails (e)): (e) requires the after count to equal the kept count and each dropped row to equal its kept row as written (`rowKey`), (b), (d) and (f) run per mapped row, (c) skips dropped rows and numbers used twice across every before fence, and (f) compares a merged row that carries `superseded by #N` as if written with the after number of its own before fence's row N (`withFollowedRef`); any other reference change is a changed cell. `isFenceFixedPoint` is E14. `page-checks.ts` holds `strictFailures` (gate a, the projection's three checks) and `exposedLines` (gate g). Tests: `test/fence-repair-validate.test.ts`, `test/fence-repair-merge.test.ts`.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex ffa6d562fc..cdf97b4d80 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -11,7 +11,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/facts/extract.ts` — the LLM facts extractor (`extractFactsFromTurnWithOutcome` and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). Model: `resolveFactsExtractionModel(engine)` returns the model and the setting that chose it (`facts.extraction_model`, then the `resolveModelDetailed` chain on the `reasoning` tier); when nothing chose one and the tier's key-aware default resolved through Anthropic, `FACTS_EXTRACTION_MEASURED_DEFAULTS` substitutes `anthropic:claude-haiku-5-5` (source `measured_default`; the facts-absorb quality gate, gbrain-evals `docs/benchmarks/2026-10-08-facts-extraction-model.md`), and `gbrain models` reports that row through the same resolver. `getFactsExtractionModel` is its string wrapper. Deterministic junk gate: `isJunkFact(text, kind?)` tests `JUNK_FACT_PATTERNS` — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified `commitment` is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is a genuine commitment); meta-narration and provider-error strings are junk for every kind. `isJunkFilterEnabled(engine)` is the config kill switch (fail-open on a config read error); `getFactsExtractionPromptAppendix` supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become `entity_slug`): `isUnknownSpeakerLabel` (anonymous diarizer labels — `Speaker A`, `SPEAKER_00`, `spk_0`, `other|unknown|guest`) and `isNullLikeEntity` (placeholder STRINGS `"null"`/`"None"`/`"n/a"` where the prompt asked for JSON null; shared with `write-single.ts`) both null the attribution and KEEP the fact, so no consumer can mint `entity_slug='null'` through the resolver's fallback slugify. The provider-error arm is start-anchored (`^\W*`, optional error/status token or a `<step> stopped|failed because …` prefix, then `(spend|rate) (limit|cap) … (hit|exceeded|reached)`), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: `facts.extraction_prompt_appendix` (non-empty text is appended to the extraction prompt) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on), plus the opt-in `facts.extraction_missing_confidence` (stored when confidence is missing, null or non-numeric; unset keeps 1.0). A numeric-string confidence (`"0.3"`) is read as the stated value; unknown kinds are still stored as `fact` but counted in a stderr warning. Every extractor `chat()` call (first attempt, the #2113 truncation retry, the malformed-output retry) carries `responseSchema: FACTS_EXTRACTION_SCHEMA` (mirrors `RawExtracted`: `facts[]` of `{fact, kind ∈ ALL_EXTRACT_KINDS}` plus `entity/confidence/notability/metric/value/unit/period` — EVERY property in `required`, the optional ones nullable via type unions, `additionalProperties: false` at both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's default `strict: true`); the gateway honors it only on openai-compatible recipes that declare structured outputs (Ollama's server-side grammar), so small local models cannot emit malformed JSON, while `parseExtractorJsonDetailed` still validates the reply text on every lane. Pinned by `test/facts-extract-structured-output.test.ts`.-- `src/core/facts/forget.ts` — `forgetFactInFence(engine, id, {reason?, sourceId?, worldOnly?, supersededBy?})` checks source and visibility before inspecting state, then commits a durable withdrawal through `facts/withdrawal.ts`. With `supersededBy: { rowNum }` (the `writeSingleFact` supersession path) it only expires the row and strikes it with a page-local `#N` supersession reference: no withdrawal, so the old claim stays rememberable and no other page is invalidated. A writable source fence is atomically struck with a date and reason; otherwise the DB-body mirror is best-effort. Both paths remain withdrawn on stale reimport while the withdrawal database is preserved. The file resolver and per-page lock match fence writes. The body-only mirror deliberately leaves a hash mismatch so the next import re-chunks. Forget is retraction, not deletion of original prose, files or backups. `strikeFenceRow` and `supersededFact` are exported for the S9 checked supersede (`facts/proposal-supersede.ts`). Pinned by `test/forget-reconcile-durability.test.ts`, `test/privacy-strip-and-forget.test.ts`, and `test/e2e/delegated-grants-withdrawal.test.ts`.+- `src/core/facts/forget.ts` — `forgetFactInFence(engine, id, {reason?, sourceId?, worldOnly?, supersededBy?})` checks source and visibility before inspecting state, then commits a durable withdrawal through `facts/withdrawal.ts`. With `supersededBy: { rowNum }` (the `writeSingleFact` supersession path) it only expires the row and strikes it with a page-local `#N` supersession reference: no withdrawal, so the old claim stays rememberable and no other page is invalidated. A writable source fence is atomically struck with a date and reason; otherwise the DB-body mirror is best-effort. Both paths remain withdrawn on stale reimport while the withdrawal database is preserved. The file resolver and per-page lock match fence writes. The body-only mirror deliberately leaves a hash mismatch so the next import re-chunks. Forget is retraction, not deletion of original prose, files or backups. `strikeFenceRow` and `supersededFact` are exported for the S9 checked supersede (`facts/proposal-supersede.ts`). `strikeFenceRow` returns null for a fence that parses with warnings (#6385 R12), so forget falls back to the DB-only expire and the file keeps the rows the parser could not read. Pinned by `test/forget-reconcile-durability.test.ts`, `test/privacy-strip-and-forget.test.ts`, and `test/e2e/delegated-grants-withdrawal.test.ts`.- `src/core/facts/phantom-audit.ts` — JSONL audit at `${resolveAuditDir()}/phantoms-YYYY-Www.jsonl`. Pattern copy of `src/core/audit-slug-fallback.ts` (ISO-week rotation, honors `GBRAIN_AUDIT_DIR`). Exports `logPhantomEvent(record)` + `readRecentPhantomEvents(days)` + `computePhantomAuditFilename(now?)`. Records every outcome: `redirected | ambiguous | drift | no_canonical | not_phantom_has_residue | pass_skipped_lock_busy`. Best-effort writes — stderr warn on failure, never throws. Separate file from `stub-guard-audit.ts` (distinct consumer + lifecycle: stub-guard logs PREVENTIVE blocks; phantom-audit logs CLEANUP decisions, to be read by a future `phantoms_pending` doctor check).diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 4c3c3330f9..b45ab5a20c 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -99,10 +99,10 @@ rejection of serve-only flags before a brain opens.- `src/core/extraction-review.ts` — Extraction quarantine lane markers, sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).-- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`; a confidence cell outside 0..1 or not a plain number is `FACTS_TABLE_MALFORMED`, a `claim_value` cell parses strictly (plain/scientific numbers, `1,234,567` separators, a leading currency symbol, a k/M/B suffix that scales; anything else such as `1,5` or `0.9abc` is `FACTS_TABLE_MALFORMED`), `formatFenceDate` writes UTC-midnight dates as `YYYY-MM-DD` and any other instant as a UTC timestamp so TTLs and write-time `valid_from` round-trip, so the page is non-authoritative instead of failing the DB CHECK), render (`renderFactsTable`), and strip (`stripFactsFence({keepVisibility})` — the remote-read privacy boundary `get_page`/`fetch_page`/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: `replaceOrInsertFactsFence(body, fenceBlock)` replaces an existing fence in place or inserts a fresh `## Facts` section ABOVE the timeline sentinel (`timelineSentinelOffset`, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (`upsertFactRow`, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. `restoreHiddenFactRows(incoming, existing)` is the row-level, visibility-aware merge `import-file.ts` applies per fence-bearing column (compiled_truth AND timeline) when a remote caller writes back a page it read with hidden rows stripped — without it, a remote get→edit→put round-trip would silently drop every non-`world` fact row. Rules: only non-`world` rows of the existing fence are restoration candidates (a caller's deletion of a VISIBLE row stays honored — world rows are never restored); a hidden row whose rowNum is absent from the incoming fence is restored at its stable rowNum (cross-page `#F<N>` refs survive); a rowNum collision (a caller-authored addition landing on a hidden number the caller never saw) keeps the hidden row's number and renumbers the CALLER's row onto fresh appended numbers (upsertFactRow's append-only contract); same rowNum + same claim keeps the incoming version (idempotent full-content write-throughs); either side parsing with warnings returns null — re-rendering a fence that didn't fully parse would drop the caller's unparsed rows — and `factsGapWarning` surfaces exactly that residual loss. Pure and side-effect-free. Pinned by `test/facts-fence.test.ts` + the remote write-back describes in `test/privacy-strip-and-forget.test.ts` (row-level merge, world-only deletion honored, timeline-embedded fence round-trip).+- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`; #6385: cells are read by the column the header names (`factsHeaderLayout`, `FACTS_FENCE_COLUMNS`), so an unknown, repeated or missing required header column is one `FACTS_TABLE_MALFORMED` and no rows, a header in canonical order keeps the positional typed tail, and `factsRowProblem` lets a row leave off only trailing optional columns and refuses a non-empty cell past the layout; a confidence cell outside 0..1 or not a plain number is `FACTS_TABLE_MALFORMED`, a `claim_value` cell parses strictly (plain/scientific numbers, `1,234,567` separators, a leading currency symbol, a k/M/B suffix that scales; anything else such as `1,5` or `0.9abc` is `FACTS_TABLE_MALFORMED`), `formatFenceDate` writes UTC-midnight dates as `YYYY-MM-DD` and any other instant as a UTC timestamp so TTLs and write-time `valid_from` round-trip, so the page is non-authoritative instead of failing the DB CHECK), render (`renderFactsTable`), and strip (`stripFactsFence({keepVisibility})` — the remote-read privacy boundary `get_page`/`fetch_page`/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: `replaceOrInsertFactsFence(body, fenceBlock)` replaces an existing fence in place or inserts a fresh `## Facts` section ABOVE the timeline sentinel (`timelineSentinelOffset`, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (`upsertFactRow`, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. `upsertFactRow` throws `FenceRewriteRefusal` (fence-shared.ts) when the fence it starts from parses with warnings (#6385 R12): it re-renders the parsed rows, so a rewrite would delete the rows the parser skipped. `restoreHiddenFactRows(incoming, existing)` is the row-level, visibility-aware merge `import-file.ts` applies per fence-bearing column (compiled_truth AND timeline) when a remote caller writes back a page it read with hidden rows stripped — without it, a remote get→edit→put round-trip would silently drop every non-`world` fact row. Rules: only non-`world` rows of the existing fence are restoration candidates (a caller's deletion of a VISIBLE row stays honored — world rows are never restored); a hidden row whose rowNum is absent from the incoming fence is restored at its stable rowNum (cross-page `#F<N>` refs survive); a rowNum collision (a caller-authored addition landing on a hidden number the caller never saw) keeps the hidden row's number and renumbers the CALLER's row onto fresh appended numbers (upsertFactRow's append-only contract); same rowNum + same claim keeps the incoming version (idempotent full-content write-throughs); either side parsing with warnings returns null — re-rendering a fence that didn't fully parse would drop the caller's unparsed rows — and `factsGapWarning` surfaces exactly that residual loss. Pure and side-effect-free. Pinned by `test/facts-fence.test.ts` + the remote write-back describes in `test/privacy-strip-and-forget.test.ts` (row-level merge, world-only deletion honored, timeline-embedded fence round-trip).- `src/core/facts/attribution.ts` — speaker attribution's one dedup rule: `attributionCompatible(a, b)` is false only for two different known speakers (`user`, `assistant`, `other`); NULL (no recorded speaker) is compatible with either. Every dedup path applies it before candidate limits: `findCandidateDuplicates` (`attributedTo` option, SQL pre-limit), `decideSingleFact` exact and cosine matches, capture exact/near matches, hot-memory collapse (`collapseHotFacts` splits a fingerprint group by speaker when it holds two), fence reindex (`duplicateActiveFenceRows`) and the managed batch key (`facts-prepare.ts`). `facts.attributed_to` (migration v215) is written by the extractor (`facts.attribution`, default on per `docs/eval/decisions/p2-e3-heldout/`; `false` opts out), carried in the fence's 15th cell (only on rows that have it), returned by `recall` and hot memory, rendered `(assistant said)` in context packs, and kept out of `consolidate` (takes are the user's own). Pinned by `test/facts/speaker-attribution.test.ts`.-- `src/core/fence-shared.ts` — shared pipe-table primitives for the `## Takes` (`takes-fence.ts`) and `## Facts` (`facts-fence.ts`) fences: `parseRowCells`, `isSeparatorRow`, `stripStrikethrough`, `parseStringCell`, `escapeFenceCell`. `parseRowCells` is escape-aware: `\|` stays inside its cell and decodes back to a literal `|` (exact inverse of `escapeFenceCell`), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. Pinned by the escape cases in `test/facts-fence.test.ts` + the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.+- `src/core/fence-shared.ts` — shared pipe-table primitives for the `## Takes` (`takes-fence.ts`) and `## Facts` (`facts-fence.ts`) fences: `parseRowCells`, `isSeparatorRow`, `stripStrikethrough`, `parseStringCell`, `escapeFenceCell`, and the rewrite guard (#6385 R12) `assertFenceRewritable` / `FenceRewriteRefusal` that `upsertFactRow`, `upsertTakeRow`, `supersedeRow` and `mergePhantomFenceRows` throw when their input fence parses with warnings (the message names the fence only; the warnings, which embed row text, stay on the error). `parseRowCells` is escape-aware: `\|` stays inside its cell and decodes back to a literal `|` (exact inverse of `escapeFenceCell`), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. Pinned by the escape cases in `test/facts-fence.test.ts` + the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. In `inferLinkType` a per-edge verb counts only when it belongs to the link being typed (`attachedVerb`: a match with another link between it and this one, or written immediately before another link, is that link's), then precedence founded > invested_in > advises > works_at decides; `joined [X] as <role>` reads as works_at. `attendanceEvidenceRanges` accepts an `Attendees:`/`Participants:` line (plain or bold) and a `## Attendees`/`## Participants` link-list section (`Participants` since gbrain-evals N12-6, with a `LINK_EXTRACTOR_VERSION_TS` bump so meeting pages re-extract). Markdown links, bare-slug prose refs, and slash-shaped wikilinks match ANY dir-shaped path (`ANY_DIR_SEGMENT`), not a directory whitelist — nonexistent targets are dropped by the persist paths' page-existence checks (`resolveCandidateSources`, put_page's allSlugs filter, `addLinksBatch` INNER JOINs) and counted as `skippedMissingTarget` in the extract summaries; the `DIR_PATTERN` whitelist is only the typed fast-path for pass-2b wikilinks (non-whitelisted `[[dir/...]]` get an equivalent direct typed candidate in pass 2c, plus the flag-gated suffix rescue for non-exact matches). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEntityRefs`); `EntityRef.needsResolution: true` tags refs from this pass (the ref's `slug` is the wikilink TARGET, `name` the optional display alias). `SlugResolver` gains optional `resolveBasenameMatches(name): Promise<string[]>` (multi-match by design — emits one edge per matching page). The single shared basename matcher is `buildBasenameIndex(slugs)` + `queryBasenameIndex(index, name)` + `normalizeBasename` (keys raw/lower/slugified tail, stable-sorted shorter-first then lexical), used by `makeResolver`, the FS `resolveBasenameMatchesFromSlugs`, AND the doctor check so they cannot drift. `makeResolver` step 1 falls back to `resolveSlugWithAlias` (rename aliases) for a slug-shaped value with no live page; its fuzzy title step and live keyword step (source-scoped) accept a person/company/fund/organization candidate only under `sameEntityName`, so a near-name stays unresolved instead of linking to a different entity (`test/entity-resolution-near-names.test.ts`). With `link_resolution.global_basename` on, `extractFrontmatterLinks` passes `resolve(name, dirHint, { globalBasename, selfSlug })`, and a unique basename match (self excluded) resolves right after the exact steps and before the fuzzy and live keyword steps, the exact-name-first precedence of `resolveEntitySlug` (#5749, `test/link-resolution-basename-before-search.test.ts`). `makeResolver(engine, {mode, sourceId})` builds the index lazily via `engine.getAllSlugs({sourceId})` — source-scoped so a bare `[[name]]` never resolves to a same-tail page in a different source. `extractPageLinks` gains `opts.globalBasename` (routes `needsResolution` refs through `resolveBasenameMatches` keyed on `ref.slug`, emits candidates tagged `linkType: 'wikilink_basename'` + `linkSource: 'wikilink-resolved'`, skips self-loops) and `opts.skipFrontmatter`. All three surfaces (FS extract, DB extract, `put_page` auto-link) tag provenance with `link_source='wikilink-resolved'`; `put_page` includes it in its reconcilable-edge set so stale basename edges are removed when the wikilink or the flag goes away. Exports `WIKILINK_BASENAME_LINK_TYPE` + `isGlobalBasenameEnabled(engine)` (resolution order: env `GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME` → DB config `link_resolution.global_basename` → default false). `gbrain doctor`'s `link_resolution_opportunity` check surfaces a paste-ready enable hint when ≥5 bare wikilinks would resolve AND ≥20% match. Migration v113 widens `links_link_source_check` to admit `'wikilink-resolved'`; v114 then opens it to any kebab-case provenance (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, ≤64 chars) so external derivers register their own tag (e.g. `citation-graph`) without a migration. `LINK_EXTRACTOR_VERSION_TS` also lives here (bump like `CHUNKER_VERSION` to invalidate prior extract-stale stamps). Pinned by `test/link-extraction.test.ts`, `test/extract-fs.test.ts`, `test/doctor.test.ts`, `test/e2e/global-basename-pglite.test.ts`. #6191: `inferLinkType` applies `link-target-roles.ts` `targetTakesVerb` to every per-edge and fallback verb: `works_at` never types a link to a person, meeting, calendar-event, media, image or transcript target (unknown type: a `people/`, `meetings/`, `calendar/`, `cal/` slug), `founded`/`invested_in` never a temporal or media one; a refused verb keeps scanning lower-precedence rules, then `mentions` (`test/link-type-target-guard.test.ts`).diff --git a/docs/guides/fence-format.md b/docs/guides/fence-format.mdindex 9782260882..9bddff0271 100644--- a/docs/guides/fence-format.md+++ b/docs/guides/fence-format.md@@ -34,7 +34,7 @@ A facts fence sits between `<!--- gbrain:facts:begin -->` and `<!--- gbrain:fact<a id="facts-columns"></a>## Facts columns-Facts cells are read by position.+Facts cells are read by the column the header names, in any order. A header with a column that is not one of these names, a column named twice, or no column for a row that cannot be left off reads no rows: the fence is held until it is repaired (the repair maps the [header spellings](#header-spellings) and the order). A header in canonical order may be shorter than its rows: the cells after it keep their canonical position. A row may leave off only trailing columns marked below, and a cell past the last column must be empty.| Position | Column | Values | May be left off the row end | Default when the header lacks it | Meaning || --- | --- | --- | --- | --- | --- |@@ -52,6 +52,7 @@ Facts cells are read by position.| 12 | `claim_value` | a number, optionally with 1,234 separators or a k/M/B suffix | yes | - | Value of a typed claim. || 13 | `claim_unit` | free text | yes | - | Unit (`USD`, `people`, ...), or empty. || 14 | `claim_period` | free text | yes | - | Period (`monthly`, `annual`, ...), or empty. |+| 15 | `attributed_to` | `user`, `assistant`, `other` | yes | - | Who asserted the claim, or empty. |<a id="facts-layouts"></a>- **Narrow, 10 cells** (what gbrain writes unless a row needs a wide column):@@ -68,6 +69,13 @@ Facts cells are read by position.|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|--------------|-------------|------------|--------------|```+- **Attributed, 15 cells** (adds `attributed_to`; written when a row records who asserted it, and rows without it may stop at 14 cells):++ ```text+ | # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period | attributed_to |+ |---|-------|------|------------|------------|------------|------------|-------------|--------|---------|--------------|-------------|------------|--------------|---------------|+ ```+- **Shortest row, 9 cells:** the narrow row without `context`. A row that is short anywhere else is `short_row`.<a id="takes-columns"></a>diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex a59a1fc1a7..329d73efe0 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -338,7 +338,7 @@ clears or retries it with no one acting.| <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. | `-` | no | Move the fence out of the code, or delete the fence to remove its rows. Format: [markers](fence-format.md#markers). || <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`). | `-` | no | Renumber the new row, or add the stored take back to the fence. Format: [row numbers](fence-format.md#row-numbers). || <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. | `-` | yes | Repair the fence so it parses (`gbrain repair fences --source <source>` previews it); the withdrawn row then stays withdrawn. Format: [examples](fence-format.md#examples). |-| <a id="fence-target_fence_malformed"></a>`target_fence_malformed` | A verb that appends to or edits a page (`remember`, `extract_facts`, `takes_*`, `facts relink`, `edit_page`) found that page's stored fence does not parse and cannot be normalized in the same write (`edit_page` and the other takes writes never normalize). Memory verbs keep their v1 code (`invalid_params`, `detail: invalid_fence`). | `-` | yes | The maintenance run repairs the stored fence; to do it now, `gbrain repair fences --slug <slug>` on the brain host. Or read the page, fix the named fence (or write the whole page with `put_page`, which normalizes what it can and names every row it cannot), then retry with a new request_id. Format: [examples](fence-format.md#examples). |+| <a id="fence-target_fence_malformed"></a>`target_fence_malformed` | A verb that appends to or edits a page (`remember`, `extract_facts`, `takes_*`, `facts relink`, `edit_page`) found that page's stored fence does not parse and cannot be normalized in the same write (`edit_page` and the other takes writes never normalize). A fact write that would re-render a facts fence the parser reads with warnings (a malformed row, or a header naming a column outside the facts schema) refuses the same way, so the skipped rows are never dropped. Memory verbs keep their v1 code (`invalid_params`, `detail: invalid_fence`). | `-` | yes | The maintenance run repairs the stored fence; to do it now, `gbrain repair fences --slug <slug>` on the brain host. Or read the page, fix the named fence (or write the whole page with `put_page`, which normalizes what it can and names every row it cannot), then retry with a new request_id. Format: [examples](fence-format.md#examples). || <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. | `-` | yes | 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. Format: [what gbrain never guesses](fence-format.md#never-guessed). || <a id="fence-normalizer_failed"></a>`normalizer_failed` | The normalizer or its validator failed on this fence (a gbrain bug); the fence was not rewritten. A coordinated write refuses; a legacy import stores the page as written. | `manual` | no | Run `gbrain doctor --json` and report it with the gbrain version; an upgrade re-screens the file. Format: [what gbrain fixes](fence-format.md#normalized). || <a id="fence-llm_unavailable"></a>`llm_unavailable` | The repair model timed out, was rate-limited or returned a server error. | `llm` | yes | Nothing to do: the next maintenance run (or `gbrain repair fences --apply`) retries. Format: [tiers](fence-format.md#never-guessed). |diff --git a/scripts/build-fence-format.ts b/scripts/build-fence-format.tsindex 76a28df436..bca636787d 100644--- a/scripts/build-fence-format.ts+++ b/scripts/build-fence-format.ts@@ -21,7 +21,7 @@ import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, isValidHolder, parseTakesFence } frimport {ALLOWED, BASE_WIDTH, BRAIN_ALIASES, CANONICAL_HEADER, COLUMN_DEFAULTS, COLUMNS, FACT_KIND_SYNONYMS, FACTS_COLUMNS,HEADER_ALIASES, MIN_CELLS, NAMED_COLUMNS, NOTABILITY_SYNONYMS, PRIVATE_SYNONYMS, TAKE_KIND_SYNONYMS, TAKES_COLUMNS,- TOLERATED_TRAILING, appendOriginalKind, confidenceFormat, holderAlias,+ TOLERATED_TRAILING, WIDE_WIDTH, appendOriginalKind, confidenceFormat, holderAlias,} from '../src/core/fence-repair/schema.ts';import { FENCE_REASON_CODES, FENCE_REASONS, GATE_REASONS } from '../src/core/fence-repair/reasons.ts';import type { FenceKind, FenceTier, FixClass, GateLetter } from '../src/core/fence-repair/types.ts';@@ -50,6 +50,7 @@ const FACTS_TEXT: Record<(typeof FACTS_COLUMNS)[number], string> = {claim_value: 'Value of a typed claim.',claim_unit: 'Unit (`USD`, `people`, ...), or empty.',claim_period: 'Period (`monthly`, `annual`, ...), or empty.',+ attributed_to: 'Who asserted the claim, or empty.',};const TAKES_TEXT: Record<(typeof TAKES_COLUMNS)[number], string> = {@@ -134,7 +135,8 @@ function columnTable(kind: FenceKind): string {function layouts(kind: FenceKind): string {const all = COLUMNS[kind];const dropped = all.slice(MIN_CELLS[kind], BASE_WIDTH[kind]);- const wide = all.slice(BASE_WIDTH[kind]);+ const wide = all.slice(BASE_WIDTH[kind], WIDE_WIDTH[kind]);+ const { attributed, attributedSep } = CANONICAL_HEADER[kind];return [`- **Narrow, ${BASE_WIDTH[kind]} cells** (what gbrain writes unless a row needs a wide column):`,'',@@ -143,13 +145,22 @@ function layouts(kind: FenceKind): string {` ${CANONICAL_HEADER[kind].narrowSep}`,' ```','',- `- **Wide, ${all.length} cells** (adds ${codes(wide)}):`,+ `- **Wide, ${WIDE_WIDTH[kind]} cells** (adds ${codes(wide)}):`,'',' ```text',` ${CANONICAL_HEADER[kind].wide}`,` ${CANONICAL_HEADER[kind].wideSep}`,' ```','',+ ...(attributed && attributedSep ? [+ `- **Attributed, ${all.length} cells** (adds ${codes(all.slice(WIDE_WIDTH[kind]))}; written when a row records who asserted it, and rows without it may stop at ${WIDE_WIDTH[kind]} cells):`,+ '',+ ' ```text',+ ` ${attributed}`,+ ` ${attributedSep}`,+ ' ```',+ '',+ ] : []),`- **Shortest row, ${MIN_CELLS[kind]} cells:** the narrow row without ${codes(dropped)}. A row that is short anywhere else is \`short_row\`.`,].join('\n');}@@ -228,7 +239,7 @@ export function renderFenceFormatRegion(): string {'<a id="facts-columns"></a>','## Facts columns','',- 'Facts cells are read by position.',+ 'Facts cells are read by the column the header names, in any order. A header with a column that is not one of these names, a column named twice, or no column for a row that cannot be left off reads no rows: the fence is held until it is repaired (the repair maps the [header spellings](#header-spellings) and the order). A header in canonical order may be shorter than its rows: the cells after it keep their canonical position. A row may leave off only trailing columns marked below, and a cell past the last column must be empty.','',columnTable('facts'),'',diff --git a/src/core/cycle/phantom-redirect-managed.ts b/src/core/cycle/phantom-redirect-managed.tsindex 9b06987766..e4d7febc88 100644--- a/src/core/cycle/phantom-redirect-managed.ts+++ b/src/core/cycle/phantom-redirect-managed.ts@@ -45,7 +45,11 @@ export async function redirectManagedPhantom(engine: BrainEngine, page: Page, caconst [dbMax] = await engine.executeRaw<{ n: number | string | null }>('SELECT MAX(row_num) AS n FROM facts WHERE source_id = $1 AND source_markdown_slug = $2', [sourceId, canonical]);- const merged = mergePhantomFenceRows(target.page.compiled_truth, parseFactsFence(page.compiled_truth ?? '').facts, Number(dbMax?.n ?? 0));+ // #6385 R12: a fence that parses with warnings would lose its skipped rows, the phantom's with the deleted page and the canonical's in the re-render.+ const phantomFence = parseFactsFence(page.compiled_truth ?? '');+ if (phantomFence.warnings.length > 0) return drift('phantom facts fence does not parse cleanly');+ if (parseFactsFence(target.page.compiled_truth).warnings.length > 0) return drift('canonical facts fence does not parse cleanly');+ const merged = mergePhantomFenceRows(target.page.compiled_truth, phantomFence.facts, Number(dbMax?.n ?? 0));if (merged.body !== null && parseFactsFence(merged.body).warnings.length > 0) return drift('rendered fence failed re-parse');const outcome = await submitMaintenanceIntent(engine, authority, canonical, {kind: 'managed_maintenance_phantom_merge', expected_revision: target.revision,diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.tsindex bfbb3604c9..1f81f3bb1c 100644--- a/src/core/cycle/phantom-redirect.ts+++ b/src/core/cycle/phantom-redirect.ts@@ -52,6 +52,7 @@ import {type ParsedFact,} from '../facts-fence.ts';import { locateOutsideCode } from '../fence-scan.ts';+import { assertFenceRewritable } from '../fence-shared.ts';import { parseMarkdown, splitBody, serializeMarkdown } from '../markdown.ts';import { tryAcquireDbLock, syncLockId, type DbLockHandle } from '../db-lock.ts';import { isAborted } from '../abort-check.ts';@@ -243,6 +244,8 @@ function appendPhantomFenceRowsToCanonical(* The canonical body with the phantom's rows appended (null when every row* dedups onto an existing canonical row) and the phantom -> canonical row* number map. Shared by the file writer above and the managed redirect.+ * Throws `FenceRewriteRefusal` when the canonical fence does not parse+ * cleanly; the pass records the phantom as `drift` and moves nothing.*/export function mergePhantomFenceRows(body: string,@@ -250,7 +253,10 @@ export function mergePhantomFenceRows(dbMaxRowNum: number,): { body: string | null; renumber: Map<number, number> } {const renumber = new Map<number, number>();- const { facts: existingFacts } = parseFactsFence(body);+ const parsed = parseFactsFence(body);+ // Re-rendering a canonical fence the parser skipped rows of would delete them.+ assertFenceRewritable('facts', parsed);+ const existingFacts = parsed.facts;// Dedup key combines claim + valid_from. We deliberately do NOT include// valid_until or status in the key so that a "fact about Alice" already@@ -527,6 +533,18 @@ export async function tryRedirectPhantom(return { outcome: 'drift', canonical };}+ // Only parsed rows move and the phantom is then deleted, so a phantom fence+ // the parser skipped rows of would lose them: leave it for a person.+ if (parseFactsFence(page.compiled_truth ?? '').warnings.length > 0) {+ logPhantomEvent({+ phantom_slug: page.slug,+ outcome: 'drift',+ source_id: sourceId,+ reason: 'phantom facts fence does not parse cleanly',+ });+ return { outcome: 'drift', canonical };+ }+// D10: dry-run preview — no FS / DB / audit writes.if (dryRun) return { outcome: 'redirected', canonical };diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.tsindex 46f0358d32..b84f59b62a 100644--- a/src/core/facts-fence.ts+++ b/src/core/facts-fence.ts@@ -46,6 +46,7 @@ import {stripStrikethrough,parseStringCell,escapeFenceCell,+ assertFenceRewritable,} from './fence-shared.ts';import { findLineOutsideFencedCode, locateOutsideCode, protectedRegions, unclosedCodeFenceStart } from './fence-scan.ts';@@ -166,6 +167,47 @@ function parseNumericCell(raw: string): number | undefined | null {return Number.isFinite(n) ? n : null;}+/** #6385: the facts columns in canonical order (`#` is the row number), as the header names them. */+export const FACTS_FENCE_COLUMNS = [+ '#', 'claim', 'kind', 'confidence', 'visibility', 'notability', 'valid_from', 'valid_until', 'source', 'context',+ 'claim_metric', 'claim_value', 'claim_unit', 'claim_period', 'attributed_to',+] as const;+export type FactsFenceColumn = typeof FACTS_FENCE_COLUMNS[number];+/** Columns a header may leave out, and a row may omit at its end. */+export const FACTS_OPTIONAL_COLUMNS: ReadonlySet<string> = new Set(['context', 'claim_metric', 'claim_value', 'claim_unit', 'claim_period', 'attributed_to']);++/**+ * #6385: the column each cell of a row is read as, from the header cells, or+ * why the header cannot be read. Every header cell must name a facts column+ * once, and every required column must be named. A header in canonical order+ * is a prefix of the canonical layout, so cells past it keep their canonical+ * meaning (a 14-cell typed row under the 10-column header); any other header+ * is the whole layout.+ */+export function factsHeaderLayout(headerCells: readonly string[]): { layout: FactsFenceColumn[]; named: number } | { problem: string } {+ const names = headerCells.map(cell => cell.trim().toLowerCase());+ const seen = new Set<string>();+ for (const name of names) {+ if (!(FACTS_FENCE_COLUMNS as readonly string[]).includes(name)) return { problem: `unsupported header column "${name}"` };+ if (seen.has(name)) return { problem: `duplicate header column "${name}"` };+ seen.add(name);+ }+ const missing = FACTS_FENCE_COLUMNS.find(column => !FACTS_OPTIONAL_COLUMNS.has(column) && !seen.has(column));+ if (missing) return { problem: `header has no "${missing}" column` };+ const canonical = names.every((name, i) => name === FACTS_FENCE_COLUMNS[i]);+ return { layout: canonical ? [...FACTS_FENCE_COLUMNS] : names as FactsFenceColumn[], named: names.length };+}++/**+ * #6385: why a row cannot be read under a header layout, or null. A row may+ * omit only trailing optional columns the header names; cells past the+ * layout must be empty, since a value there has no column to mean.+ */+export function factsRowProblem(layout: readonly FactsFenceColumn[], named: number, cells: readonly string[]): 'short' | 'extra' | null {+ if (cells.slice(layout.length).some(cell => cell.trim())) return 'extra';+ return layout.slice(cells.length, named).some(column => !FACTS_OPTIONAL_COLUMNS.has(column)) ? 'short' : null;+}+function parseSupersededByFromContext(context: string | undefined): number | undefined {if (!context) return undefined;const m = context.match(/superseded by #(\d+)/i);@@ -206,6 +248,8 @@ export function parseFactsFence(body: string): FactsFenceParseResult {const lines = inner.split('\n');const facts: ParsedFact[] = [];let sawHeader = false;+ let layout: FactsFenceColumn[] = [];+ let named = 0;const seenRowNums = new Set<number>();for (let i = 0; i < lines.length; i++) {@@ -214,11 +258,20 @@ export function parseFactsFence(body: string): FactsFenceParseResult {const cells = parseRowCells(line);if (!cells) continue;- // Header row: cells include 'claim' and 'kind' (case-insensitive).+ // Header row: cells include 'claim' and 'kind' (case-insensitive). #6385:+ // cells are then read by the column the header names, so a header this+ // parser cannot map reads no rows (a rewrite refuses; the repair lane+ // maps aliases and order).if (!sawHeader) {const lower = cells.map(c => c.toLowerCase());if (lower.includes('claim') && lower.includes('kind')) {sawHeader = true;+ const header = factsHeaderLayout(cells);+ if ('problem' in header) {+ warnings.push(`FACTS_TABLE_MALFORMED: ${header.problem}`);+ return { facts: [], warnings };+ }+ ({ layout, named } = header);continue;}warnings.push(`FACTS_TABLE_MALFORMED: row before header: "${line.trim()}"`);@@ -228,29 +281,25 @@ export function parseFactsFence(body: string): FactsFenceParseResult {// Separator row (just dashes/colons) — skip.if (isSeparatorRow(cells)) continue;- // Expect 10 cells (legacy 10-cell fence) OR 14 cells (v0.35.4- // typed-claim wide fence): row_num, claim, kind, confidence,- // visibility, notability, valid_from, valid_until, source, context,- // [claim_metric, claim_value, claim_unit, claim_period].- // Tolerate 9 (missing trailing context cell) — markdown editors often- // drop empty trailing cells.- if (cells.length < 9) {+ // A row may drop trailing optional cells (markdown editors often drop an+ // empty trailing context); a required cell or a value past the layout is+ // a malformed row.+ const shape = factsRowProblem(layout, named, cells);+ if (shape === 'short') {warnings.push(`FACTS_TABLE_MALFORMED: only ${cells.length} cells in row "${line.trim()}"`);continue;}+ if (shape === 'extra') {+ warnings.push(`FACTS_TABLE_MALFORMED: ${cells.length} cells in row "${line.trim()}", more than its ${layout.length} columns`);+ continue;+ }- const [- rowNumStr, claimRaw, kindRaw, confidenceRaw,- visibilityRaw, notabilityRaw,- validFromRaw, validUntilRaw,- sourceRaw,- contextRaw = '',- claimMetricRaw = '',- claimValueRaw = '',- claimUnitRaw = '',- claimPeriodRaw = '',- attributedToRaw = '',- ] = cells;+ const cell = (column: FactsFenceColumn): string => cells[layout.indexOf(column)] ?? '';+ const rowNumStr = cell('#'), claimRaw = cell('claim'), kindRaw = cell('kind'), confidenceRaw = cell('confidence');+ const visibilityRaw = cell('visibility'), notabilityRaw = cell('notability');+ const validFromRaw = cell('valid_from'), validUntilRaw = cell('valid_until'), sourceRaw = cell('source'), contextRaw = cell('context');+ const claimMetricRaw = cell('claim_metric'), claimValueRaw = cell('claim_value'), claimUnitRaw = cell('claim_unit');+ const claimPeriodRaw = cell('claim_period'), attributedToRaw = cell('attributed_to');const rowNum = parseInt(rowNumStr, 10);if (!Number.isFinite(rowNum) || rowNum <= 0) {@@ -536,7 +585,8 @@ export function factsGapWarning(** Append-only — row_num is set to (max existing rowNum in the fence) + 1.* Stable forever, so cross-page refs like `<slug>#F<N>` keep pointing at- * the same row.+ * the same row. Throws `FenceRewriteRefusal` when the existing fence does+ * not parse cleanly: re-rendering it would drop the rows the parser skipped.*/export function upsertFactRow(body: string,@@ -545,7 +595,9 @@ export function upsertFactRow(active?: boolean;},): { body: string; rowNum: number } {- const { facts } = parseFactsFence(body);+ const parsed = parseFactsFence(body);+ assertFenceRewritable('facts', parsed);+ const { facts } = parsed;const nextRowNum = newRow.rowNum?? (facts.length > 0 ? Math.max(...facts.map(f => f.rowNum)) + 1 : 1);diff --git a/src/core/facts/forget.ts b/src/core/facts/forget.tsindex 7f1d56a665..c53a3d24ff 100644--- a/src/core/facts/forget.ts+++ b/src/core/facts/forget.ts@@ -73,11 +73,13 @@ export function supersededFact(fact: ParsedFact, today: string, newRowNum: numbe* Strike fence row `rowNum` inside `body` with `strike` (strikethrough,* valid_until = today, and a withdrawal or supersession marker in context,* preserving existing context). Returns the rewritten body, or null when the- * fence lacks the row (DB drifted from markdown) or its markers — callers- * fall back to a DB-only expire.+ * fence lacks the row (DB drifted from markdown), its markers, or does not+ * parse cleanly (re-rendering it would drop the rows the parser skipped) —+ * callers fall back to a DB-only expire and the bytes stay as they are.*/export function strikeFenceRow(body: string, rowNum: number, strike: (fact: ParsedFact) => ParsedFact): string | null {const parsed = parseFactsFence(body);+ if (parsed.warnings.length > 0) return null;const 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);diff --git a/src/core/facts/relink-publish.ts b/src/core/facts/relink-publish.tsindex 4095baa283..2d6b41d9c8 100644--- a/src/core/facts/relink-publish.ts+++ b/src/core/facts/relink-publish.ts@@ -34,6 +34,7 @@ import { decideSingleFact } from './single-prepare.ts';import { isFactWithdrawn } from './withdrawal.ts';import { appendContextNote } from './subject-infer.ts';import { normalizeTargetFences } from '../fence-repair/import-step.ts';+import { refuseUnparsedRewrite } from '../fence-repair/refusal.ts';import { pageFencesNormalized } from '../fence-repair/report.ts';export const RELINK_OPERATION = 'relink_facts';@@ -186,7 +187,9 @@ export async function prepareRelinkMutation(engine: BrainEngine, row: WriteRequeconst v = link.value;const rowNum = next++;rowNums.set(link.id, rowNum);- body = upsertFactRow(body, fenceRow(v, rowNum, appendContextNote(v.context as string | null, byId.get(link.id)!.note))).body;+ // #6385 R12: a fence that does not parse cleanly refuses typed (`fence_malformed` below) instead of losing rows.+ body = refuseUnparsedRewrite({ compiled_truth: body, timeline }, row.slug, row.source_id,+ () => upsertFactRow(body, fenceRow(v, rowNum, appendContextNote(v.context as string | null, byId.get(link.id)!.note))).body);}}const page = links.length ? await (await import('../persistence/page-prepare.ts')).preparePageMutation(engine, { ...row, intent: {diff --git a/src/core/fence-repair/content.ts b/src/core/fence-repair/content.tsindex f23ccad218..52cfad682b 100644--- a/src/core/fence-repair/content.ts+++ b/src/core/fence-repair/content.ts@@ -21,7 +21,7 @@ import { parseTakesFence } from '../takes-fence.ts';import type { MergeOrigins } from './merge.ts';import { planRowRules, type CellText, type RowPlan } from './rules.ts';import { extractRawRows, rowNumOf, type RawFence, type RawRow, type RawSection } from './raw-rows.ts';-import { ALLOWED, BASE_WIDTH, canonicalColumn, CANONICAL_HEADER, collapse, COLUMN_DEFAULTS, COLUMNS, supersededRef } from './schema.ts';+import { ALLOWED, BASE_WIDTH, canonicalColumn, CANONICAL_HEADER, collapse, COLUMN_DEFAULTS, COLUMNS, supersededRef, WIDE_WIDTH } from './schema.ts';import { headerlessMisfit } from './stray-cells.ts';import { applyEdits, fenceBlocked, type Edit } from './structure.ts';import type { FenceCtx, FenceFix, FenceIssue, FenceKind, FenceReason, FenceSection } from './types.ts';@@ -149,7 +149,9 @@ function takesShaped(fence: RawFence): boolean {function planRewrite(fence: RawFence): Rewrite {const { kind } = fence;const wide = fence.columns.some(c => c !== null && COLUMNS[kind].indexOf(c) >= BASE_WIDTH[kind]);- const target = COLUMNS[kind].slice(0, wide ? COLUMNS[kind].length : BASE_WIDTH[kind]);+ // #6385: a header naming a column past the typed layout (facts `attributed_to`) keeps it.+ const width = fence.columns.some(c => c !== null && COLUMNS[kind].indexOf(c) >= WIDE_WIDTH[kind]) ? COLUMNS[kind].length : wide ? WIDE_WIDTH[kind] : BASE_WIDTH[kind];+ const target = COLUMNS[kind].slice(0, width);const defaults = Object.keys(COLUMN_DEFAULTS[kind]).filter(c => !fence.columns.includes(c));return { target, defaults };}@@ -288,11 +290,13 @@ function emitFence(pass: Pass, work: FenceWork): void {function emitRewrite(pass: Pass, fence: RawFence, rewrite: Rewrite): void {const header = fence.header!;- const wide = rewrite.target.length > BASE_WIDTH[fence.kind];const text = CANONICAL_HEADER[fence.kind];- pass.edits[fence.section].push({ start: header.start, end: header.end, text: wide ? text.wide : text.narrow });+ const width = rewrite.target.length;+ const [headerText, sepText] = width > WIDE_WIDTH[fence.kind] ? [text.attributed!, text.attributedSep!]+ : width > BASE_WIDTH[fence.kind] ? [text.wide, text.wideSep] : [text.narrow, text.narrowSep];+ pass.edits[fence.section].push({ start: header.start, end: header.end, text: headerText });const sep = fence.separators.find(s => s.line === header.line + 1);- if (sep) pass.edits[fence.section].push({ start: sep.start, end: sep.end, text: wide ? text.wideSep : text.narrowSep });+ if (sep) pass.edits[fence.section].push({ start: sep.start, end: sep.end, text: sepText });const at = { fence: fence.kind, section: fence.section, row: null, line: header.line };pass.fixes.push({ ...at, column: null, class: 'header_alias' });for (const column of rewrite.defaults) pass.fixes.push({ ...at, column, class: 'column_default' });diff --git a/src/core/fence-repair/llm.ts b/src/core/fence-repair/llm.tsindex 7ec86120ac..fb8f9b31d7 100644--- a/src/core/fence-repair/llm.ts+++ b/src/core/fence-repair/llm.ts@@ -39,7 +39,7 @@ import { thinkingOffControl, thinkingOffMaxOutputTokens } from '../ai/thinking-oimport { isSeparatorRow, parseRowCells } from '../fence-shared.ts';import { sectionsOf } from './page-checks.ts';import { extractRawRows, primaryFence, type RawFence, type RawRow } from './raw-rows.ts';-import { ALLOWED, BASE_WIDTH, CANONICAL_HEADER, COLUMNS, COLUMN_DEFAULTS } from './schema.ts';+import { ALLOWED, BASE_WIDTH, CANONICAL_HEADER, COLUMNS, COLUMN_DEFAULTS, WIDE_WIDTH } from './schema.ts';import { FENCE_REASON_CODES, FENCE_REASONS, GATE_REASONS } from './reasons.ts';import type { FenceIssue, FenceKind, FencePage, FenceReason, FenceSection, GateLetter } from './types.ts';@@ -132,7 +132,8 @@ function headerOf(req: Pick<Tier3Request, 'kind' | 'layout'>): { header: string;}function vocabulary(kind: FenceKind): string {- return Object.entries(ALLOWED[kind]).filter(([column]) => column !== '#').map(([column, values]) => `- ${column}: ${values.join(', ')}`).join('\n');+ // The Tier 3 layouts end at the typed columns, so a column past them (facts `attributed_to`) is not offered.+ return Object.entries(ALLOWED[kind]).filter(([column]) => column !== '#' && COLUMNS[kind].indexOf(column) < WIDE_WIDTH[kind]).map(([column, values]) => `- ${column}: ${values.join(', ')}`).join('\n');}const GATE_TEXT: Record<GateLetter, string> = {@@ -233,7 +234,7 @@ export function extractSingleTable(text: string, req: Pick<Tier3Request, 'kind'if (lines.some(line => !line.startsWith('|')) || lines.length < 2) return { ok: false, reason: 'llm_malformed' };const headerCells = parseRowCells(lines[0]!)?.map(cell => cell.trim().toLowerCase()).join('|');const sepCells = parseRowCells(lines[1]!);- const layout = (['narrow', 'wide'] as const).find(width => headerCells === COLUMNS[req.kind].slice(0, width === 'wide' ? COLUMNS[req.kind].length : BASE_WIDTH[req.kind]).join('|'));+ const layout = (['narrow', 'wide'] as const).find(width => headerCells === COLUMNS[req.kind].slice(0, width === 'wide' ? WIDE_WIDTH[req.kind] : BASE_WIDTH[req.kind]).join('|'));if (!layout || !sepCells || !isSeparatorRow(sepCells)) return { ok: false, reason: 'llm_malformed' };const rows = lines.slice(2);if (rows.some(row => parseRowCells(row) === null || isSeparatorRow(parseRowCells(row)!))) return { ok: false, reason: 'llm_malformed' };diff --git a/src/core/fence-repair/normalize.ts b/src/core/fence-repair/normalize.tsindex 4ed8a5f997..84786ab612 100644--- a/src/core/fence-repair/normalize.ts+++ b/src/core/fence-repair/normalize.ts@@ -23,7 +23,7 @@ import { structuralPass } from './structure.ts';import type { FenceCtx, FenceFix, FenceIssue, FencePage, FenceSection, StoredRowMap } from './types.ts';/** Rule-set version; bump when a rule widens. It is part of the hold `fence_version` (`FENCE_VERSION`), so older holds are re-screened. */-export const FENCE_RULES_VERSION = 3;+export const FENCE_RULES_VERSION = 4;export interface NormalizeResult<T extends FencePage> {page: T;diff --git a/src/core/fence-repair/raw-rows.ts b/src/core/fence-repair/raw-rows.tsindex b48651bb8d..afe4dd024e 100644--- a/src/core/fence-repair/raw-rows.ts+++ b/src/core/fence-repair/raw-rows.ts@@ -14,7 +14,7 @@* `accepted` replays the strict parser on the same region, so a row is* accepted exactly when `parseFactsFence` / `parseTakesFence` would return it.*/-import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, factsHeaderLayout, factsRowProblem, type FactsFenceColumn } from '../facts-fence.ts';import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';import { indexOfOutsideCode, scanMarkdownCode, type MarkdownCodeMap } from '../fence-scan.ts';import { isSeparatorRow } from '../fence-shared.ts';@@ -300,8 +300,10 @@ function setHeader(fence: RawFence, header: RawRow): void {seen.add(column);return column;});- // A header shorter than the narrowest row the parser reads leaves whole columns absent.- fence.needsRewrite = !fence.strictHeader || !canonicalOrder(kind, fence.columns) || fence.columns.length < MIN_CELLS[kind];+ // A header shorter than the narrowest row the parser reads leaves whole columns absent;+ // a facts header cell with no canonical name (or a repeated one) is never read by position (#6385).+ fence.needsRewrite = !fence.strictHeader || !canonicalOrder(kind, fence.columns) || fence.columns.length < MIN_CELLS[kind]+ || (kind === 'facts' && fence.columns.some(c => c === null));}/** The header puts every column the strict parser reads by position at its canonical position. */@@ -350,6 +352,8 @@ function rowShape(fence: RawFence, row: RawRow): RawRow['shape'] {// Facts rows of 14 cells are the typed layout even under a narrow header.const layoutMax = kind === 'facts' && row.cells.length === 14 ? 14 : Math.max(headerLen, BASE_WIDTH[kind]);const allValid = [...row.byColumn].every(([column, cell]) => cellValid(kind, column, cell.text));+ // A facts cell past the canonical layout has no column to mean (#6385).+ if (kind === 'facts' && row.extra.some(cell => cell.text.trim())) return 'extra_cells';return row.cells.length > layoutMax && !allValid ? 'extra_cells' : 'ok';}if (row.cells.length > headerLen) return 'extra_cells';@@ -357,8 +361,8 @@ function rowShape(fence: RawFence, row: RawRow): RawRow['shape'] {return missing.every(c => TOLERATED_TRAILING[kind].has(c)) ? 'ok' : 'short_row';}-/** Cells the strict parsers reject a row for, with their positions (takes holders only warn). */-const FACTS_CHECKED: ReadonlyArray<[string, number]> = [['kind', 2], ['visibility', 4], ['notability', 5], ['confidence', 3], ['claim_value', 11]];+/** Cells the strict parsers reject a row for (takes holders only warn); facts by header column (#6385), takes by position. */+const FACTS_CHECKED: readonly FactsFenceColumn[] = ['kind', 'visibility', 'notability', 'confidence', 'claim_value', 'attributed_to'];const TAKES_CHECKED: ReadonlyArray<[string, number]> = [['kind', 2], ['weight', 4]];/** Replay the strict parser over the region: which rows it returns. */@@ -367,14 +371,33 @@ function markAccepted(fence: RawFence, pipeLines: RawRow[]): void {const { kind } = fence;const seen = new Set<number>();let sawHeader = false;+ let layout: FactsFenceColumn[] = [];+ let named = 0;for (const row of pipeLines) {- if (!sawHeader) { sawHeader = strictHeaderCells(row); continue; }+ if (!sawHeader) {+ sawHeader = strictHeaderCells(row);+ if (sawHeader && kind === 'facts') {+ const header = factsHeaderLayout(row.cells.map(c => c.text));+ if ('problem' in header) return;+ ({ layout, named } = header);+ }+ continue;+ }const texts = row.cells.map(c => c.text);- if (isSeparatorRow(texts) || texts.length < MIN_CELLS[kind]) continue;+ if (isSeparatorRow(texts)) continue;+ if (kind === 'facts') {+ if (factsRowProblem(layout, named, texts)) continue;+ const cell = (column: FactsFenceColumn) => texts[layout.indexOf(column)] ?? '';+ const rowNum = parseRowNum(cell('#'));+ if (rowNum === null || seen.has(rowNum)) continue;+ seen.add(rowNum);+ row.accepted = FACTS_CHECKED.every(column => cellValid('facts', column, cell(column)));+ continue;+ }+ if (texts.length < MIN_CELLS[kind]) continue;const rowNum = parseRowNum(texts[0]!);if (rowNum === null || seen.has(rowNum)) continue;seen.add(rowNum);- const checked = kind === 'facts' ? FACTS_CHECKED : TAKES_CHECKED;- row.accepted = checked.every(([column, at]) => cellValid(kind, column, texts[at] ?? ''));+ row.accepted = TAKES_CHECKED.every(([column, at]) => cellValid(kind, column, texts[at] ?? ''));}}diff --git a/src/core/fence-repair/refusal.ts b/src/core/fence-repair/refusal.tsindex dea57e6f7d..01c8845569 100644--- a/src/core/fence-repair/refusal.ts+++ b/src/core/fence-repair/refusal.ts@@ -16,6 +16,7 @@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 { FenceRewriteRefusal } from '../fence-shared.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';@@ -61,7 +62,7 @@ const at = (reason: FenceReason, fence: FenceKind, section: FenceSection, 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']],+ facts: [['kind', 'enum_unmapped'], ['visibility', 'enum_unmapped'], ['notability', 'enum_unmapped'], ['confidence', 'confidence_out_of_range'], ['claim_value', 'claim_value_invalid'], ['attributed_to', 'enum_unmapped']],takes: [['kind', 'takes_kind_unsupported'], ['weight', 'weight_missing']],};@@ -110,6 +111,8 @@ function warningReasons(warning: string): readonly FenceReason[] {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 (/^\d+ cells in row /.test(rest)) return ['extra_cells'];+ if (/^(unsupported|duplicate) header column |^header has no /.test(rest)) return ['header_unmapped', 'takes_in_facts'];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'];@@ -329,3 +332,24 @@ export function targetFenceRefusal(location: FenceMessageLocation, slug: string,if (issues.length) error.fenceIssues = issues.slice(0, 20);return error;}++/**+ * #6385 R12: the refusal of a write whose target page's `fence` does not+ * parse cleanly, so the fence rewrite it needs would drop the rows the parser+ * skipped. Typed `invalid_fence` / `target_fence_malformed`, located from the+ * page like every other fence refusal.+ */+export function unparsedFenceRefusal(page: { compiled_truth: string; timeline?: string | null }, fence: FenceKind, slug: string, sourceId: string): OperationError {+ const defect = scanCanonicalFences(page).defects.find(d => d.fence === fence) ?? at('unparseable', fence, 'body', null);+ return targetFenceRefusal(defect, slug, sourceId);+}++/** Run a fence rewrite for a coordinated writer: a `FenceRewriteRefusal` becomes `unparsedFenceRefusal` for `page`. */+export function refuseUnparsedRewrite<T>(page: { compiled_truth: string; timeline?: string | null }, slug: string, sourceId: string, rewrite: () => T): T {+ try {+ return rewrite();+ } catch (error) {+ if (error instanceof FenceRewriteRefusal) throw unparsedFenceRefusal(page, error.fence, slug, sourceId);+ throw error;+ }+}diff --git a/src/core/fence-repair/schema.ts b/src/core/fence-repair/schema.tsindex a914077f69..d8c5d4bc4d 100644--- a/src/core/fence-repair/schema.ts+++ b/src/core/fence-repair/schema.ts@@ -14,7 +14,7 @@ import type { FenceKind } from './types.ts';export const FACTS_COLUMNS = ['#', 'claim', 'kind', 'confidence', 'visibility', 'notability', 'valid_from', 'valid_until', 'source', 'context',- 'claim_metric', 'claim_value', 'claim_unit', 'claim_period',+ 'claim_metric', 'claim_value', 'claim_unit', 'claim_period', 'attributed_to',] as const;export const TAKES_COLUMNS = ['#', 'claim', 'kind', 'who', 'weight', 'since', 'source', 'resolved', 'quality', 'evidence', 'value', 'unit', 'by',@@ -24,6 +24,8 @@ export const TAKES_COLUMNS = [export const COLUMNS: Record<FenceKind, readonly string[]> = { facts: FACTS_COLUMNS, takes: TAKES_COLUMNS };/** The narrow canonical layout (facts 10, takes 7); the wide one adds the remaining columns. */export const BASE_WIDTH: Record<FenceKind, number> = { facts: 10, takes: 7 };+/** The wide canonical layout (facts 14 typed columns, takes 13); a facts header that names `attributed_to` adds it as a 15th (#6385). */+export const WIDE_WIDTH: Record<FenceKind, number> = { facts: 14, takes: 13 };/** Fewest cells the strict parser reads (facts 9 = no context, takes 6 = no source). */export const MIN_CELLS: Record<FenceKind, number> = { facts: 9, takes: 6 };/** Columns read by header name rather than position (takes resolution columns). */@@ -33,7 +35,7 @@ export const NAMED_COLUMNS: Record<FenceKind, ReadonlySet<string>> = {};/** Columns a row may omit at its end and still parse. */export const TOLERATED_TRAILING: Record<FenceKind, ReadonlySet<string>> = {- facts: new Set(['context', 'claim_metric', 'claim_value', 'claim_unit', 'claim_period']),+ facts: new Set(['context', 'claim_metric', 'claim_value', 'claim_unit', 'claim_period', 'attributed_to']),takes: new Set(['source', 'resolved', 'quality', 'evidence', 'value', 'unit', 'by']),};/** Write defaults for a required facts column absent from the whole header (`column_default`, T6). */@@ -42,13 +44,18 @@ export const COLUMN_DEFAULTS: Record<FenceKind, Readonly<Record<string, string>>takes: {},};-/** Header and separator text exactly as `renderFactsTable` / `renderTakesFence` emit them. */-export const CANONICAL_HEADER: Record<FenceKind, { narrow: string; wide: string; narrowSep: string; wideSep: string }> = {+/**+ * Header and separator text exactly as `renderFactsTable` / `renderTakesFence` emit them; `attributed` is+ * the facts wide header with the `attributed_to` column (#6385), what the renderer writes when a row carries it.+ */+export const CANONICAL_HEADER: Record<FenceKind, { narrow: string; wide: string; narrowSep: string; wideSep: string; attributed?: string; attributedSep?: string }> = {facts: {narrow: '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',wide: '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period |',narrowSep: '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',wideSep: '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|--------------|-------------|------------|--------------|',+ attributed: '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period | attributed_to |',+ attributedSep: '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|--------------|-------------|------------|--------------|---------------|',},takes: {narrow: '| # | claim | kind | who | weight | since | source |',@@ -76,6 +83,7 @@ export const HEADER_ALIASES: Record<FenceKind, Readonly<Record<string, readonlyclaim_value: ['claim value', 'value'],claim_unit: ['claim unit', 'unit'],claim_period: ['claim period', 'period'],+ attributed_to: ['attributed_to'],},takes: {'#': ROW_NUM_ALIASES,@@ -121,6 +129,7 @@ export function canonicalColumn(kind: FenceKind, headerCell: string): string | nconst FACT_KINDS: ReadonlySet<string> = new Set(['event', 'preference', 'commitment', 'belief', 'fact', 'idea']);const VISIBILITIES: ReadonlySet<string> = new Set(['private', 'world']);const NOTABILITIES: ReadonlySet<string> = new Set(['high', 'medium', 'low']);+const ATTRIBUTIONS: ReadonlySet<string> = new Set(['user', 'assistant', 'other']);const PLAIN_NUMBER_RE = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;const NUMERIC_CELL_RE = /^([+-]?)[$€£]?((?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|\.\d+)((?:[eE][+-]?\d+)?)\s*([kmb]?)$/i;@@ -132,6 +141,7 @@ export const ALLOWED: Record<FenceKind, Readonly<Record<string, readonly string[notability: [...NOTABILITIES],confidence: ['a number from 0 to 1'],claim_value: ['a number, optionally with 1,234 separators or a k/M/B suffix'],+ attributed_to: [...ATTRIBUTIONS],'#': ['a positive whole number'],},takes: {@@ -158,6 +168,7 @@ export function cellValid(kind: FenceKind, column: string, text: string): booleacase 'notability': return NOTABILITIES.has(lower);case 'confidence': return confidenceValid(text);case 'claim_value': return !text.trim() || NUMERIC_CELL_RE.test(text.trim());+ case 'attributed_to': return !lower || ATTRIBUTIONS.has(lower);case 'takes:kind': return TAKE_KIND_VALUES.has(lower);case 'takes:who': return isValidHolder(text.trim());case 'takes:weight': return Number.isFinite(parseFloat(text));diff --git a/src/core/fence-repair/stray-cells.ts b/src/core/fence-repair/stray-cells.tsindex 2bd929a499..789a3bd8a1 100644--- a/src/core/fence-repair/stray-cells.ts+++ b/src/core/fence-repair/stray-cells.ts@@ -22,7 +22,7 @@*/import { extractRawRows, rowNumOf, type RawCell, type RawFence, type RawRow } from './raw-rows.ts';import { kindWord } from './rules.ts';-import { BASE_WIDTH, cellValid, COLUMNS } from './schema.ts';+import { BASE_WIDTH, cellValid, COLUMNS, WIDE_WIDTH } from './schema.ts';import { applyEdits, fenceBlocked, type Edit } from './structure.ts';import type { FenceFix, FenceKind, FenceSection } from './types.ts';@@ -57,17 +57,17 @@ export function headerlessMisfit(fence: RawFence, row: RawRow): 'claim_split' |const kindCell = row.cells[2]?.text.trim() ?? '';if (kindCell && !cellValid(kind, 'kind', kindCell) && !kindWord(kindCell)) return 'claim_split';const n = row.cells.length;- const fits = kind === 'facts' ? n <= BASE_WIDTH.facts || n === COLUMNS.facts.length : n <= BASE_WIDTH.takes;+ const fits = kind === 'facts' ? n <= BASE_WIDTH.facts || n === WIDE_WIDTH.facts : n <= BASE_WIDTH.takes;return fits || row.cells.every((cell, j) => columnValid(fence, kind, j, cell.text)) ? null : 'extra_cells';}/** The widths a row may be cut back to: the header's layout, or with no header the narrow layout (facts 14 for a wider row). */function layoutWidths(fence: RawFence, row: RawRow): Set<number> {const kind = fence.kind;- if (!fence.header) return new Set([kind === 'facts' && row.cells.length > COLUMNS.facts.length ? COLUMNS.facts.length : BASE_WIDTH[kind]]);+ if (!fence.header) return new Set([kind === 'facts' && row.cells.length > WIDE_WIDTH.facts ? WIDE_WIDTH.facts : BASE_WIDTH[kind]]);const headerLen = fence.columns.length;const widths = new Set([Math.max(headerLen, BASE_WIDTH[kind])]);- if (kind === 'facts' && headerLen < COLUMNS.facts.length && row.cells.length > COLUMNS.facts.length) widths.add(COLUMNS.facts.length);+ if (kind === 'facts' && headerLen < WIDE_WIDTH.facts && row.cells.length > WIDE_WIDTH.facts) widths.add(WIDE_WIDTH.facts);return widths;}diff --git a/src/core/fence-shared.ts b/src/core/fence-shared.tsindex 95591960aa..2ef45cb3a2 100644--- a/src/core/fence-shared.ts+++ b/src/core/fence-shared.ts@@ -100,3 +100,22 @@ export function parseStringCell(raw: string): string | undefined {export function escapeFenceCell(s: string): string {return s.replace(/\|/g, '\\|').replace(/\r\n?|\n/g, '<br>');}++/**+ * A fence rewrite refused because the fence it starts from does not parse+ * cleanly. Every rewriter re-renders the rows the parser returned, so+ * rewriting such a fence would silently delete the rows the parser skipped.+ * The message names the fence only: parser warnings embed row text, so they+ * stay on `warnings` for the caller to locate, never in the message.+ */+export class FenceRewriteRefusal extends Error {+ constructor(readonly fence: 'facts' | 'takes', readonly warnings: readonly string[]) {+ super(`The ${fence} fence does not parse cleanly, so it was not rewritten; fix the fence first.`);+ this.name = 'FenceRewriteRefusal';+ }+}++/** Throw `FenceRewriteRefusal` when the parse a rewrite starts from has warnings. */+export function assertFenceRewritable(fence: 'facts' | 'takes', parsed: { warnings: readonly string[] }): void {+ if (parsed.warnings.length > 0) throw new FenceRewriteRefusal(fence, parsed.warnings);+}diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex 321c7c7adf..812ddb3b9f 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -19,6 +19,7 @@ import type { WriteRequest } from './model.ts';import type { ManagedFactIntent, FrozenExtractedFact } from './facts-maintenance.ts';import { assertManagedFactsEmbedding } from './facts-maintenance.ts';import { normalizeTargetFences } from '../fence-repair/import-step.ts';+import { refuseUnparsedRewrite } from '../fence-repair/refusal.ts';import { fenceAppendPendingTier, withPendingFenceRows } from '../eligibility/fence-overlay.ts';import { withPageTierKept } from '../trust/fence-append.ts';import { pageFencesNormalized } from '../fence-repair/report.ts';@@ -164,12 +165,14 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writinput: derivedGateInput(taint.trust, row.id), cfg: gateCfg! }) : undefined;if (gate && gate.action !== 'insert') { blocked.push(gate); continue; }const rowNum = fact.entity_slug !== null && !fallback(fact) ? nextRow++ : undefined;- if (rowNum !== undefined) body = upsertFactRow(body, { rowNum, claim: fact.fact, kind: fact.kind, visibility: fact.visibility,+ // #6385 R12: an entity fence that does not parse cleanly refuses typed instead of losing the rows it skipped.+ if (rowNum !== undefined) body = refuseUnparsedRewrite({ compiled_truth: body, timeline: target!.page.timeline }, row.slug, row.source_id, () => upsertFactRow(body, {+ rowNum, claim: fact.fact, kind: fact.kind, visibility: fact.visibility,confidence: fact.confidence ?? 1, notability: fact.notability ?? 'medium', source: fact.source, context: fact.context ?? undefined,validFrom: formatFenceDate(fact.valid_from!), validUntil: fact.valid_until ? formatFenceDate(fact.valid_until) : undefined,claimMetric: fact.claim_metric ?? undefined, claimValue: fact.claim_value ?? undefined,claimUnit: fact.claim_unit ?? undefined, claimPeriod: fact.claim_period ?? undefined,- ...(fact.attributed_to ? { attributedTo: fact.attributed_to } : {}) }).body;+ ...(fact.attributed_to ? { attributedTo: fact.attributed_to } : {}) }).body);// Strike the superseded row in this page's fence, as the remember mutation does.if (supersedes && rowNum !== undefined && supersedes.source_markdown_slug === row.slug && supersedes.row_num != null) {body = replaceOrInsertFactsFence(body, renderFactsTable(parseFactsFence(body).facts.map(f => f.rowNum === Number(supersedes.row_num)diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 1c96ad4d9f..2ff584e10a 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -16,6 +16,7 @@ import type { WriteRequest } from './model.ts';import { appendContextNote, type InferredVia } from '../facts/subject-infer.ts';import { inferenceNote } from '../facts/subject-infer-write.ts';import { normalizeTargetFences } from '../fence-repair/import-step.ts';+import { refuseUnparsedRewrite } from '../fence-repair/refusal.ts';import { requestChannelTrust } from '../trust/channel.ts';import { gateField, gateInput, heldOutcome, loadWriteGateConfig } from '../trust/gate-outcomes.ts';import { decideFactWrite, recordFlaggedRow, recordWriteGateHold } from '../write-gate-store.ts';@@ -126,9 +127,10 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeconst target = await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: snapshot.page });if (target.fixes.length) fencesNormalized = { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: target.fixes,writer: row.principal_kind, path: snapshot.page.source_path ?? null, remote: row.authority.remote }) };- const appended = upsertFactRow(target.page.compiled_truth, { claim: input.fact, kind: input.kind, visibility: input.visibility,- confidence: 1, notability: 'medium', validFrom: formatFenceDate(validFrom),- validUntil: validUntil ? formatFenceDate(validUntil) : undefined, source: fact.source, context });+ // #6385 R12: an entity fence that does not parse cleanly refuses typed instead of losing the rows it skipped.+ const appended = refuseUnparsedRewrite(target.page, row.slug, row.source_id, () => upsertFactRow(target.page.compiled_truth, {+ claim: input.fact, kind: input.kind, visibility: input.visibility, confidence: 1, notability: 'medium', validFrom: formatFenceDate(validFrom),+ validUntil: validUntil ? formatFenceDate(validUntil) : undefined, source: fact.source, context }));rowNum = appended.rowNum;let body = appended.body;const old = decision.candidate;diff --git a/src/core/takes-fence.ts b/src/core/takes-fence.tsindex c05da84bf8..20b5284044 100644--- a/src/core/takes-fence.ts+++ b/src/core/takes-fence.ts@@ -238,6 +238,7 @@ import {isSeparatorRow,stripStrikethrough,escapeFenceCell as safeFenceCell,+ assertFenceRewritable,} from './fence-shared.ts';import { indexOfOutsideCode, locateOutsideCode, protectedRegions, unclosedCodeFenceStart } from './fence-scan.ts';@@ -518,16 +519,18 @@ function nextTakeRowNum(body: string): number {* reservation rows included (W9F item 4).** `claim`, `kind`, `holder` of the input are required; `weight` defaults- * to 0.5 if omitted; `active` defaults to true.+ * to 0.5 if omitted; `active` defaults to true. Throws `FenceRewriteRefusal`+ * when the existing fence does not parse cleanly (any warning), since the+ * rewrite would drop the rows the parser skipped.*/export function upsertTakeRow(body: string,newRow: Omit<ParsedTake, 'rowNum'> & { rowNum?: number },): { body: string; rowNum: number } {- const { takes, warnings, reservedRowNums } = parseTakesFence(body);- // Surface warnings to caller via an attached marker — caller decides what to do.- // (We don't throw here so writes proceed; doctor surfaces the underlying issue.)- void warnings;+ const parsed = parseTakesFence(body);+ // Re-rendering a fence the parser skipped rows of would delete them.+ assertFenceRewritable('takes', parsed);+ const { takes, reservedRowNums } = parsed;const nextRowNum = newRow.rowNum ?? nextTakeRowNum(body);const allRows: ParsedTake[] = [@@ -575,7 +578,8 @@ export function upsertTakeRow(* The new row takes `newRowNum` when given, else `nextFreeRowNum` over the* body (W9F item 4).*- * Throws when the target row is not found in the fence.+ * Throws when the target row is not found in the fence, and+ * `FenceRewriteRefusal` when the fence does not parse cleanly.*/export function supersedeRow(body: string,@@ -583,7 +587,9 @@ export function supersedeRow(replacement: Omit<ParsedTake, 'rowNum' | 'active'>,newRowNum: number = nextTakeRowNum(body),): { body: string; oldRowNum: number; newRowNum: number } {- const { takes, reservedRowNums } = parseTakesFence(body);+ const parsed = parseTakesFence(body);+ assertFenceRewritable('takes', parsed);+ const { takes, reservedRowNums } = parsed;const idx = takes.findIndex(t => t.rowNum === oldRowNum);if (idx === -1) {throw new Error(`supersedeRow: row #${oldRowNum} not found in takes fence`);diff --git a/test/facts-fence-header.test.ts b/test/facts-fence-header.test.tsnew file mode 100644index 0000000000..9ae28222a7--- /dev/null+++ b/test/facts-fence-header.test.ts@@ -0,0 +1,125 @@+/**+ * #6385: the facts fence reads each cell by the column its header names.+ * An unknown, repeated or missing required column reads no rows (so every+ * rewrite refuses and the repair lane maps the header), a reordered+ * canonical header reads correctly, and the row width is column-aware: only+ * trailing optional columns may be left off, and a cell past the layout must+ * be empty. Synthetic content only.+ */+import { describe, expect, test } from 'bun:test';+import {+ FACTS_FENCE_BEGIN as FB, FACTS_FENCE_END as FE, parseFactsFence, renderFactsTable, upsertFactRow, type ParsedFact,+} from '../src/core/facts-fence.ts';++const CANONICAL = ['#', 'claim', 'kind', 'confidence', 'visibility', 'notability', 'valid_from', 'valid_until', 'source', 'context',+ 'claim_metric', 'claim_value', 'claim_unit', 'claim_period'];+const ROW = ['1', 'Synthetic product launch', 'event', '1.0', 'private', 'high', '2026-01-01', '', 'synthetic-fixture', '', '', '', '', ''];+const line = (cells: readonly string[]) => `| ${cells.join(' | ')} |`;+const fence = (header: readonly string[], ...rows: Array<readonly string[]>) =>+ [FB, line(header), line(header.map(() => '---')), ...rows.map(line), FE].join('\n');++describe('the three cases from the issue', () => {+ test('an `event_type` 15th column reads no rows, whatever its value, and says which column', () => {+ for (const value of ['launch', 'user', '']) {+ const parsed = parseFactsFence(fence([...CANONICAL, 'event_type'], [...ROW, value]));+ expect(parsed.facts).toEqual([]);+ expect(parsed.warnings).toEqual(['FACTS_TABLE_MALFORMED: unsupported header column "event_type"']);+ }+ });++ test('an `attributed_to` 15th column is read as the speaker', () => {+ const parsed = parseFactsFence(fence([...CANONICAL, 'attributed_to'], [...ROW, 'user']));+ expect(parsed.warnings).toEqual([]);+ expect(parsed.facts.map(f => [f.claim, f.attributedTo])).toEqual([['Synthetic product launch', 'user']]);+ });+});++describe('header mapping', () => {+ test('a reordered canonical header reads every cell by its column', () => {+ const header = ['kind', 'claim', '#', 'source', 'visibility', 'confidence', 'notability', 'valid_from', 'valid_until', 'context'];+ const parsed = parseFactsFence(fence(header, ['preference', 'Prefers async updates', '7', 'chat', 'world', '0.8', 'low', '2026-02-01', '', 'standup']));+ expect(parsed.warnings).toEqual([]);+ expect(parsed.facts.map(f => [f.rowNum, f.claim, f.kind, f.confidence, f.visibility, f.notability, f.validFrom, f.source, f.context]))+ .toEqual([[7, 'Prefers async updates', 'preference', 0.8, 'world', 'low', '2026-02-01', 'chat', 'standup']]);+ });++ test('a takes-shaped header inside a facts fence is refused', () => {+ const parsed = parseFactsFence(fence(['#', 'claim', 'kind', 'who', 'weight', 'since', 'source'], ['1', 'Synthetic take', 'take', 'brain', '0.5', '2026-01', 'notes']));+ expect(parsed.facts).toEqual([]);+ expect(parsed.warnings).toEqual(['FACTS_TABLE_MALFORMED: unsupported header column "who"']);+ });++ test('a repeated column and a missing required column are refused', () => {+ const repeated = parseFactsFence(fence([...CANONICAL.slice(0, 10), 'source'], [...ROW.slice(0, 10), 'other']));+ expect([repeated.facts, repeated.warnings]).toEqual([[], ['FACTS_TABLE_MALFORMED: duplicate header column "source"']]);+ const header = CANONICAL.slice(0, 10).filter(c => c !== 'notability');+ const missing = parseFactsFence(fence(header, ROW.slice(0, 10).filter((_, i) => i !== 5)));+ expect([missing.facts, missing.warnings]).toEqual([[], ['FACTS_TABLE_MALFORMED: header has no "notability" column']]);+ });++ test('an alias the repair lane knows (`conf`) is not read by the strict parser', () => {+ const parsed = parseFactsFence(fence(CANONICAL.slice(0, 10).map(c => c === 'confidence' ? 'conf' : c), ROW.slice(0, 10)));+ expect([parsed.facts, parsed.warnings]).toEqual([[], ['FACTS_TABLE_MALFORMED: unsupported header column "conf"']]);+ });+});++describe('column-aware row width', () => {+ const reordered = ['claim', 'kind', 'confidence', 'visibility', 'notability', 'valid_from', 'valid_until', '#', 'context', 'source'];+ const cells = ['Reordered claim', 'fact', '1.0', 'private', 'medium', '2026-03-01', '', '4', 'ctx', 'call'];++ test('a row may leave off a trailing optional column, never a required one', () => {+ const optionalLast = ['claim', 'kind', 'confidence', 'visibility', 'notability', 'valid_from', 'valid_until', '#', 'source', 'context'];+ const ok = parseFactsFence(fence(optionalLast, ['Short context', 'fact', '1.0', 'private', 'medium', '2026-03-01', '', '4', 'call']));+ expect([ok.warnings, ok.facts.map(f => [f.rowNum, f.source, f.context])]).toEqual([[], [[4, 'call', undefined]]]);+ const short = parseFactsFence(fence(reordered, cells.slice(0, 9)));+ expect(short.facts).toEqual([]);+ expect(short.warnings).toHaveLength(1);+ expect(short.warnings[0]).toStartWith('FACTS_TABLE_MALFORMED: only 9 cells in row');+ });++ test('a non-empty cell past the layout refuses the row; an empty one is ignored', () => {+ const extra = parseFactsFence(fence(reordered, [...cells, 'stray']));+ expect(extra.facts).toEqual([]);+ expect(extra.warnings[0]).toMatch(/^FACTS_TABLE_MALFORMED: 11 cells in row .*, more than its 10 columns$/);+ const empty = parseFactsFence(fence(reordered, [...cells, '']));+ expect([empty.warnings, empty.facts.map(f => f.rowNum)]).toEqual([[], [4]]);+ const past = parseFactsFence(fence([...CANONICAL, 'attributed_to'], [...ROW, 'user', 'stray']));+ expect([past.facts, past.warnings.length]).toEqual([[], 1]);+ });++ test('under a canonical-order header the typed cells after it keep their canonical position (the 14-cell typed row)', () => {+ const parsed = parseFactsFence(fence(CANONICAL.slice(0, 10), ['1', 'ARR claim', 'fact', '1.0', 'private', 'high', '', '', 'board', '', 'arr', '2.5M', 'USD', 'annual']));+ expect(parsed.warnings).toEqual([]);+ expect(parsed.facts.map(f => [f.claimMetric, f.claimValue, f.claimUnit, f.claimPeriod])).toEqual([['arr', 2_500_000, 'USD', 'annual']]);+ });+});++describe('rewrites', () => {+ const base: ParsedFact = { rowNum: 1, claim: 'First claim', kind: 'fact', confidence: 1, visibility: 'private', notability: 'medium', active: true };++ test('render -> parse -> render is a fixed point for every layout', () => {+ for (const rows of [[base], [base, { ...base, rowNum: 2, claim: 'Typed', claimMetric: 'mrr', claimValue: 50000 }],+ [base, { ...base, rowNum: 2, claim: 'Said', attributedTo: 'assistant' as const }]]) {+ const once = renderFactsTable(rows);+ const parsed = parseFactsFence(once);+ expect(parsed.warnings).toEqual([]);+ expect(renderFactsTable(parsed.facts)).toBe(once);+ }+ });++ test('an append to a reordered fence keeps every cell of the existing row, written in canonical order', () => {+ const body = `# Page\n\n${fence(['kind', 'claim', '#', 'source', 'visibility', 'confidence', 'notability', 'valid_from', 'valid_until', 'context'],+ ['preference', 'Prefers async updates', '7', 'chat', 'world', '0.8', 'low', '2026-02-01', '', 'standup'])}\n`;+ const out = upsertFactRow(body, { claim: 'New claim', kind: 'fact', confidence: 1, visibility: 'private', notability: 'medium' });+ const parsed = parseFactsFence(out.body);+ expect(parsed.warnings).toEqual([]);+ expect(parsed.facts.map(f => [f.rowNum, f.claim, f.kind, f.confidence, f.visibility, f.notability, f.source, f.context]))+ .toEqual([[7, 'Prefers async updates', 'preference', 0.8, 'world', 'low', 'chat', 'standup'], [8, 'New claim', 'fact', 1, 'private', 'medium', undefined, undefined]]);+ });++ test('an append to a fence with an unsupported header column refuses instead of rewriting the header', () => {+ const body = fence([...CANONICAL, 'event_type'], [...ROW, 'user']);+ expect(() => upsertFactRow(body, { claim: 'New claim', kind: 'fact', confidence: 1, visibility: 'private', notability: 'medium' }))+ .toThrow(/facts fence does not parse cleanly/);+ });+});diff --git a/test/fence-repair-normalize.test.ts b/test/fence-repair-normalize.test.tsindex c2823383c4..234f648591 100644--- a/test/fence-repair-normalize.test.ts+++ b/test/fence-repair-normalize.test.ts@@ -300,6 +300,27 @@ describe('header rules', () => {expectRepaired(r);});+ test('#6385: a reordered, respelled 15-column header with attributed_to is rewritten to the attributed header, every cell kept', () => {+ const body = [FB, '| Claim | # | Kind | Confidence | Visibility | Notability | Valid From | Valid Until | Source | Context | Claim Metric | Claim Value | Claim Unit | Claim Period | Attributed To |',+ '|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|',+ '| Xi said | 3 | fact | 0.7 | private | low | 2026-05-01 | | chat | ctx | mrr | 50k | USD | monthly | user |',+ '| Xi plain | 4 | event | 1.0 | world | high | 2026-05-02 | | call | | | | | | |', FE].join('\n');+ const r = run(body);+ expect(classes(r)).toEqual(['header_alias']);+ expect(r.page.compiled_truth).toContain('| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period | attributed_to |');+ expect(r.page.compiled_truth).toContain('| 3 | Xi said | fact | 0.7 | private | low | 2026-05-01 | | chat | ctx | mrr | 50k | USD | monthly | user |');+ const parsed = parseFactsFence(r.page.compiled_truth);+ expect(parsed.facts.map(f => [f.rowNum, f.claim, f.attributedTo, f.claimValue])).toEqual([[3, 'Xi said', 'user', 50_000], [4, 'Xi plain', undefined, undefined]]);+ expectRepaired(r);+ });++ test('#6385: an `event_type` column is never mapped to attributed_to; it stays header_unmapped', () => {+ const header = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period | event_type |';+ const r = run([FB, header, '| 1 | Omicron launch | event | 1.0 | private | high | 2026-01-01 | | fixture | | | | | | user |', FE].join('\n'));+ expect(reasons(r)).toEqual(['header_unmapped']);+ expect(r.page.compiled_truth).toContain(header);+ });+test('column_default fills required facts columns absent from the whole header', () => {const body = [FB, '| # | claim | kind | source |', '|---|---|---|---|', '| 1 | Lambda two | fact | call |', FE].join('\n');const r = run(body);diff --git a/test/fence-repair-validate.test.ts b/test/fence-repair-validate.test.tsindex e4d16c48d9..19bc0c3296 100644--- a/test/fence-repair-validate.test.ts+++ b/test/fence-repair-validate.test.ts@@ -36,9 +36,9 @@ describe('a correct repair passes', () => {expect(check(BEFORE, page(facts(ROW1_FIXED, ROW2)), PRIVATE, 'deterministic')).toEqual({ ok: true });});- test('a page that compiles validates against itself, even under a header with an unmapped column name', () => {+ test('#6385: a header with an unmapped column name no longer compiles, so the page does not validate against itself (gate a)', () => {const odd = page(facts(ROW2).replace('| notability |', '| salience |'));- expect(check(odd, odd)).toEqual({ ok: true });+ expect(check(odd, odd)).toMatchObject({ ok: false, gate: 'a', reason: 'still_invalid' });});test('a close_fence repair passes', () => {