Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): redacted-facts reads segmented source pages through the segment reader and lists fenced rows on segmented pages (#7125)
garrytanff7c70fa15a7
diff --git a/docs/architecture/key-files/core-fence-repair.md b/docs/architecture/key-files/core-fence-repair.mdindex c0f26e3bd7..0127d406af 100644--- a/docs/architecture/key-files/core-fence-repair.md+++ b/docs/architecture/key-files/core-fence-repair.md@@ -17,3 +17,4 @@ The #6188 fence check that coordinated writers share, fence repair tiers, the ce- `src/core/fence-repair/{measured,model}.ts` — #6188 the Tier 3 eval's verdicts and the model they pick. `measured.ts`: `FENCE_REPAIR_MEASURED_MODELS` (the models that met the preregistered rule, best first) and `FENCE_REPAIR_MEASURED` (the behavior notice's accuracy sentence), updated together by the next eval. `model.ts`: `resolveFenceRepairModel(WithSource)`: an explicit `models.fence_repair` always (any model, priced or not); unset, the first measured model whose provider key the merged env has; else null (`no_measured_model`, a paid hold whose fix is `gbrain config set models.fence_repair <model>`). `gbrain models` reports the row through it (`measured default`). Tests: `test/repair-fences.test.ts`.- `src/core/fence-repair/{repair-io,receipt,uncommitted}.ts` — #6188 fence repair I/O. `loadFenceSource(engine, sourceId, { remote })`: managed owner root, or the `OwnerRefusal` row (`persistence/owner-refusal.ts`) that says why this host may not write it (a remote caller's row names no local path), legacy checkout, mirror flag, and the `RepairBusySet` (`persistence/repair-busy.ts`: in-flight writes plus the not-yet-admitted entries of every unfinished sync cursor, failing closed); an unfinished sync no longer marks the whole source busy. `writeFenceRepair` turns a `sync_in_progress` raised at the write's admission into `{ ok: false, reason: 'sync_in_progress' }`. `readFenceTarget`: a held or walked file from the checkout (UTF-8 only, confined, slug from the page by origin, hold or path) or the stored page; `spliceFileSections` puts the repaired sections back into the file by locating each changed line range with the fewest unique context lines and refuses unless the result parses back to exactly those sections. `writeFenceRepair`: managed → `submitManagedFileRepair` (bytes bound to the before-hash, page revision and publication digest; refused imports and canonical overlays are not written); legacy → confined path re-hashed (`changed_since_read`), backed up under `~/.gbrain/backups/fences/<run>/`, written, `importFromFile` (restored from the backup if it refuses), hold cleared, and an "uncommitted fence repair" notice (`uncommitted.ts`, op `fence-repair-uncommitted`, purge-exempt) with the exact `git add`/`git commit` step, dropped on read once the path is committed; db and mirror → a revision-bound `put_page` (mirror: database-only, hold cleared). Every write carries a `FenceRepairReceipt` (`receipt.ts`: actor `fence-repair`, tier, classes, rows, columns, model, before/after sha256, cost, and for a `merge_fences` repair `merged`: per merged fence and section the fence count and every before row as `{occurrence, from_fence, kept_as | duplicate_of}`, at most `MERGED_ROWS_MAX` rows, built by `mergedReceipt`; `parseFenceRepairReceipt` rejects anything malformed) and clears the census parts of the key. Tests: `test/repair-fences.test.ts`.- `src/core/fence-repair/attempts.ts` — #6188 attempt claims and the attempt memo for paid (Tier 3) fence repairs, one `op_checkpoints` row per candidate (op `fence-repair-attempt`) changed only by compare-and-swap on a record version: `claimed` → `dispatched` → `settled` → `published` | `rejected` | `transient`, at most one paid call plus one corrective re-ask per claim. A rejected or published memo (content sha256, model, fence rules version, prompt version) is not claimed again until one changes; transient failures do not consume it; an expired lease is taken over (a stale dispatch counts a crash, two reject the memo). Records carry location and reason codes and their source incarnation, so the purge keeps them while it lives. Tests: `test/fence-repair-attempts.test.ts` (+ Postgres e2e).+- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a host that may not write the source is skipped with the owner condition as its reason (`host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`; `owner_unavailable` is the fallback; the skip's detail carries `why`, the read-only fix and `retryable`), a candidate a write in flight or an unfinished sync's frozen manifest still names is `sync_in_progress` (#6278: checked at plan, at apply and again at the write's admission in `file-repair.ts`; the rest of the source repairs while the sync runs, and a held path is not busy); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, no measured model with a key and `models.fence_repair` unset → `no_measured_model`, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `resolveFenceRepairModel` (`fence-repair/model.ts`: `models.fence_repair`, else the first measured model with a key, else none). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 58a7e631b7..ffa83e1144 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -9,14 +9,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, replays a still-pending request with the ctx's CLI write wait, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.- `src/core/repair/conversation-labels.ts` — `gbrain repair conversation-labels`, explicit-only, preview-bound and destructive (consent payload from the registry's `consentText`). `classifyLabelFacts` (read-only) takes active per-segment extractor facts (`source` exactly `cli:extract-conversation-facts`) on live pages with a bold `METADATA_LABELS` line and classes each `excluded` (page outcome stamped with `extractor_version`, withdrawn, superseded, named by another fact's `superseded_by`, referenced by `open_loops.fact_id`), `evidenced` (context carries `segment 1970-01-01`) or `ambiguous`. The preview decides each page's outcome with the current parser at no cost (`non_extractable`, `awaiting_reextraction`, `cleaned`), hashes it all, saves one approved item per page and prints the capped hand-off (`extract-conversation-facts --slugs … --dry-run`, then `--max-cost-usd`). The apply expires the approved ids still as previewed (appending `retired: conversation-labels <hash>` to the context), expires the completion marker and writes the stamped not-extractable outcome for a page still at the previewed parser input; approved pages apply in batches of `LABEL_BATCH_PAGES` (25): one database-only `managed_maintenance_conversation_label_retire` request per batch on `LABELS_ANCHOR_SLUG` on a managed brain (`prepareConversationLabelRetirement`, every page key locked, each page rechecked), one transaction per batch otherwise. No model calls. Segmented pages are not classified (the label filter reads the body columns): their unstamped per-segment facts are counted as `segmented_pages` / `segmented_facts` and named in a warning. `countLabelFacts` is doctor `conversation_label_facts`' bounded count. Pinned by `test/repair-conversation-labels.test.ts` (+ Postgres arm) and `test/conversation-facts-retained-history.test.ts`.- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).-- `src/core/repair/redacted-facts.ts` — `gbrain repair redacted-facts` (#7125), explicit-only and preview-bound. `classifyRedactedFacts` (read-only) takes active facts whose text holds a redaction marker and runs `restoreNeutralized` (`think/sanitize.ts`, with the pre-fix `LEGACY_EVAL_SHELL` shape) against the page the fact's context names and the page holding it (`readPageSnapshot` body + timeline, then up to 50 `page_versions` bodies): `evidenced` when every proving text proves the same restoration, `ambiguous` (`conflicting_sources`) when a text holds two spans around the words or texts disagree, `unproven` (`no_source_page` / `not_in_source`) otherwise. The preview hashes every candidate with its restoration and saves one approved item per page; the apply reclassifies each fact, rewrites database-only rows through one database-only `managed_maintenance_restore_redacted_facts` request per page on a managed brain (`prepareRedactedFactsRestore`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain (exact-text compare-and-set; context gets `restored: redacted-facts repair`), and rewrites fenced rows' claims in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection replaces the row. Pinned by `test/repair-redacted-facts.test.ts` (+ Postgres arm).+- `src/core/repair/redacted-facts.ts` — `gbrain repair redacted-facts` (#7125), explicit-only and preview-bound. `classifyRedactedFacts` (read-only) takes active facts whose text holds a redaction marker and runs `restoreNeutralized` (`think/sanitize.ts`, with the pre-fix `LEGACY_EVAL_SHELL` shape) against the page the fact's context names and the page holding it (`pageTexts`: an inline page's body + timeline, a segmented page's body through `readBodyRange` up to 16 MiB, then up to 50 `page_versions` bodies): `evidenced` when every proving text proves the same restoration, `ambiguous` (`conflicting_sources`) when a text holds two spans around the words or texts disagree, `unproven` (`no_source_page` / `not_in_source`) otherwise. A proved fenced row on a segmented page is `segmented` (`segmented_page`): listed with its restoration, never rewritten (`restoreFencedRows` reads and publishes inline bodies only). The preview hashes every candidate with its restoration and saves one approved item per page; the apply reclassifies each fact, rewrites database-only rows through one database-only `managed_maintenance_restore_redacted_facts` request per page on a managed brain (`prepareRedactedFactsRestore`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain (exact-text compare-and-set; context gets `restored: redacted-facts repair`), and rewrites fenced rows' claims in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection replaces the row. Pinned by `test/repair-redacted-facts.test.ts` (+ Postgres arm).- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id, and `file_database_drift` (W4.11) when its last replay attempt was refused `source_changed` and the page has not been written since (`lastFailedAttempt`; the detail and an apply's `file_database_drift` outcome name `gbrain sources reconcile <source> <slug> --preview`; `test/repair-failed-writes-drift-w411.test.ts`); owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969). The superseded / already-written / duplicate rule lives in `persistence/terminal-classify.ts`, shared with the #6650 terminal-failure readers.- `src/core/repair/ontology-facts.ts` — `gbrain repair ontology-facts` (#6264), explicit-only and preview-bound (`--apply --expect <hash>`). `classifyOntologyFacts` (read-only; also doctor `ontology_facts_fenced`) takes ontology rows (`dimension IS NOT NULL`) carrying the pre-fix fence step's signature, a `row_num` or a `source_markdown_slug` that differs from `source` (`mergeOntologyFact` writes them equal and never sets `row_num`), and classes each `fenced` or `retired`, or excluded as `withdrawn` (`fact_withdrawals`), `consolidated` or `duplicate` (restoring would collide with the ontology dedup key). The apply sets `row_num` NULL, `source_markdown_slug = source` and `expired_at` NULL in one statement that rechecks row number, page, expiry and the dedup key (`changed_since_preview` otherwise), through `coordinatedDatabaseWrite('ontology_propose')` on the entity and page keys on a managed brain or one maintenance transaction otherwise; the withdrawal trigger re-expires a claim forgotten after the preview (`withdrawn`). Page text is never rewritten. Tests: `test/ontology-fence-sweep.test.ts`.- `src/core/repair/timeline-comments.ts` — `gbrain repair timeline-comments` (#6184), explicit-only. The plan lists pages with timeline rows whose source, summary or detail carries `<!--`/`-->` or whose body has a materialized bullet carrying markup (`dropCommentBullets`), with residuals `comment_only_rows`, `comment_bearing_rows`, `pages_with_comment_bullets`. Apply: one revision-bound `put_page` per page dropping those generated bullets (user-written bullets are left), then one transaction under the page lock (`withCoordinatedWrite` with maintenance attribution on managed brains) that deletes comment-only rows and rewrites the rest to their stripped tuple, or deletes them when the page already has it. Idempotent. `timeline.ts` warns `timeline_comment_markup` naming this kind while such rows exist. Rows on a segmented page are not planned (the apply rewrites a whole body): residuals `segmented_pages` / `segmented_rows` and a warning naming them.- `src/core/repair/aliases.ts` — `gbrain repair aliases` (#6619), explicit-only, projection publication, wired to doctor `dangling_aliases`. One item per (source, target slug) whose alias rows (`page_aliases.slug`, `slug_aliases.canonical_slug`) point at a slug with no page row at all; apply rechecks that under the page key lock and deletes both tables' rows for it, inside `withCoordinatedWrite` on a managed brain (both tables carry the managed writer guard). Aliases of soft-deleted pages are the `soft_deleted_target` residual; rename redirects (`alias_slug` = the missing slug) are never touched. Exports `ORPHANED_ALIAS_COUNTS_SQL` / `SOFT_DELETED_ALIAS_COUNT_SQL`, which `checkDanglingAliases` (`src/core/onboard/checks.ts`) reports apart, naming `repairPreviewCommand('aliases', {source})` per source instead of raw SQL. Test: `test/purge-aliases-6619.test.ts`.- `src/core/repair/orphan-children.ts` — `gbrain repair orphan-children` (#5216, #4738), explicit-only, brain-wide, projection publication. `PAGE_CHILD_FK_TARGETS` + `orphanPredicate` (a correlated, table-qualified `NOT EXISTS`, so Postgres plans an anti-join instead of a per-row subplan once page ids outgrow work_mem; `test/e2e/repair-orphan-children-plan-postgres.test.ts`) are the single target list (doctor `child_table_orphans` in `doctor/checks/core-health.ts` imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. `probeTornPages` reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the `torn_pages` residual plus a warning naming id/source/slug; they are never changed. The `storage_corrupt` reason in `pg-access-classify.ts` points XX000 storage errors here (`repair-orphan-children-5216.test.ts`, `pg-access-storage-corrupt-5216.test.ts`).-- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a host that may not write the source is skipped with the owner condition as its reason (`host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`; `owner_unavailable` is the fallback; the skip's detail carries `why`, the read-only fix and `retryable`), a candidate a write in flight or an unfinished sync's frozen manifest still names is `sync_in_progress` (#6278: checked at plan, at apply and again at the write's admission in `file-repair.ts`; the rest of the source repairs while the sync runs, and a held path is not busy); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, no measured model with a key and `models.fence_repair` unset → `no_measured_model`, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `resolveFenceRepairModel` (`fence-repair/model.ts`: `models.fence_repair`, else the first measured model with a key, else none). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.- `src/core/repair/content-lane.ts` — the content-repair lane (#6377). `CONTENT_REPAIR_KINDS` is the ordered list of repair kinds that clear managed-sync content holds (today `fences`; the GBRA-72 integration appends `slug-conflicts`), read by `gbrain repair content` (`src/commands/repair-content.ts`), the `content_repair` cycle phase and `gbrain sync unblock --apply`, so a new kind plugs in with one entry. `CONTENT_REPAIR_HOLD_KINDS` maps a hold code to the kind that clears it (`invalid_fence` → `fences`; `frontmatter_slug_conflict` → `null` until Lane B's kind lands, which keeps the surfaces' refusal text). `runContentLane(engine, scope, { apply, kinds?, only, skip, expect?, noLlm, maxLlmUsd, deadline, registry?, signal? })` has no rule logic: it runs each kind through `repairRunner` in order (a kind that throws item-scoped becomes a `stopped` result with reason `error`, its code, the redacted message and the kind's preview as `fix`, and the next kind runs; a run-scoped error, or any error after `signal` aborts, is thrown; site `repair.content_lane_kinds`), passing the run's paid allowance minus what earlier kinds spent (read from each result's `cost.llm_usd`; the daily ledger is `FENCE_REPAIR_LEDGER` for every kind) and one absolute deadline (a `time_budget` stop ends the pass; any other stop lets the next kind run), and returns per-kind results, each kind's own `preview_hash` (no combined hash: `--expect` is one hash per kind in lane order, `parseContentLaneExpect` refuses a wrong count with `invalid_params` before any kind runs), the lane's spend and remaining allowance, and `apply_command` (`contentLaneArgv`). A preview plans every kind before any mutation; `--apply --expect` binds each kind to its approved set; a bare apply runs each kind's own plan-and-apply (`changed_since_read` binding, held reasons recorded on the holds). `contentHoldDisposition(record, auto)` reads a hold's stored repair state (`fenceHoldStatus` for a fence hold; `meta.content_repair.action` for a slug-conflict hold, read loosely) and says whether an unattended surface may run the kind (`repair`), must list it (`listed`: `needs_human` for a manual reason or a recommended merge, `paid`, `owner`) or has no kind for it (`unsupported`). Output is counts, codes, hashes and paths only. Tests: `test/cycle-content-repair.test.ts` (stub kinds), `test/repair-content.test.ts` (the real `fences` kind through the CLI).- `src/core/repair/slug-conflicts.ts` — `gbrain repair slug-conflicts` (#6377, Lane B), the lane kind that clears `frontmatter_slug_conflict` holds: preview-bound, `spends: 'llm'`, `checks: []` (doctor keeps `git_held_files` on `frontmatter`), not explicit-only. Candidates are the source's slug-conflict holds (plus `--only <path>`); identity is resolved, not textual: the frontmatter slug is normalized the way the screen does and resolved through `slug_aliases` to a page id in the same source (a slug resolving to the held file's own page is exempt; a held file with no page yet is a normal candidate). Deterministic tier (`remove_slug`, confidence high): the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token; besides SLUG_MISMATCH `autoFixFrontmatter` may propose only style-only `NESTED_QUOTES` (left as written, listed as `style_only`), any other code holds it `still_invalid` naming it; the one-line edit publishes through the frontmatter repair's coordinated path (`prepareRepairPublication` / `submitManagedFileRepair`: bytes bound to the sha256 the preview read, import, hold clear and Git effect in one write). Every verdict uses managed sync's own screen (`sync-screen.ts` `loadSyncScreenRun` + `frozenImportScreenInput` + `screenFrozenContent`, on the file's bytes and on the edited bytes): a held file the screen now admits as it is (its line is clean, or names the file's own page as written) is planned as `import` and published unchanged through `submitManagedFileRepair` with an `import` receipt and `holdObservedAt` (the hold observation the plan read; a newer hold is kept and the hold records a `changed_since_read` retry); a file sync would hold whatever the lane writes (the page it is filed as carries another slug than its path, or the line reaches the own page only through an alias) is held `slug_page_mismatch` with both slugs (`named` on the hold). Everything else goes to the model tier (`src/core/content-repair/judgment.ts`): `remove_slug` applies the same way, `merge_into <canonical>` and `needs_human` are recorded on the hold as codes and slugs only (`recordContentHoldRepair`, `meta.content_repair`) and rendered by `sync status` as `needs_human` paragraphs; nothing merges pages. Caps and ledger are the fence repair's (`FENCE_REPAIR_LEDGER`, `fences.repair.max_usd_per_page` / `_per_day`, `fences.repair.llm`, `--no-llm`, `--max-usd`); the receipt is a `content_repair` receipt (action, tier, confidence, model, cost, before/after sha256, style_only) carried by the write and the commit trailer `gbrain-repair: <hold_code> <tier> <confidence>`. A bare `--apply` rotates past the last candidate it attempted (`slug-conflict-repair-rotation`), and an item-scoped apply failure counts an attempt on the hold (`onItemFailures`) toward `HOLD_ATTEMPTS_NEEDS_HUMAN`. Tests: `test/repair-slug-conflicts.test.ts`, `test/repair-slug-conflicts-sync-screen.test.ts`, `test/pathological/a44-slug-conflicts-rotation.test.ts`.- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). #5966 (W14 P1.7): the slug rule itself is `slugStampedFrontmatter(slug, fm)` in `src/core/markdown.ts` (stamps `slug:` when the path cannot derive it, such as a doubled hyphen, and replaces a foreign `fm.slug`; used by `serializePageToMarkdown` and `commands/export.ts`, digest-neutral since `parseMarkdown` drops `fm.slug`); `slugStampCandidate` proposes a SAFE `slug:` stamp for a well-formed file at a page's recorded `source_path` whose path derives another slug and that declares none (a legacy render of a slug the path cannot derive), inserted as `serializeMarkdown` writes it; never normalizes or guesses. Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. An `invalid_fence` hold is listed with a resolution that defers to `gbrain repair fences --source <id> --only <path>` (frontmatter repair never changes fences). Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`. Wave B decision #10: the preview and the apply count the source's pages stored in segments (one COUNT; their stored head is NULL, so the embedded-block check skips them) as residual `skipped_segmented` plus a `skipped (segmented): N` warning, absent at 0 (`test/large-pages/doctor-skipped-segmented.test.ts`). Decision #1: the re-import's already-matches check reads a page stored in segments back whole (`materializedSnapshot`) up to 24 MiB; over it the file is `needs_review` with `page_body_segmented` (`pageBodyOverCeilingError`) before its publication is prepared (`test/large-pages/segmented-frontmatter-reimport.test.ts`).diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 816f68b14f..5cb0784f88 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1600,7 +1600,7 @@ maintenance request per page on a managed brain). Nothing is withdrawn, soBefore the fix for #7125, fact extraction ran the prompt-injection patternsover the text it stored, and one pattern matched the English word "system"-before a parenthesis. "Acme Business System (ABS)" was stored as "Danaher+before a parenthesis. "Acme Business System (ABS)" was stored as "AcmeBusiness [redacted](ABS)", in the fact, its page's `## Facts` fence, thepage's search chunks and its history, and `trust scan` flags the marker asinstruction-like. Extraction no longer rewrites stored text, and the pattern@@ -1625,13 +1625,14 @@ pages it came from: the page its context names (the page or transcript theturn came from) and the page that holds it, as each reads now and in up to 50retained versions. A text proves a restoration when the words around everymarker in the fact occur there around exactly one span the marker's pattern-matches.+matches. A page stored in segments is read as evidence up to 16 MiB.| Class | Meaning | Restored || --- | --- | --- || `evidenced` | Every text that proves a restoration proves the same one. | By `--apply --expect <hash>` || `ambiguous` | A text holds two different spans around the same words, or two texts prove different restorations. | Never; listed || `unproven` | No page it came from exists any more (`no_source_page`), or none still holds the words around the marker (`not_in_source`). | Never; listed |+| `segmented` | Proved, but the fact's row sits in the `## Facts` fence of a page stored in segments, which this repair does not rewrite (`segmented_page`). The listing shows the restored text. | Never; listed |The apply restores exactly the previewed set. A fact that changed since thepreview reports `changed_since_preview` and keeps its text. A fact with a row@@ -1641,8 +1642,8 @@ page); a fact with no fence row is rewritten database-only (one maintenancerequest per page on a managed brain) and gets `restored: redacted-factsrepair` appended to its context; its vector no longer matches its text, sothe next `gbrain embed` re-embeds it. Page history keeps the damaged-revisions. Edit an `ambiguous` or `unproven` fact by hand if you know the-missing word.+revisions. Edit an `ambiguous`, `unproven` or `segmented` fact by hand if you know+the missing word.<a id="loop-facts"></a>### Loop factsdiff --git a/scripts/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjsindex 942efcd69a..3171892ec4 100644--- a/scripts/check-core-guard-coverage.mjs+++ b/scripts/check-core-guard-coverage.mjs@@ -41,6 +41,7 @@ const EXEMPT = {'src/core/repair/file-drift.ts': 'removes a held file whose page is deleted: no live page records the path (re-read under the publication guard), the page row is untouched, and core counts only live pages; --prefer file publishes through file-repair.ts','src/core/repair/captured-facts.ts': 'owner-run repair that expires fact rows (shrinks only)','src/core/repair/extractor-facts.ts': 'owner-run repair restoring expired fact rows',+ 'src/core/repair/redacted-facts.ts': 'owner-run, preview-bound repair rewriting the text of database-only fact rows to words a source page proves; page text is unchanged (fenced rows publish through put_page, preparePageMutation)','src/core/repair/conversation-labels.ts': 'owner-run repair expiring fact rows and writing an outcome row (shrinks only; page text unchanged)','src/core/shared-skills/publication.ts': 'skill bundles, not pages','src/core/persistence/prepared-import.ts': 'type definitions shared by import preparers; prepares nothing itself',diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex f22d6ca170..c315df6c79 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -481,6 +481,10 @@ src/core/repair/overwritten-edits.ts previewEdit call:serializePageToMarkdown SEsrc/core/repair/overwritten-edits.ts versionMarkdown call:serializePageToMarkdown SEGW inline versions only: a segmented version has no lost_digest and is never previewed; the restore goes through revert_version, which refuses a segmented page or versionsrc/core/repair/overwritten-edits.ts versionMarkdown field SEGW inline versions only: overwriteContent returns null for a segmented version, which answers version_changedsrc/core/repair/overwritten-edits.ts versionMarkdown sql SEGW selects body_storage; a segmented version answers version_changed+src/core/repair/redacted-facts.ts pageTexts field INLINE inline branch only (a segmented page's body is read through readBodyRange in segmentedText)+src/core/repair/redacted-facts.ts pageTexts sql INLINE page_versions rows that hold a body copy (compiled_truth IS NOT NULL); a segmented version has none and is not read+src/core/repair/redacted-facts.ts restoreFencedRows call:serializePageToMarkdown INLINE inline pages only: a segmented page returns before the read, and its fenced rows preview as class segmented+src/core/repair/redacted-facts.ts restoreFencedRows field INLINE inline pages only: a segmented page returns before the read, and its fenced rows preview as class segmentedsrc/core/repair/safe-chunks.ts safeChunksRepair sql METAsrc/core/repair/segmented-mirror.ts fileHoldsWithdrawnRows field NONE the overlay result of one file fragment (a facts fence block) for the region digests (body-digests.ts); no page body is readsrc/core/repair/slug-conflicts.ts pageContent call:serializePageToMarkdown SEGWdiff --git a/src/core/repair/redacted-facts.ts b/src/core/repair/redacted-facts.tsindex a1046f1c0b..2fe84cc13b 100644--- a/src/core/repair/redacted-facts.ts+++ b/src/core/repair/redacted-facts.ts@@ -24,6 +24,11 @@* or texts prove different restorations; listed, never changed.* - unproven: no text proves one (no source page, or the words are gone);* listed, never changed.+ * - segmented: proved, but the row sits in the facts fence of a page+ * stored in segments, which this repair does not rewrite; listed with+ * its restoration, never changed.+ * A segmented source page is read as evidence through the segment reader+ * (up to 16 MiB).** The apply rewrites only the evidenced facts that are still exactly as* previewed. A fenced row (`row_num` on its page) gets its claim rewritten in@@ -52,14 +57,18 @@ import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saimport { INJECTION_PATTERNS, LEGACY_EVAL_SHELL, restoreNeutralized } from '../think/sanitize.ts';import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';+import { readBodyRange } from '../page-body/read-range.ts';export const REDACTED_FACTS_INTENT = 'managed_maintenance_restore_redacted_facts';const RESTORE_PATTERNS = [...INJECTION_PATTERNS, LEGACY_EVAL_SHELL];const RESTORED_CONTEXT = 'restored: redacted-facts repair';/** Retained versions read per source page, newest first. */const VERSIONS_PER_PAGE = 50;+/** A segmented source body longer than this is not read as evidence. */+const TEXT_MAX_BYTES = 16 * 1024 * 1024;-export type RedactedFactClass = 'evidenced' | 'ambiguous' | 'unproven';+export type RedactedFactClass = 'evidenced' | 'ambiguous' | 'unproven' | 'segmented';export interface RedactedFactCandidate {id: number;@@ -68,9 +77,9 @@ export interface RedactedFactCandidate {slug: string;row_num: number | null;class: RedactedFactClass;- /** `restorable`, `conflicting_sources`, `no_source_page` or `not_in_source`. */+ /** `restorable`, `conflicting_sources`, `no_source_page`, `not_in_source` or `segmented_page`. */reason: string;- /** The stored text, and the restored text when evidenced. */+ /** The stored text, and the restored text when evidenced (or proved on a segmented page). */fact: string;restored: string | null;/** The texts that proved the restoration (`<slug>` or `<slug>@version:<id>`). */@@ -100,6 +109,44 @@ const contextSlug = (context: string | null) => {return /^[^\s|]+$/.test(first) ? first : null;};+interface PageTexts { segmented: boolean; texts: Array<{ label: string; text: string }> }++/** A segmented body's stored text, read segment by segment; null when it is over TEXT_MAX_BYTES (it proves nothing). */+async function segmentedText(db: BrainEngine, pageId: number): Promise<string | null> {+ const decoder = new TextDecoder('utf-8', { ignoreBOM: true });+ let bytes = 0;+ let text = '';+ for await (const piece of readBodyRange(db, { pageId, space: 'stored', start: 0, end: Infinity, audience: 'trusted' })) {+ bytes += piece.bytes.length;+ if (bytes > TEXT_MAX_BYTES) return null;+ text += decoder.decode(piece.bytes, { stream: true });+ }+ return text + decoder.decode();+}++/**+ * The texts a page offers as evidence: its body as it reads now and its+ * retained versions that hold a body copy. A segmented page's body is read+ * through the segment reader; a segmented version carries no body copy and is+ * not read.+ */+async function pageTexts(db: BrainEngine, sourceId: string, slug: string): Promise<PageTexts> {+ const snapshot = await db.readPageSnapshot(slug, { sourceId }).catch(() => null);+ if (!snapshot) return { segmented: false, texts: [] };+ const texts: PageTexts['texts'] = [];+ const segmented = isSegmentedPage(snapshot.page);+ if (segmented) {+ const text = await segmentedText(db, snapshot.page.id);+ if (text !== null) texts.push({ label: slug, text });+ } else {+ texts.push({ label: slug, text: [snapshot.page.compiled_truth ?? '', snapshot.page.timeline ?? ''].join('\n') });+ }+ const versions = await db.executeRaw<{ id: number | string; compiled_truth: string }>(`SELECT id, compiled_truth FROM page_versions+ WHERE page_id=$1 AND compiled_truth IS NOT NULL ORDER BY id DESC LIMIT ${VERSIONS_PER_PAGE}`, [snapshot.page.id]);+ for (const v of versions) texts.push({ label: `${slug}@version:${v.id}`, text: v.compiled_truth });+ return { segmented, texts };+}+/** Read-only: every active fact of these sources whose text holds a redaction marker, classified, in (source, page, id) order. */export async function classifyRedactedFacts(db: BrainEngine, sourceIds: string[], opts: { ids?: number[] } = {}): Promise<RedactedFactCandidate[]> {const rows = await db.executeRaw<FactRow>(`@@ -108,20 +155,11 @@ export async function classifyRedactedFacts(db: BrainEngine, sourceIds: string[]WHERE f.source_id=ANY($1::text[]) AND f.expired_at IS NULL AND f.superseded_by IS NULLAND f.fact LIKE '%[redacted%' AND ($2::bigint[] IS NULL OR f.id=ANY($2::bigint[]))ORDER BY f.source_id, f.id`, [sourceIds, opts.ids ?? null]);- const texts = new Map<string, Array<{ label: string; text: string }>>();+ const pages = new Map<string, PageTexts>();const sourceTexts = async (sourceId: string, slug: string) => {const key = `${sourceId}\u0000${slug}`;- if (texts.has(key)) return texts.get(key)!;- const found: Array<{ label: string; text: string }> = [];- const snapshot = await db.readPageSnapshot(slug, { sourceId }).catch(() => null);- if (snapshot) {- found.push({ label: slug, text: [snapshot.page.compiled_truth ?? '', snapshot.page.timeline ?? ''].join('\n') });- const versions = await db.executeRaw<{ id: number | string; compiled_truth: string }>(`SELECT id, compiled_truth FROM page_versions- WHERE page_id=$1 AND compiled_truth IS NOT NULL ORDER BY id DESC LIMIT ${VERSIONS_PER_PAGE}`, [snapshot.page.id]);- for (const v of versions) found.push({ label: `${slug}@version:${v.id}`, text: v.compiled_truth });- }- texts.set(key, found);- return found;+ if (!pages.has(key)) pages.set(key, await pageTexts(db, sourceId, slug));+ return pages.get(key)!;};const candidates: RedactedFactCandidate[] = [];for (const row of rows) {@@ -130,16 +168,19 @@ export async function classifyRedactedFacts(db: BrainEngine, sourceIds: string[]let read = 0;let conflicting = false;for (const slug of slugs) {- for (const { label, text } of await sourceTexts(row.source_id, slug)) {+ for (const { label, text } of (await sourceTexts(row.source_id, slug)).texts) {read++;const result = restoreNeutralized(row.fact, text, RESTORE_PATTERNS);if (result.ambiguous) conflicting = true;else if (result.restored && !result.unresolved) proofs.set(result.text, [...(proofs.get(result.text) ?? []), label]);}}+ const proved = !conflicting && proofs.size === 1;+ const held = proved && row.row_num !== null && row.source_markdown_slug !== null+ && (await sourceTexts(row.source_id, row.source_markdown_slug)).segmented;const [klass, reason]: [RedactedFactClass, string] = conflicting || proofs.size > 1 ? ['ambiguous', 'conflicting_sources']- : proofs.size === 1 ? ['evidenced', 'restorable'] : ['unproven', read ? 'not_in_source' : 'no_source_page'];- const [restored, evidence] = klass === 'evidenced' ? [...proofs][0]! : [null, [...proofs.values()].flat()];+ : held ? ['segmented', 'segmented_page'] : proved ? ['evidenced', 'restorable'] : ['unproven', read ? 'not_in_source' : 'no_source_page'];+ const [restored, evidence] = proved ? [...proofs][0]! : [null, [...proofs.values()].flat()];candidates.push({ id: Number(row.id), source_id: row.source_id, slug: targetSlug(row), row_num: row.row_num === null ? null : Number(row.row_num),class: klass, reason, fact: row.fact, restored, evidence, visibility: row.visibility, entity_slug: row.entity_slug,source_markdown_slug: row.source_markdown_slug, fact_hash: factHash(row) });@@ -152,6 +193,7 @@ const DETAILS: Record<string, string> = {conflicting_sources: 'its source texts hold different spans around the same words, so nothing proves one restoration; left unchanged',no_source_page: 'no page it came from exists any more, so nothing can prove the original words; left unchanged',not_in_source: 'the words around the marker are not in any page it came from, so nothing proves the original words; left unchanged',+ segmented_page: 'its row sits in the facts fence of a page stored in segments, and this repair rewrites a fence by publishing the whole body; left unchanged',};function previewCommand(scope: RepairScope, all: string[]): string {@@ -191,9 +233,10 @@ export const redactedFactsRepair: RepairHandler = {if (approved.length) await saveApprovedSet(engine, { command: 'redacted-facts', hash }, approved);const count = (klass: RedactedFactClass) => candidates.filter(c => c.class === klass).length;const listing: RepairListing[] = candidates.map(c => ({ item: `${c.source_id}:${c.slug}#${c.id}`, class: c.class,- detail: c.class === 'evidenced' ? `"${c.fact}" -> "${c.restored}" (proved by ${c.evidence.join(', ')})` : `"${c.fact}": ${DETAILS[c.reason]}` }));+ detail: c.class === 'evidenced' ? `"${c.fact}" -> "${c.restored}" (proved by ${c.evidence.join(', ')})`+ : c.restored ? `"${c.fact}" -> "${c.restored}" (proved by ${c.evidence.join(', ')}): ${DETAILS[c.reason]}` : `"${c.fact}": ${DETAILS[c.reason]}` }));return { items: approved.map((page, i) => pageItem(page, hash, i, i === approved.length - 1)), preview_hash: hash, listing,- residuals: { evidenced: count('evidenced'), ambiguous: count('ambiguous'), unproven: count('unproven') } };+ residuals: { evidenced: count('evidenced'), ambiguous: count('ambiguous'), unproven: count('unproven'), segmented: count('segmented') } };}if (!opts.expect) {throw new OperationError('invalid_params', 'gbrain repair redacted-facts --apply restores only the set a preview printed.',@@ -295,7 +338,7 @@ export async function prepareRedactedFactsRestore(engine: BrainEngine, row: Writasync function restoreFencedRows(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem, page: RedactedFactsPage, facts: RedactedFactCandidate[]): Promise<number[]> {const engine = ctx.engine;const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });- if (!snapshot) return [];+ if (!snapshot || isSegmentedPage(snapshot.page)) return [];let body = snapshot.page.compiled_truth ?? '';const rewritten: RedactedFactCandidate[] = [];for (const fact of facts) {diff --git a/test/repair-redacted-facts.test.ts b/test/repair-redacted-facts.test.tsindex 130f2f4d72..a8525754eb 100644--- a/test/repair-redacted-facts.test.ts+++ b/test/repair-redacted-facts.test.ts@@ -27,6 +27,7 @@ import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { managedBrain } from './helpers/managed-brain.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { createSegmentedPage } from './helpers/segmented-page.ts';const ACME = 'companies/acme-example';const NOTES = 'notes/operating-models';@@ -106,7 +107,7 @@ ${fence}expect(wave.spec.count(wave.check.details!)).toBe(5);const preview = await repair(engine, []);- expect(preview.results[0].residuals).toEqual({ evidenced: 2, ambiguous: 1, unproven: 2 });+ expect(preview.results[0].residuals).toEqual({ evidenced: 2, ambiguous: 1, unproven: 2, segmented: 0 });const classes = Object.fromEntries(preview.results[0].listing!.map(l => [Number(l.item.split('#')[1]), l.class]));expect(classes).toEqual({ [fencedId]: 'evidenced', [dbOnly]: 'evidenced', [unproven]: 'unproven', [noPage]: 'unproven', [conflicting]: 'ambiguous' });expect(preview.results[0].listing!.find(l => l.item.endsWith(`#${fencedId}`))!.detail).toContain(ABS_RESTORED);@@ -132,7 +133,7 @@ ${fence}expect((await factText(engine, conflicting)).fact).toBe('The Acme [redacted](ACS) launch');expect((await factsRedactionMarkerCheck(engine)).details).toMatchObject({ affected: 3 });- expect((await repair(engine, [])).results[0].residuals).toEqual({ evidenced: 0, ambiguous: 1, unproven: 2 });+ expect((await repair(engine, [])).results[0].residuals).toEqual({ evidenced: 0, ambiguous: 1, unproven: 2, segmented: 0 });}, { databaseUrl });}, 180_000);@@ -172,7 +173,7 @@ ${SOURCE_TEXT}const id = Number((await engine.executeRaw<{ id: number }>(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, context)VALUES ('default', $1, $2, 'fact', 'private', 'sync:import', $3) RETURNING id`, [ACME, ABS_DAMAGED, NOTES]))[0].id);const preview = await repair(engine, []);- expect(preview.results[0].residuals).toEqual({ evidenced: 1, ambiguous: 0, unproven: 0 });+ expect(preview.results[0].residuals).toEqual({ evidenced: 1, ambiguous: 0, unproven: 0, segmented: 0 });expect(preview.results[0].listing![0].detail).toContain(`${NOTES}@version:`);expect((await repair(engine, applyArgs(preview))).results[0].outcomes).toEqual({ restored: 1 });const [row] = await engine.executeRaw<{ fact: string; context: string }>('SELECT fact, context FROM facts WHERE id=$1', [id]);@@ -181,6 +182,28 @@ ${SOURCE_TEXT}expect((await factsRedactionMarkerCheck(engine)).status).toBe('ok');}, 120_000);+ test('a segmented source page proves a restoration from its second segment; a proved fenced row on a segmented page is listed, never rewritten', async () => {+ const source = 'notes/segmented-models';+ const held = 'companies/segmented-example';+ await createSegmentedPage(engine, { slug: source, truth: `${'Filler line.\n'.repeat(90_000)}${SOURCE_TEXT}\n` });+ await createSegmentedPage(engine, { slug: held, truth: 'Segmented example notes.\n' });+ const insert = async (fact: string, rowNum: number | null, holder: string | null) => Number((await engine.executeRaw<{ id: number }>(`INSERT INTO facts+ (source_id, entity_slug, fact, kind, visibility, source, context, row_num, source_markdown_slug)+ VALUES ('default', $1, $2, 'fact', 'private', 'sync:import', $3, $4, $5) RETURNING id`, [held, fact, source, rowNum, holder]))[0].id);+ const dbOnly = await insert(EXOS_DAMAGED, null, null);+ const fenced = await insert(ABS_DAMAGED, 1, held);+ const preview = await repair(engine, []);+ expect(preview.results[0].residuals).toEqual({ evidenced: 1, ambiguous: 0, unproven: 0, segmented: 1 });+ const listed = Object.fromEntries(preview.results[0].listing!.map(l => [Number(l.item.split('#')[1]), l]));+ expect(listed[dbOnly]!.class).toBe('evidenced');+ expect(listed[fenced]!.class).toBe('segmented');+ expect(listed[fenced]!.detail).toContain(ABS_RESTORED);+ expect((await repair(engine, applyArgs(preview))).results[0].outcomes).toEqual({ restored: 1 });+ expect((await factText(engine, dbOnly)).fact).toBe(EXOS_RESTORED);+ expect((await factText(engine, fenced)).fact).toBe(ABS_DAMAGED);+ await engine.executeRaw('DELETE FROM facts WHERE id=$1', [fenced]);+ }, 120_000);+test('the publication rewrites a row only while it is exactly as previewed (a change after the recheck wins)', async () => {const id = Number((await engine.executeRaw<{ id: number }>(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, context)VALUES ('default', $1, $2, 'fact', 'private', 'sync:import', $3) RETURNING id`, [ACME, EXOS_DAMAGED, NOTES]))[0].id);