Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Operators can open facts saved private before the world default, with a preview and undo (Discussion #8194) (#9523)

Garry Tan9f1d54232def
diff --git a/behavior-changes.d/open_facts_repair_8194.md b/behavior-changes.d/open_facts_repair_8194.md
new file mode 100644
index 0000000000..f3c7e93f3a
--- /dev/null
+++ b/behavior-changes.d/open_facts_repair_8194.md
@@ -0,0 +1,4 @@
+---
+kind: add
+---
+New command: gbrain repair open-facts opens facts that were saved private before facts.default_visibility became world, so remote callers that are not the brain owner can recall them. Nothing changes until the operator runs it on the brain host: preview with gbrain repair open-facts --source <id> --created-before <ISO-8601>, then apply exactly that preview with --apply --expect <hash>. Facts on private, member or quarantined pages, withdrawn, contested, expired or superseded facts stay private and are counted by reason. Each change is recorded in ~/.gbrain/repair/open-facts/, and --undo <ledger> makes the opened facts private again (what was already read stays read).
diff --git a/changelog.d/capy-open-legacy-private-facts.md b/changelog.d/capy-open-legacy-private-facts.md
new file mode 100644
index 0000000000..3d1090c3be
--- /dev/null
+++ b/changelog.d/capy-open-legacy-private-facts.md
@@ -0,0 +1,8 @@
+**New `gbrain repair open-facts` lets the operator open facts saved private before the world default, after a preview, with an undo.**
+
+<!-- behavior-change: open_facts_repair_8194 -->
+
+### Added
+- `gbrain repair open-facts --source <id> --created-before <ISO-8601>` previews the active private facts saved before that instant, counts every fact it leaves private by reason (private, missing or quarantined pages, member pages, withdrawn, contested, expired, superseded), and `--apply --expect <hash>` opens exactly that window in place, keeping ids and trust tiers (Discussion #8194).
+- Facts with no page and transcript-lane facts are listed apart and open only with `--class unpaged:<lane>`; `--ids-file` narrows the set; `--undo <ledger>` re-privates what a run opened.
+- The command runs only from the CLI on the brain host: remote callers, member mode (`GBRAIN_ENFORCED_MEMBER`), `repair --all`, doctor and the remediation plan never run it. Nothing changes until an operator runs it.
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 4cab43ac6a..7b1a548722 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -32,6 +32,7 @@ src/core/persistence/twin-merge.ts 10 coordinator The #6948 twin merge (links in
src/core/repair/origin-twins.ts 1 coordinator gbrain repair origin-twins and the post-sync heal resolve each verified twin as a receipted managed_maintenance_resolve_origin_twin request (submitDatabaseMaintenanceIntent, owner host only) on managed brains and in one maintenanceTransaction on unmanaged brains; the verdict is recomputed inside the write and any drift holds the file instead of merging.
src/core/repair/unwithdrawn-facts.ts 1 coordinator `gbrain repair unwithdrawn-facts` (#8819) puts the ledger before-state back on preview-approved facts a fact_fence generation retired though no fence held them. On a managed brain the UPDATE runs only inside the managed_maintenance_restore_unwithdrawn_facts publication; an unmanaged or repo-less brain classifies every candidate excluded (unmanaged_reconcile), so a set previewed while it was managed is reclassified in one maintenanceTransaction under the page lock after the revision recheck and restores nothing.
src/core/repair/private-labels.ts 1 coordinator `gbrain repair private-labels` (GST-2059) removes or re-adds only the previewed privacy keys on preview-approved pages. On a managed brain each page goes through publishMaintenancePage (maintenancePreflight owner check, revision-bound, keep_trust; the Git door on a repo source); an unmanaged or repo-less brain re-imports it in one maintenanceTransaction under the page lock after the revision recheck, except a page whose file sits in an unmanaged source's checkout, which is held (file_backed) and never written.
+src/core/repair/open-facts.ts 2 coordinator `gbrain repair open-facts` (#8194) sets preview-approved private facts to world (and --undo back to private) in place, keeping id and tier; each UPDATE rechecks the fact under its row lock after the holding, provenance and entity pages are locked FOR SHARE. On a managed brain database-only rows change only inside the managed_maintenance_open_fact_visibility publication (submitDatabaseMaintenanceIntent, maintenancePreflight owner check) and fence rows only inside the keep_trust maintenance page publication naming open_facts, which rolls back unless every named row moved. On an unmanaged or repo-less brain the database-only UPDATE runs in one maintenanceTransaction, and the fence-row UPDATE runs inside the label write's maintenanceTransaction (importAtRevision) after the page import and before writePageThrough writes a checkout file, so a row the recheck keeps private (revision_conflict) or a failed file write rolls the page, the file write and the rows back together.
src/core/repair/label-write.ts 1 coordinator The label-only page write of `gbrain repair visibility` and `gbrain repair private-labels` (GST-2468). On a managed brain it publishes through publishMaintenancePage (maintenancePreflight owner check, revision-bound, keep_trust, label_edit), or through publishMaintenancePages with a maintenance batch for repair visibility --readers (GST-2476; visibility.ts applyBatch admits a window of pages together), so the Git effect commits a window's ready files together. Only an unmanaged or repo-less brain calls importFromContent (importAtRevision), in one maintenanceTransaction under the page lock after the revision recheck and under withTrustKeep; for a page whose file sits in an unmanaged checkout (writeLabelFile) the file must still hold the page (ownerRepairFile), and writePageThrough writes the spliced bytes back with their preimage checked inside that transaction, so a refused or failed file write rolls the import back.
src/core/search-vector-backfill.ts 2 projection backfillPageVectors (reindex-search-vector, the fts_cjk_boundary migration) rewrites only pages.search_vector, through the seal's pageSearchVectorSql over the sanitized timeline and guarded by the knowledge revision it read (its read is an UPDATE-to-self of id); canonical fields are untouched and the managed writer guard passes search_vector-only updates.
src/commands/sources-set-path.ts 1 coordinator Managed rebind uses native exclusion, exact manifest verification and a retained source-incarnation receipt; unmanaged pointer repair remains explicit.
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index c6fc24bf1e..ca2090e90f 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -44,4 +44,5 @@ The #6188 fence check and fence repair live in [fence repair](core-fence-repair.
- `src/core/links-fence.ts` + `src/core/links-fence-projection.ts` — the `## Links` fence (G5): the markdown form of authored (manual) edges, `<!--- gbrain:links:begin -->` / `end` around `| to | type | source | valid_from | valid_until | context |`, one row per (to, type, source), source defaulting to `manual`; a reconciliation-managed provenance (`MANAGED_LINK_SOURCES`, exported here and re-exported by `ops/links.ts`), a bad date or a duplicate key is a skipped row with a warning. `parseLinksFence` (state `absent` / `parsed` / `malformed`), the deterministic `renderLinksFence` (rows sorted by key), `upsertLinksFenceRow` (omitted context and dates keep the stored ones; identical row = unchanged body), `removeLinksFenceRows` (leaves an empty fence), `replaceOrInsertLinksFence` (a `## Links` section at the end of compiled_truth, above an unclosed code block) and `maskLinksFence`, which `extractBodyLinks` applies so the fence cells are never also extracted as markdown, wikilink or bare-slug edges. A rewrite of a fence that parses with warnings throws `LinksFenceRewriteRefusal`. Cells use `escapeFenceCell` plus the same one-level marker encoding for `gbrain:links:*`. `projectLinksFence(tx, page, rows)` reconciles only what the page's fence owns: edges with origin_page_id = the page and origin_field `links_fence` (deleted, context-updated, inserted by key) and `manual` transitions with origin_page_id = the page, compared per row by (to, type, link_source, kind, date) and written with the row's source in `link_source`, then refreshes the touched relationships; a row whose target is not a live page in the source yields no edge. `linksFenceProjectionRows` returns null for an absent or malformed fence, so such a body changes no edge (an absent fence retires nothing, as for facts; unlike facts no held generation is recorded, so after a hand deletion of the whole section the database keeps edges git no longer has until `remove_link` or the G3 indexer), and drops rows typed with a link type the active pack does not declare. Callers: `prepareCanonicalProjections` (every projected page publication, quarantined and segmented-unread bodies excepted), `prepareAutomaticLinks` (put_page auto-links and the managed links maintenance, so `extract --stale` restores a lost fence edge) and `persistence/manual-links.ts`. Database-only manual edges (origin_field NULL) are never touched by any of them. Pinned by `test/links-fence.test.ts` and `test/managed-links-fence.test.ts`.
- `src/core/persistence/source-lifecycle.ts` retire batches with `topology-transaction.ts` (#7702/#8905) — every `topologyTransaction` runs under `statement_timeout=5s` and `lock_timeout=1s` and maps SQLSTATE 57014/55P03 to `write_pending`, so a managed `remove` or `purge` first deletes the source's pages in batches of `SOURCE_RETIRE_BATCH_PAGES` (500; about 110 ms per batch with chunks and links on Postgres) under the native locks `withTopologyLocks` holds, each batch its own `topologyTransaction`. A batch re-checks the final transaction's preconditions (admin state, `lockTopologyRows`, the incarnation read before the locks, archived or `EXPIRED_ARCHIVE_SQL` due, no prior receipt other than this request's own admission, no `oauth_clients` reference, `assertTopologyRequestsSettled` from `topology-locks.ts`, `lockTopologyPrincipal`, and on the first batch `admitTopologyRetire` from `topology-receipts.ts`, which checks the receipt quotas at the largest receipt and records the admission) and, when one would refuse or replay, stops without deleting so the final transaction reports it, or throws that refusal before deleting; a batch that fails `write_pending` is retried at half the size (floor 1), so heavy pages still fit the bound; a refusal after some batches committed says how many pages that run already deleted; a dry run, a missing checkout, an unconfirmed operation and an admission-hooked call never batch. The final transaction's `sources` delete runs `removedSourceScrubCtes` (#9068: the source's retrieval and volunteer rows, and its slugs in eval candidates), so a run that stops after some batches leaves those rows until a retry commits. Each batch deletes inside `withCoordinatedWrite` with local-CLI attribution (the `pages` guard needs the source in `gbrain.write_sources`; only the final `sources` delete sets `gbrain.topology_change`). Committed batches are durable: a retry (same or new request_id) resumes, and the receipt's `pages_deleted` counts the pages deleted by the run that commits it. #8984: the first batch's transaction records the admission, a `persistence_topology_changes` row in state `recovering` with no recovery record, bound to the source incarnation it deletes from (`isRetireAdmission`); `recordTopologyChange` settles it `committed`, and a remove or purge that deletes that incarnation under another request, or any other lifecycle operation that commits a change to it (archive, restore, rebind, claim), settles it `failed` (`supersedeTopologyRetires`, which skips only the caller's own principal and request_id pair). A retry of the request_id against another incarnation (the source was removed and re-added) refuses `source_retire_superseded`, settles the admission `failed` and deletes nothing, also when a since-replaced CLI registration (another principal) admitted that request_id for a remove or purge, since idempotency is per principal; an admission bound to the current incarnation still resumes under the new registration; deactivation and graduation list an unsettled admission as a blocker that names its request_id and asks the user whether to finish it or keep what is left; an automatic expired-archive purge's admission (`expired_only` in its outcome) is left to the next automatic run with `needsUser: false`, and `sources writer status --json` lists the stopped and superseded requests (`topology_requests`). Tests: `test/source-retire-batched.test.ts` (PGLite), `test/e2e/source-retire-batched-postgres.test.ts` (60,000 pages), `test/source-retire-incarnation.test.ts` and `test/e2e/source-retire-incarnation-postgres.test.ts`.
- `src/core/persistence/label-edit.ts` + `src/core/repair/label-write.ts` (GST-2468) — the label-only page write of operator repairs (`repair visibility`, `repair private-labels`). `label-edit.ts`: `LABEL_KEYS` (visibility, access, confidentiality), `readLabelEdit` validates a `managed_maintenance_page` intent's `label_edit` (`set` plain-word values, `remove` keys), `spliceLabelLines` removes, replaces or appends label lines in a file's frontmatter text and declines (null) a block or multi-line value, a duplicate key or a file with no frontmatter block. `page-prepare.ts` `labelEditFile` uses it in `compareFileTarget` when the file matches the snapshot: the edited file (or its edited head over the write's body, for a fence row) must read back as the file the write would render, else the write refuses `label_edit_refused` (GST-2603; reason `file_differs` with the differing keys in `detail`, or `label_line`); the file is never re-rendered under a label edit. GST-2603: `labelEditFit` (also used by `writeLabelFile`) aligns the file with the stored page before comparing, and `align-stored.ts` `keepStoredOnlyStamps` (used by `alignWithStored` and sync's `keepStoredStamps`) keeps the stamps gbrain holds only in the database (the `validate: false` grandfather stamp and a stored `legacy_type` whose aligned type is the page's), so they never count as a difference; `fileSnapshotDifference` lists the differing keys (frontmatter keys, title, type, tags, body, timeline) for the raw and inferred reading and `fileMatchesSnapshot` is its empty case. `label-write.ts` `labelFileRefusal` is a write-free preflight (managed: `prepareFileTarget`, with the drift's keys from `error.localEdit` and `gbrain sources reconcile <id> <slug> --preview` as next step; unmanaged: `ownerRepairFile`, next step `gbrain sync --source <id>`; repo-less or no file: null); `visibility.ts` holds refusing pages in the preview (`details.held`, `residuals.held_file_drift` / `held_label_edit`, outside the hash and approved set) and `labelWrite` / `private-labels.ts` `prepareWrite` throw only its `label_edit_refused` before writing. `repair/core.ts` counts `label_edit_refused` as declined and never toward `item_failures_systemic`. Test: `test/label-repair-derived-stamps-gst2603.test.ts`. `label-write.ts`: `writeLabelPage` publishes through the maintenance door with `keep_trust` and the edit on a managed brain, else `importAtRevision` (maintenance transaction, page lock, `withTrustKeep`); `filesInCheckout` names the unmanaged pages whose checkout file would undo a database-only write; for those, `writeLabelFile` applies `labelEditFile` to the file's own bytes (it must still hold the page, `ownerRepairFile`), imports it under `withTrustKeep` and writes it back through `writePageThrough` (`fileText`, preimage checked) in one transaction; drift or a file edited mid-write throws `source_changed`, and a file it cannot write (`sync.write_through` off, `url_clone`, an unresolvable target, a write error) returns a held `file_backed` outcome with the import rolled back. `repair visibility` calls it directly; `private-labels` still holds those pages as `file_backed`; `repair/origin-carry.ts` (GST-2689) uses `writeLabelFile`, `importAtRevision` and `publishMaintenancePages` the same way to label derived pages private before their origin row goes, and parks the origin when one returns held or throws. GST-2476: `label-edit.ts` also edits `readable_by` (`READERS_KEY`, `EDIT_KEYS`; `set` takes a plain-word list, rendered `readable_by: [a, b]`), and `writeLabelPage` takes a maintenance `batch` (then `publishMaintenancePages([page], {batch})`). `src/core/repair/readers.ts` is `repair visibility --readers`: `checkedReaders` (members exist and are enabled, groups exist, else `access_member_invalid`; a list that leaves out the owner refuses unless `allowWithoutOwner`), `planReaders` (named pages or a `--slugs-file`, up to `READERS_MAX_PAGES`, approved set bound to each page's live readers) `readersWrite` (re-checks a page, holds a segmented one, renders the edit) and `applyReaders` (phase `READERS_PHASE`, one label-only write); `visibility.ts` `applyBatch` admits a managed source's run of readers items together through `publishMaintenancePages` under the run's batch (Postgres publishes them in groups of up to 8), so the Git effect commits a window's ready files together; `readersGitCounts` reports the run's Git effect states. `visibility.ts` `labelWrite` holds a managed page with no canonical file outside `storage.db_only` as `canonical_file_missing`. GST-2519, labels under `storage.db_only`: `sync-classify.ts` `gitVerdict` keeps a strict source's `db_ahead` path when `state.dbOnly` (a label repair on a page whose file Git still tracks there survives later syncs; a commit that moved still imports); `sync-prepare.ts` imports a db_only file over a live page through `withStoredLabels(text, stored, incoming)`, which adds each `EDIT_KEYS` label the row holds and the file does not state, so an import there never widens (a label the file states applies, wider included); `page-prepare.ts` `prepareFileTarget` lets a label repair of a strict page stamped `git_ignored`, with no recorded file and a path Git still ignores, write the database only instead of holding it `canonical_file_missing`. Tests: `test/db-only-labels-gst2519.test.ts`, `test/sync-classify-strict-g3.test.ts`.
+- `src/core/repair/open-facts.ts` + `src/commands/repair-open-facts.ts` (#8194) — `gbrain repair open-facts`, the operator-only, explicit-only, preview-bound repair that opens facts stamped private before `facts.default_visibility world`. `openFactsReasonSql` is the one exclusion expression the preview, its reason counts and the locked apply share (expired, superseded, member page, withdrawn or purged at any visibility, any pending trust proposal or a rejected or undone widening, a holding, provenance or entity page that is `derivationPrivateSql` on any row with the slug, deleted or not, a missing or quarantined holding or provenance page, an unresolved provenance slug); `openFactClassSql` classes facts `fenced`, `unfenced` or `unpaged:<lane>` (no page or a transcript lane; opened only when named). Keyset windows (`--after`, `--limit`), the approved set binds the window and an apply refuses `preview_changed` when a new fact became eligible inside it. Writes lock the named pages FOR SHARE and each fact FOR UPDATE before the recheck: database-only rows change in place (managed: the `managed_maintenance_open_fact_visibility` intent, `prepareOpenFactsIntent`; else a maintenance transaction); fenced rows go through the label-only door with the cell set by `strikeFenceRow` (managed: `publishMaintenancePage` with `openFacts`, whose keep_trust publication `openFactsPublication` runs under `persistence/context.ts` `withOpenFacts`, the only setter of `gbrain.write_open_facts`, which `openedFactRowSql` reads in `trust/fence-guard.ts`, `generations/adapters/fact-rows.ts` and `canonical-projections.ts` so the row moves to world in place; unmanaged: the import, then the in-place update). The CLI keeps the write-ahead ledger (`repairLedger` in `repair-private-labels.ts`) and `--undo` re-privates what it opened. Refuses remote callers (`trusted_cli_required`) and `GBRAIN_ENFORCED_MEMBER` (`member_mode_refused`). Test: `test/repair-open-facts-8194.test.ts` (PGLite and Postgres, with a two-session race).
- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB; `boundedUnifiedDiff` keeps its LCS table under `EDIT_PAGE_DIFF_CELL_BUDGET` (4M cells) by diffing only the window between common leading/trailing lines, and a window still over budget becomes one coarse hunk flagged `diff_coarse` (pinned by `test/large-pages/edit-diff-bounded.test.ts`). Called at submission (`page-mutations.ts`, before admission; skipped for a segmented page) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`. `within` and the segmented path: [large page writes](core-services-2-continued.md#large-page-writes).
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 8e33c73c79..bb05f8d84b 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -319,6 +319,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/repair/ghost-pages.ts` (2): `gbrain repair ghost-pages` retirement: a receipted `managed_maintenance_retire_ghost_page` request (a prepared `delete_page` with no file bytes) on managed brains; the unmanaged version and soft delete run in `maintenanceTransaction` after the same recheck.
- `src/core/repair/moved-pages.ts` (1): `gbrain repair moved-pages` fold: a receipted `managed_maintenance_fold_moved_page` request on the old page that also holds the moved page's key, on managed brains; the unmanaged fold runs in `maintenanceTransaction` under both page locks after the same recheck.
- `src/core/repair/ontology-facts.ts` (1): a coordinated database-only write (`coordinatedDatabaseWrite`, the `ontology_propose` path) on managed brains; the unmanaged ontology-facts restore runs in `maintenanceTransaction`.
+- `src/core/repair/open-facts.ts` (2): `gbrain repair open-facts` (#8194) changes the visibility of preview-approved facts in place: a `managed_maintenance_open_fact_visibility` request (database-only rows) or the keep_trust maintenance page publication naming `open_facts` (fence rows) on managed brains; on unmanaged brains the database-only UPDATE runs in `maintenanceTransaction`, and the fence-row UPDATE runs inside the label write's `maintenanceTransaction` (importAtRevision) before any checkout file is written.
- `src/core/repair/redacted-facts.ts` (1): a `managed_maintenance_restore_redacted_facts` request on managed brains; the unmanaged restore of database-only and conversation-extractor fact text runs in `maintenanceTransaction`.
- `src/core/repair/rename-identity.ts` (5): `gbrain repair rename-identity` carry, unmanaged brains only (a managed brain refuses `managed_remedy_unavailable` before writing); the fence-row merge, the provisional page's retirement, the slug move and the import run in one `maintenanceTransaction` under both page locks after the plan-hash recheck.
- `src/core/repair/secret-spans.ts` (1): `gbrain repair secret-spans` (GST-327) rewrites the credential spans of each preview-approved page under the page key: inside `withCoordinatedWrite` with maintenance attribution on managed brains, `withWriteAttribution` with maintenance attribution on unmanaged ones.
diff --git a/docs/guides/access-designations.md b/docs/guides/access-designations.md
index 2610d7aa23..ca9aa375bb 100644
--- a/docs/guides/access-designations.md
+++ b/docs/guides/access-designations.md
@@ -188,7 +188,9 @@ host saved with `visibility: "private"`, or one on a page whose `readable_by` na
on a page whose readers leave the owner out (even with `reads-restricted on`) or on another member's page stays with the brain host, and one the owner confirmed or curated files a `forget_requires_owner`
proposal instead, as for a shared fact. The trade-off: an owner agent that follows a planted instruction can share a fact
without passing any flag, so pass `visibility: "private"` for a fact that must stay with the owner. Extracted facts follow `facts.default_visibility` (private when unset)
-and are never wider than their page. Remote fact reads return private facts to the owner only.
+and are never wider than their page. Remote fact reads return private facts to the owner only. Facts saved `private`
+before `facts.default_visibility` became `world` stay private until the operator opens them from the brain host with
+`gbrain repair open-facts` (preview first, with an undo; see [repair](repair.md#open-facts-saved-private-before-the-world-default)).
### The owner (`gbrain access owner`)
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 16654497d4..56d3585cc2 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2451,6 +2451,80 @@ line with any other key, a non-string value or a page id that isn't an integer
is counted as unreadable and never applied. Run restore on the host and
`GBRAIN_HOME` that ran the clear, because the ledger lives there.
+### Open facts saved private before the world default
+
+Facts saved before `facts.default_visibility` became `world` were stamped
+`private`, so remote callers that are not the brain owner (a shared token, a
+second agent) can't recall them, even on pages everyone may read. Nothing
+opens them on upgrade. `gbrain repair open-facts` opens them when you, the
+operator, decide to, from the CLI on the brain host:
+
+```bash
+gbrain repair open-facts --source <id> --created-before 2026-06-01T00:00:00Z --json # preview; writes nothing
+gbrain repair open-facts --source <id> --created-before 2026-06-01T00:00:00Z --apply --expect <preview_hash>
+```
+
+`--created-before` is required: name the moment the default became `world` on
+this brain, with its offset (a date alone, such as `2026-06-01`, is read as
+midnight UTC; the preview prints the cut it used), and facts saved after it
+stay as they were written. The preview
+lists one window of facts (`--limit`, default 1000; `--after <id>` previews
+the next one), each with its class: `fenced` (a row of a page's `## Facts`
+table) or `unfenced` (a fact stored only in the database, held on a page).
+Facts with no page, and facts from transcript lanes (conversation
+extraction, capture hooks, connectors), are counted as `unpaged:<lane>` and
+open only when you name that class, for example `--class unpaged:mail:extract`
+(quote a lane that contains spaces).
+`--ids-file <file>` (one fact id per line) narrows the set.
+
+The preview also counts every fact it leaves private, by reason: `expired`,
+`superseded`, `member_page`, `withdrawn` (forgotten or purged, at any
+visibility), `contested` (an open trust proposal, or a widening the owner
+rejected or undid), `holding_page_private`, `holding_page_missing`,
+`holding_page_quarantined`, `provenance_private`, `provenance_unresolved`,
+`provenance_quarantined` and `entity_page_private`. A page counts as private
+the same way `gbrain repair visibility` judges it (its label, a privacy alias,
+`readable_by`, a folder rule), across every row with that slug, deleted or
+not, so the tighten repair never plans to close what this opened.
+
+`--apply --expect <hash>` opens exactly the previewed window, keeping each
+fact's id, provenance, creation time and trust tier; a fact that became
+eligible inside the window since the preview refuses `preview_changed`. Each
+write locks the pages the fact names and checks it again, so a page made
+private while the apply waits keeps its facts private. A fenced row has its
+table cell set to `world` by the same label-only write the other privacy
+repairs use. A fact the apply could not open is reported `fact_left_private`
+with the reason, never as applied.
+
+The command refuses remote callers and any CLI running under
+`GBRAIN_ENFORCED_MEMBER`, and it never runs from `gbrain repair --all`,
+`gbrain doctor` or the remediation plan.
+
+Every change is written ahead to
+`~/.gbrain/repair/open-facts/<brain>.jsonl` (under `$GBRAIN_HOME/.gbrain/` if
+set). To undo:
+
+```bash
+gbrain repair open-facts --source <id> --undo <ledger> --json
+gbrain repair open-facts --source <id> --undo <ledger> --apply --expect <preview_hash>
+```
+
+Undo reads the ledger you name and refuses one that is missing
+(`undo_ledger_missing`) or that records another brain
+(`undo_ledger_wrong_brain`) or another source (`undo_ledger_wrong_source`).
+It re-privates the facts the ledger opened that are still world and
+unchanged, and counts the rest as skipped (`expired`, `superseded`,
+`changed`, `already_private`, `gone`). A fact whose write confirmed after the
+run stopped waiting has only its intent line; undo closes it too, unless it
+was already world before that run (`world_before_run`) or an accepted trust
+proposal widened it since (`widened_by_proposal`). It restores the label only: anything
+a remote caller read while a fact was world stays read.
+
+On a personal brain where every remote caller is you, you may not need this
+at all: bind the client to the owner instead (`gbrain access owner set`, then
+`gbrain auth rescope --client <id> --member <owner>`), and it reads private
+facts without opening them to anyone else.
+
### Lost fence rows
A page rewrite that drops its `## Facts` or takes section is safe on its
@@ -4918,6 +4992,10 @@ type and mode at apply time). They are excluded everywhere else:
- The `gbrain post-upgrade` banner prints such a finding as
`<check>: N (explicit_kind_required; preview with: gbrain repair <kind>)`.
+`open-facts` is not in these lists: its preview needs `--source` and
+`--created-before`, which only you can name, so no listed command would run
+as printed.
+
A remediation step or any other runner that reaches an explicit-only kind
without its name refuses with `explicit_kind_required`. A build that does not
implement the kind refuses with `unavailable`.
diff --git a/docs/operations/mcp-surface-runbook.md b/docs/operations/mcp-surface-runbook.md
index f27ffeef67..9995c06b21 100644
--- a/docs/operations/mcp-surface-runbook.md
+++ b/docs/operations/mcp-surface-runbook.md
@@ -227,6 +227,11 @@ the database before limits and aggregate calculations. A gated page reads exactl
like a missing one (no existence oracle), and link/graph output never
enumerates private slugs.
+Facts are separate: a fact stamped `private` (as every fact was before
+`facts.default_visibility` became `world`) stays hidden from remote callers
+that are not the owner until the operator opens it with
+`gbrain repair open-facts` (docs/guides/repair.md); no remote path opens it.
+
Single-user brains where every connected agent is equally trusted can opt
out:
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 69c3c9d8da..3f308bb0a3 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -307,7 +307,9 @@ Save ONE fact with mandatory attribution.
`share: true`, and its `visibility: "world"` is refused; the brain owner's
own credential saves as above (shared by default, `private` on its member
page when it asks or the page or default keeps facts private). The response
- names the `page` and `visibility` the fact got.
+ names the `page` and `visibility` the fact got. Facts saved `private` before
+ the default became `world` stay private until the operator runs
+ `gbrain repair open-facts` on the brain host (no remote verb opens them).
Response: `{ id, status, status_text, entity_slug, valid_until,
protocol_version }` (+ `degraded_dedup: true` when no embedding provider —
diff --git a/llms-full.txt b/llms-full.txt
index 1f50816f92..03715c301a 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -8243,7 +8243,9 @@ Save ONE fact with mandatory attribution.
`share: true`, and its `visibility: "world"` is refused; the brain owner's
own credential saves as above (shared by default, `private` on its member
page when it asks or the page or default keeps facts private). The response
- names the `page` and `visibility` the fact got.
+ names the `page` and `visibility` the fact got. Facts saved `private` before
+ the default became `world` stay private until the operator runs
+ `gbrain repair open-facts` on the brain host (no remote verb opens them).
Response: `{ id, status, status_text, entity_slug, valid_until,
protocol_version }` (+ `degraded_dedup: true` when no embedding provider —
diff --git a/plugin-variants/gbrain-coding/skills/conventions/page-privacy.md b/plugin-variants/gbrain-coding/skills/conventions/page-privacy.md
index d4a471c97b..a4f2f5a861 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/page-privacy.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/page-privacy.md
@@ -11,7 +11,8 @@ Every page you write carries no `visibility`, no `access` and no `readable_by` u
Research, project, ops, people, company and meeting pages and summaries of world pages get nothing.
Never write `access:` or `confidentiality:` on a page: gbrain reads only a few values as private and ignores the rest
(`access: personal` reads as world and can reach git; a write says so with `privacy_label_ignored`).
-Never remove a privacy label you did not set unless the user asks; the bulk path is `gbrain repair private-labels`.
+Never remove a privacy label you did not set unless the user asks; the bulk path is `gbrain repair private-labels`
+(facts saved private before the world default: `gbrain repair open-facts`, on the user's go).
The brain owner's agents (credentials bound to `gbrain access owner`) read private pages; every other remote caller
gets `not_found`. Full definition: `docs/guides/access-designations.md`.
diff --git a/plugin-variants/gbrain-daily/skills/conventions/page-privacy.md b/plugin-variants/gbrain-daily/skills/conventions/page-privacy.md
index d4a471c97b..a4f2f5a861 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/page-privacy.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/page-privacy.md
@@ -11,7 +11,8 @@ Every page you write carries no `visibility`, no `access` and no `readable_by` u
Research, project, ops, people, company and meeting pages and summaries of world pages get nothing.
Never write `access:` or `confidentiality:` on a page: gbrain reads only a few values as private and ignores the rest
(`access: personal` reads as world and can reach git; a write says so with `privacy_label_ignored`).
-Never remove a privacy label you did not set unless the user asks; the bulk path is `gbrain repair private-labels`.
+Never remove a privacy label you did not set unless the user asks; the bulk path is `gbrain repair private-labels`
+(facts saved private before the world default: `gbrain repair open-facts`, on the user's go).
The brain owner's agents (credentials bound to `gbrain access owner`) read private pages; every other remote caller
gets `not_found`. Full definition: `docs/guides/access-designations.md`.
diff --git a/plugin/skills/conventions/page-privacy.md b/plugin/skills/conventions/page-privacy.md
index d4a471c97b..a4f2f5a861 100644
--- a/plugin/skills/conventions/page-privacy.md
+++ b/plugin/skills/conventions/page-privacy.md
@@ -11,7 +11,8 @@ Every page you write carries no `visibility`, no `access` and no `readable_by` u
Research, project, ops, people, company and meeting pages and summaries of world pages get nothing.
Never write `access:` or `confidentiality:` on a page: gbrain reads only a few values as private and ignores the rest
(`access: personal` reads as world and can reach git; a write says so with `privacy_label_ignored`).
-Never remove a privacy label you did not set unless the user asks; the bulk path is `gbrain repair private-labels`.
+Never remove a privacy label you did not set unless the user asks; the bulk path is `gbrain repair private-labels`
+(facts saved private before the world default: `gbrain repair open-facts`, on the user's go).
The brain owner's agents (credentials bound to `gbrain access owner`) read private pages; every other remote caller
gets `not_found`. Full definition: `docs/guides/access-designations.md`.
diff --git a/scripts/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjs
index 4d936112e3..46f0234011 100644
--- a/scripts/check-core-guard-coverage.mjs
+++ b/scripts/check-core-guard-coverage.mjs
@@ -51,6 +51,7 @@ const EXEMPT = {
'src/core/repair/extractor-facts.ts': 'owner-run repair restoring expired fact rows',
'src/core/repair/unwithdrawn-facts.ts': 'owner-run, preview-bound repair putting expired fact rows back to their recorded before-state (row number and lifecycle); page text is unchanged',
'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/open-facts.ts': 'owner-run, preview-first repair (#8194): its own intent only changes the visibility of named database-only fact rows in place; fenced rows publish through the keep_trust maintenance page, which preparePageMutation guards (openFactsPublication wraps it)',
'src/core/repair/visibility.ts': 'owner-run, preview-first repair that only tightens database-only fact rows from world to private; page text is unchanged (fenced rows and page labels publish through put_page, preparePageMutation)',
'src/core/repair/purged-page-facts.ts': 'owner-run repair expiring fact rows of pages that no longer exist (shrinks only; no page text)',
'src/core/repair/conversation-labels.ts': 'owner-run repair expiring fact rows and writing an outcome row (shrinks only; page text unchanged)',
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index 11e1829ba8..b16ed18506 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -580,6 +580,8 @@ src/core/repair/lost-fence-rows.ts plannedPage call:serializePageToMarkdown SEGW
src/core/repair/lost-fence-rows.ts plannedPage field SEGW materializedSnapshot within the single-string ceiling; over it counts as fence_unreadable (segmentedOverCeiling, checked before the read)
src/core/repair/lost-fence-rows.ts scanLostFenceRows field SEGW materializedSnapshot within the single-string ceiling; over it counts as fence_unreadable (segmentedOverCeiling, checked before the read)
src/core/repair/lost-fence-rows.ts scanLostFenceRows 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/open-facts.ts applyFence call:serializePageToMarkdown INLINE inline pages only: a segmented page returns before the read and its fenced facts stay private for the owner
+src/core/repair/open-facts.ts applyFence field INLINE inline pages only: a segmented page returns before the read and its fenced facts stay private for the owner
src/core/repair/origin-carry.ts stamp call:serializePageToMarkdown SEGW a segmented page fails before the read (segmented_page) and parks its origin
src/core/repair/orphan-children.ts PROBE_SQL sql META
src/core/repair/overwritten-edits.ts previewEdit call:serializePageToMarkdown SEGW only high-confidence edits (live page and version both inline at scan time) are previewed; a page whose revision moved since the scan is skipped before it is serialized
diff --git a/skills/conventions/page-privacy.md b/skills/conventions/page-privacy.md
index d4a471c97b..a4f2f5a861 100644
--- a/skills/conventions/page-privacy.md
+++ b/skills/conventions/page-privacy.md
@@ -11,7 +11,8 @@ Every page you write carries no `visibility`, no `access` and no `readable_by` u
Research, project, ops, people, company and meeting pages and summaries of world pages get nothing.
Never write `access:` or `confidentiality:` on a page: gbrain reads only a few values as private and ignores the rest
(`access: personal` reads as world and can reach git; a write says so with `privacy_label_ignored`).
-Never remove a privacy label you did not set unless the user asks; the bulk path is `gbrain repair private-labels`.
+Never remove a privacy label you did not set unless the user asks; the bulk path is `gbrain repair private-labels`
+(facts saved private before the world default: `gbrain repair open-facts`, on the user's go).
The brain owner's agents (credentials bound to `gbrain access owner`) read private pages; every other remote caller
gets `not_found`. Full definition: `docs/guides/access-designations.md`.
diff --git a/skills/skills.lock.history.json b/skills/skills.lock.history.json
index 6bde8874a6..613c74d2ca 100644
--- a/skills/skills.lock.history.json
+++ b/skills/skills.lock.history.json
@@ -339,7 +339,8 @@
"fb7ae8746a578500d6789b68ff40049037aa4d337b65b42f7c1745ae7080c2db"
],
"conventions/page-privacy.md": [
- "ccaa3f8f996eca27cfc57a7c1b0d1979057c8253f9b7672fed31183e569410c9"
+ "ccaa3f8f996eca27cfc57a7c1b0d1979057c8253f9b7672fed31183e569410c9",
+ "f2fb32fa6e89a2fb4d2f68050cb164e0207a13d6745f2cb76db49bea2840eef5"
],
"conventions/path-discipline.md": [
"8af5415721bd115e6979c96688bcf542a32675809ada9aaedbb6706a40926954"
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index d2d17ddd9a..9328589f45 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -53,7 +53,7 @@
"conventions/exec-output.md": "75f3abbc4041413bd4ee38af44fe82e91657b2c84525e6b92f627400e0abab47",
"conventions/line-grammar.md": "9d00254359153064e9fc0959d8c15743b5ff860890ed556178185bee32c7aeb1",
"conventions/model-routing.md": "c0d5031e4372c108d7e94346dc2958c21389f3b67544524578bbc9ea32d53c34",
- "conventions/page-privacy.md": "ccaa3f8f996eca27cfc57a7c1b0d1979057c8253f9b7672fed31183e569410c9",
+ "conventions/page-privacy.md": "f2fb32fa6e89a2fb4d2f68050cb164e0207a13d6745f2cb76db49bea2840eef5",
"conventions/path-discipline.md": "8af5415721bd115e6979c96688bcf542a32675809ada9aaedbb6706a40926954",
"conventions/quality.md": "8aa681001114689d34268ccadaf0e2ff07b8f68aa5987c093a8c4a7a744f12a6",
"conventions/regex-discipline.md": "d96a9baa6f27184e165889a9c655607366a739d851684d9f41cdec294f99edac",
@@ -226,7 +226,7 @@
"skillpack-check/SKILL.md": "0d2d2d201ed72e19b47d7e3743b5bbdfb5c2655d1f34d29447c601fca3908f9e",
"skillpack-harvest/SKILL.md": "0f86314b58d25b5511809f567c04aedc3fba6fe35ed642ac52d8216ae365b6eb",
"skillpack-harvest/routing-eval.jsonl": "cb4783288e95af3132b32ecb40a54cffc095f57b36240f96a25c2d2adf5e68c6",
- "skills.lock.history.json": "478c9e8fc345301496c2d493db4d5859191a211cd56790d461645c440d461791",
+ "skills.lock.history.json": "09610dd63a53ebb252ff98d9f0058d84a5d01c27e2279b971c2c0af2de9c349c",
"smoke-test/SKILL.md": "f5099e1d2ab9dc6827096249e68414f7ae357c29b39fb069a54bb7fb74f414a5",
"soul-audit/SKILL.md": "7a48e180849f7502d332878c443397f90a3756f45caa94f76bcfcc7c997469c8",
"storage-manifest/SKILL.md": "1debbefba61007a17cda1525496875d1edfde90642adf3ec031f25a71724807e",
diff --git a/src/commands/repair-open-facts.ts b/src/commands/repair-open-facts.ts
new file mode 100644
index 0000000000..b87bdb3a06
--- /dev/null
+++ b/src/commands/repair-open-facts.ts
@@ -0,0 +1,35 @@
+/**
+ * The CLI side of `gbrain repair open-facts` (#8194), so the repair core touches no filesystem (GBRA-248): its undo
+ * ledger at <gbrain home>/repair/open-facts/<brain_id>.jsonl (0700 directory, 0600 file, as private-labels keeps its
+ * own) and the fact ids an `--ids-file` lists.
+ */
+import { existsSync, readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { opError } from '../core/ops/contract.ts';
+import type { OpenFactsLedger, OpenFactsLedgerLine } from '../core/repair/open-facts.ts';
+import { ledgerAt, repairLedger } from './repair-private-labels.ts';
+
+export const openFactsLedger = (brainId: string): OpenFactsLedger => repairLedger<OpenFactsLedgerLine>('open-facts', brainId);
+
+/** `--undo <ledger>`: the ledger at that path, whose lines the undo plans from and appends to; a missing file refuses `undo_ledger_missing`. */
+export function openFactsUndoLedger(path: string): OpenFactsLedger {
+ const full = resolve(path);
+ if (!existsSync(full)) {
+ throw opError('invalid_params', `--undo ${path}: no ledger file is there, so nothing was planned.`,
+ 'Pass the ledger path the apply printed; gbrain keeps it in ~/.gbrain/repair/open-facts/ (in $GBRAIN_HOME/.gbrain/repair/open-facts/ when GBRAIN_HOME is set).', { reason: 'undo_ledger_missing' });
+ }
+ return ledgerAt<OpenFactsLedgerLine>(full, false);
+}
+
+/** The fact ids a file lists, one per line; blank lines and # comments are skipped. */
+export function readFactIdsFile(path: string): number[] {
+ const refused = (why: string) => opError('invalid_params', `--ids-file ${path} ${why}.`, 'Pass a readable file with one fact id per line (# starts a comment), e.g. the ids a preview listed.',
+ { reason: 'ids_file_unreadable' });
+ let text: string;
+ try { text = readFileSync(path, 'utf8'); } catch (error) { throw refused(`could not be read (${(error as NodeJS.ErrnoException).code ?? 'error'})`); }
+ const lines = text.split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith('#'));
+ const bad = lines.find(line => !/^[1-9]\d{0,15}$/.test(line));
+ if (bad !== undefined) throw refused(`lists "${bad.slice(0, 40)}", which is not a fact id`);
+ if (!lines.length) throw refused('lists no fact id');
+ return lines.map(Number);
+}
diff --git a/src/commands/repair-private-labels.ts b/src/commands/repair-private-labels.ts
index 8548ee6fb7..aa827d4da8 100644
--- a/src/commands/repair-private-labels.ts
+++ b/src/commands/repair-private-labels.ts
@@ -11,7 +11,19 @@ import { gbrainPath } from '../core/config.ts';
import type { PrivateLabelsLedger } from '../core/repair/private-labels.ts';
export function privateLabelsLedger(brainId: string): PrivateLabelsLedger {
- const path = gbrainPath('repair', 'private-labels', `${brainId.replace(/[^A-Za-z0-9._-]/g, '_')}.jsonl`);
+ return repairLedger('private-labels', brainId);
+}
+
+/** A repair kind's undo ledger at <gbrain home>/repair/<kind>/<brain_id>.jsonl (`gbrain repair open-facts` keeps one too). */
+export function repairLedger<Line>(kind: string, brainId: string): { path: string; lines: unknown[]; unreadable: number; record(line: Line): void } {
+ return ledgerAt<Line>(gbrainPath('repair', kind, `${brainId.replace(/[^A-Za-z0-9._-]/g, '_')}.jsonl`), true);
+}
+
+/**
+ * The JSONL ledger at `path`: its parsed lines, the count it could not parse, and an append that keeps the file 0600.
+ * `ownDir`: the directory is gbrain's own, created 0700; a ledger the operator named elsewhere leaves its directory as it is.
+ */
+export function ledgerAt<Line>(path: string, ownDir: boolean): { path: string; lines: unknown[]; unreadable: number; record(line: Line): void } {
const lines: unknown[] = [];
let unreadable = 0;
for (const text of existsSync(path) ? readFileSync(path, 'utf8').split('\n') : []) {
@@ -19,8 +31,10 @@ export function privateLabelsLedger(brainId: string): PrivateLabelsLedger {
try { lines.push(JSON.parse(text)); } catch { unreadable++; }
}
return { path, lines, unreadable, record(line) {
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
- chmodSync(dirname(path), 0o700);
+ if (ownDir) {
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
+ chmodSync(dirname(path), 0o700);
+ }
appendFileSync(path, `${tornTail(path) ? '\n' : ''}${JSON.stringify(line)}\n`, { mode: 0o600 });
chmodSync(path, 0o600);
} };
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 755a32c55a..71096b82cf 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -40,6 +40,8 @@ import { normalizeSeatLabel } from '../core/context/seat.ts';
import { agentSessionFlagArgs } from '../core/repair/agent-session-facts.ts';
import { fileDriftConsentText } from '../core/repair/file-drift.ts';
import { privateLabelsLedger } from './repair-private-labels.ts';
+import { openFactsLedger, openFactsUndoLedger, readFactIdsFile } from './repair-open-facts.ts';
+import { createdBeforeRequired, memberModeRefused } from '../core/repair/open-facts.ts';
import { isAbsolute } from 'node:path';
import { readFileSync } from 'node:fs';
@@ -230,16 +232,16 @@ Proposed readers for the pages every member's key reads (visibility --propose):
Renames whose identity sync did not keep (rename-identity): docs/guides/live-sync.md#renaming-a-page.`;
const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--include-cross-entity', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force', '--close', '--held', '--allow-without-owner', '--propose']);
-const VALUE_FLAGS = new Set(['--readers', '--slugs-file', '--out', '--rules', '--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from', '--side', '--state', '--after', '--cursor', '--provenance', '--kind', '--mode', '--run', '--key', '--generation', '--day', '--cwd', '--session', '--principal']);
+const VALUE_FLAGS = new Set(['--readers', '--slugs-file', '--out', '--rules', '--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from', '--side', '--state', '--after', '--cursor', '--provenance', '--kind', '--mode', '--run', '--key', '--generation', '--day', '--cwd', '--session', '--principal', '--created-before', '--ids-file', '--undo']);
/** Flags only some kinds accept, with the kinds that do. */
const KIND_FLAGS: Record<string, readonly string[]> = {
'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins', 'rename-identity', 'url-clone-fences'],
'--include-cross-entity': ['duplicate-facts'],
- '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins', 'moved-pages', 'timeline-order', 'contact-rows', 'provenance', 'secret-spans', 'segmented-tiling', 'visibility'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift', 'visibility', 'private-labels'], '--since': ['file-drift', 'generations'],
+ '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins', 'moved-pages', 'timeline-order', 'contact-rows', 'provenance', 'secret-spans', 'segmented-tiling', 'visibility'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift', 'visibility', 'private-labels', 'open-facts'], '--since': ['file-drift', 'generations'],
'--held': ['file-drift', 'generations'], '--side': ['file-drift'], '--state': ['file-drift'], '--cursor': ['file-drift'], '--provenance': ['file-drift'],
'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],
'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],
- '--after': ['uncommitted-deletions'],
+ '--after': ['uncommitted-deletions', 'open-facts'], '--created-before': ['open-facts'], '--ids-file': ['open-facts'], '--undo': ['open-facts'],
'--kind': ['generations'], '--mode': ['generations'], '--run': ['generations'], '--key': ['generations'], '--generation': ['generations'], '--day': ['fact-claim-dates'], '--rules': ['secret-spans'],
'--cwd': ['agent-session-facts'], '--session': ['agent-session-facts'], '--principal': ['agent-session-facts'],
'--readers': ['visibility'], '--slugs-file': ['visibility'], '--allow-without-owner': ['visibility'], '--propose': ['visibility'], '--out': ['visibility'],
@@ -248,7 +250,7 @@ const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit
'--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required', '--since': '7d', '--side': 'deleted', '--state': 'tombstone_edited', '--keep': 'prior',
'--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d', '--from': 'notes/old', '--after': '1200', '--cursor': 'NEXT_CURSOR', '--provenance': 'never_committed',
'--kind': 'atom', '--mode': 'restore', '--run': 'RUN_ID', '--key': 'page:notes/a', '--generation': '42', '--day': '2026-01-15', '--rules': 'openai,aws_access_key',
- '--cwd': '/srv/agent-workers', '--session': 'SESSION_ID', '--principal': 'worker-a', '--readers': 'alice-example,group:team-a', '--slugs-file': 'slugs.txt', '--out': '/srv/proposals' };
+ '--cwd': '/srv/agent-workers', '--session': 'SESSION_ID', '--principal': 'worker-a', '--created-before': '2026-06-01T00:00:00Z', '--ids-file': 'ids.txt', '--undo': 'LEDGER_PATH', '--readers': 'alice-example,group:team-a', '--slugs-file': 'slugs.txt', '--out': '/srv/proposals' };
/** A usage refusal whose fix is the read-only preview (gbrain repair without --apply writes nothing). */
const invalid = (message: string, suggestion: string, preview: string[] = ['gbrain', 'repair', '--json']) => opError('invalid_params', message, suggestion,
{ fix: readFix('Previews the repair; without --apply it writes nothing.', { argv: preview }) });
@@ -259,7 +261,9 @@ interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolea
held: boolean; side?: string; state?: string; provenance?: string; cursor?: string;
keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean; from?: string; close: boolean; afterPage?: number;
generationKind?: string; generationMode?: string; run?: string; key?: string; generation?: number; day?: string; rules?: string[];
- cwdPrefixes: string[]; sessions: string[]; principal?: string; readers?: string; slugsFile?: string; allowWithoutOwner: boolean; propose: boolean; out?: string }
+ cwdPrefixes: string[]; sessions: string[]; principal?: string; readers?: string; slugsFile?: string; allowWithoutOwner: boolean; propose: boolean; out?: string;
+ /** `open-facts` (#8194): every --class value, the cut, the ids file and the ledger to undo. */
+ classes: string[]; createdBefore?: string; idsFile?: string; undo?: string }
/** `--max-usd` on a kind that never calls a paid model: the cap belongs to the doctor remediation run. */
function maxUsdRefusal(flag: string, cap: string | undefined, kind: string | undefined): OperationError {
@@ -303,7 +307,7 @@ function readSlugsFile(path: string): string[] {
/** Strict parse: every flag is known, value flags carry a value, at most one kind. */
export function parseRepairArgs(args: string[]): RepairArgs {
const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false, includeCrossEntity: false, diff: false, yes: false, noLlm: false, only: [], skip: [], slugs: [],
- allDrifted: false, held: false, requests: [], includeFailures: false, force: false, close: false, cwdPrefixes: [], sessions: [], allowWithoutOwner: false, propose: false };
+ allDrifted: false, held: false, requests: [], includeFailures: false, force: false, close: false, cwdPrefixes: [], sessions: [], allowWithoutOwner: false, propose: false, classes: [] };
const used = new Set<string>();
const positional: string[] = [];
let maxUsdText: string | undefined;
@@ -359,7 +363,16 @@ export function parseRepairArgs(args: string[]): RepairArgs {
}
else if (flag === '--request') parsed.requests.push(value);
else if (flag === '--from') parsed.from = value;
- else if (flag === '--class') parsed.driftClass = value;
+ else if (flag === '--class') { parsed.driftClass = value; parsed.classes.push(value); }
+ else if (flag === '--created-before') {
+ if (!/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2}))?$/.test(value) || !Number.isFinite(Date.parse(value))) {
+ throw opError('invalid_params', `--created-before takes an ISO-8601 instant (got "${value}").`,
+ 'Pass the instant facts.default_visibility became world on this brain with its offset, e.g. --created-before 2026-06-01T00:00:00Z; a date alone (2026-06-01) is read as midnight UTC.', { reason: 'created_before_invalid' });
+ }
+ parsed.createdBefore = new Date(value).toISOString();
+ }
+ else if (flag === '--ids-file') parsed.idsFile = value;
+ else if (flag === '--undo') parsed.undo = value;
else if (flag === '--side') parsed.side = value;
else if (flag === '--state') parsed.state = value;
else if (flag === '--cursor') parsed.cursor = value;
@@ -469,6 +482,15 @@ export function parseRepairArgs(args: string[]): RepairArgs {
throw new OperationError('invalid_params', `--include-ambiguous applies only to an explicit-only kind named on the command line (${explicitKinds}).`,
`Preview one by name: ${repairPreviewCommand(EXPLICIT_REPAIR_REGISTRY[0]!.kind)}`);
}
+ if (parsed.kind === 'open-facts') {
+ const bad = parsed.classes.find(cls => cls !== 'fenced' && cls !== 'unfenced' && !(cls.startsWith('unpaged:') && cls.slice('unpaged:'.length).trim() !== ''));
+ if (bad !== undefined) throw opError('invalid_params', `--class for gbrain repair open-facts is fenced, unfenced or unpaged:<lane> (got "${bad}").`,
+ 'Pass a class the preview counts under eligible, e.g. --class unpaged:mail:extract, or omit --class for fenced and unfenced facts.', { reason: 'class_invalid' });
+ if (parsed.undo !== undefined && (parsed.createdBefore !== undefined || parsed.classes.length || parsed.idsFile !== undefined || parsed.afterPage !== undefined)) {
+ throw invalid('--undo takes only --source: it re-privates what its ledger recorded.', `Preview the undo on its own: gbrain repair open-facts${parsed.source ? ` --source ${parsed.source}` : ''} --undo ${parsed.undo}`,
+ ['gbrain', 'repair', 'open-facts', ...(parsed.source ? ['--source', parsed.source] : []), '--undo', parsed.undo, '--json']);
+ }
+ }
return parsed;
}
@@ -528,7 +550,15 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }
const { kind, apply, all, json, noEmbed, includeAmbiguous, includeCrossEntity, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText,
prefer, requests, allDrifted, driftClass, since, held, side, state, provenance, cursor, keep, requestId, olderThan, includeFailures, force, from, close, afterPage,
- generationKind, generationMode, run, key, generation, day, rules, cwdPrefixes, sessions, principal, readers, slugsFile, allowWithoutOwner, propose, out } = parseRepairArgs(args);
+ generationKind, generationMode, run, key, generation, day, rules, cwdPrefixes, sessions, principal, readers, slugsFile, allowWithoutOwner, propose, out,
+ classes, createdBefore, idsFile, undo } = parseRepairArgs(args);
+ if (kind === 'open-facts') {
+ if (process.env.GBRAIN_ENFORCED_MEMBER !== undefined) throw memberModeRefused();
+ if (!source) throw opError('invalid_params', 'gbrain repair open-facts opens facts in one named source.', 'Name one source with --source (gbrain sources list --json lists them).',
+ { reason: 'source_required' });
+ if (undo === undefined && createdBefore === undefined) throw createdBeforeRequired();
+ }
+ const openFactIds = kind === 'open-facts' && idsFile !== undefined ? readFactIdsFile(idsFile) : undefined;
if (propose) {
if (source) await resolveRepairScope(engine, source);
const { proposeVisibility, proposalLines } = await import('./repair-propose.ts');
@@ -599,6 +629,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),
...(k === kind && (k === 'visibility' || k === 'private-labels') && driftClass ? { driftClass } : {}),
...(k === kind && k === 'private-labels' ? { privateLabelsLedger: privateLabelsLedger(scope.brain_id) } : {}),
+ ...(k === kind && k === 'open-facts' ? { openFacts: { classes, ledger: undo !== undefined ? openFactsUndoLedger(undo) : openFactsLedger(scope.brain_id), ...(createdBefore !== undefined ? { createdBefore } : {}),
+ ...(openFactIds ? { ids: openFactIds } : {}), ...(idsFile !== undefined ? { idsFile } : {}), ...(undo !== undefined ? { undo } : {}) } } : {}),
...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since, ...(held ? { held } : {}), ...(side ? { side } : {}), ...(state ? { state } : {}), ...(provenance ? { provenance } : {}), ...(cursor ? { cursor } : {}),
progress: createProgress(cliOptsToProgressOptions(getCliOptions())) } : {}),
...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index d33235b8ed..d159b613dc 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--only', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--room', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--card', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--filter', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--preview', '--privacy-url', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--alert', '--aliases', '--all', '--all-drifted', '--all-from', '--all-sources', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--body', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--calls', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--concurrent', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--days', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--drop-field', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--finalize', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--from-prefix', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--gbrain-skill-resolver', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--history', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--labelled-only', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extensions', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-open-pages', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--priority', '--privacy-url', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--push-remote', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--read-sources', '--reader-mode', '--readers', '--reads-unscoped', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--room', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--strict-json', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--synopsis', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--terms-url', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unschedule', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--wakeshift', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--alert', '--aliases', '--all', '--all-drifted', '--all-from', '--all-sources', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--body', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--calls', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--concurrent', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--created-before', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--days', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--drop-field', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--finalize', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--from-prefix', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--gbrain-skill-resolver', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--history', '--hold-state', '--holds', '--home', '--http', '--id', '--ids-file', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--labelled-only', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extensions', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-open-pages', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--priority', '--privacy-url', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--push-remote', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--read-sources', '--reader-mode', '--readers', '--reads-unscoped', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--room', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--strict-json', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--synopsis', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--terms-url', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--undo', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unschedule', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--wakeshift', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--card', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--expected-revision', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--privacy-url', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -114,7 +114,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'reindex-search-vector': ['--accept-pending', '--as', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--room', '--source', '--timeout', '--timings', '--wait', '--yes'],
'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--check', '--code', '--concurrency', '--confirm-destructive', '--content-root', '--cursor', '--db-only', '--detail', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--hold-state', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer', '--prefer-postgres', '--preview', '--priority', '--provenance', '--query', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--request-id', '--scopes', '--source', '--timeout'],
- 'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--allow-without-owner', '--apply', '--as', '--audit', '--auto-additive', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--conflicts', '--cursor', '--cwd', '--day', '--diff', '--email', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--out', '--prefer', '--prefix', '--preview', '--principal', '--probe', '--progress-interval', '--progress-json', '--propose', '--provenance', '--quiet', '--readers', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--room', '--rules', '--run', '--scopes', '--seat', '--session', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],
+ 'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--allow-without-owner', '--apply', '--as', '--audit', '--auto-additive', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--conflicts', '--created-before', '--cursor', '--cwd', '--day', '--diff', '--email', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--ids-file', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--out', '--prefer', '--prefix', '--preview', '--principal', '--probe', '--progress-interval', '--progress-json', '--propose', '--provenance', '--quiet', '--readers', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--room', '--rules', '--run', '--scopes', '--seat', '--session', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--stale', '--state', '--timeout', '--timings', '--undo', '--url', '--wait', '--yes'],
'repair-jsonb': ['--accept-pending', '--as', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--room', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--list-out', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--reads-unscoped', '--rebase', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--remove', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--stat', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
diff --git a/src/core/generations/adapters/fact-rows.ts b/src/core/generations/adapters/fact-rows.ts
index 194ea2f0db..03714970f5 100644
--- a/src/core/generations/adapters/fact-rows.ts
+++ b/src/core/generations/adapters/fact-rows.ts
@@ -20,6 +20,7 @@ import type { GenerationAdapter, GenerationKey, ItemRow } from '../contract.ts';
import { factRowIdentity, fenceRowKey, FACT_FENCE_KIND, publishFenceGeneration, type FenceGenerationOutcome, type FenceItem, type FenceRead } from '../fence.ts';
import { activateGeneration, generationKeyLock, itemSetHash, readLiveGeneration, recordHeld } from '../publish.ts';
import { factsFenceHeld } from '../fence-evidence.ts';
+import { openedFactRowSql } from '../../persistence/context.ts';
export const CONSOLIDATION_KIND = 'consolidation';
@@ -61,7 +62,8 @@ export async function factPreimages(db: BrainEngine, sourceId: string, ids: read
* are those attached to the page that the incoming fence no longer holds at the same number and claim (conversation
* extractor rows only when a fence row claims their number, #5731). #8819: of the others, only a row some fence of the
* page held, or whose claim the incoming fence states, retires (fence-evidence.ts); a row the fence never held is `kept`
- * active, since no fence edit withdrew it.
+ * active, since no fence edit withdrew it. #8194: a row `gbrain repair open-facts` opens in place (persistence/context.ts
+ * openedFactRowSql) is neither retired nor kept: fence-guard moves it to world with its id.
* Held: the caller expires nothing.
*/
export async function projectFactFenceGeneration(tx: BrainEngine, input: { sourceId: string; slug: string; read: FenceRead; incoming: string;
@@ -73,6 +75,7 @@ export async function projectFactFenceGeneration(tx: BrainEngine, input: { sourc
OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num))
AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text)
WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)
+ AND NOT ${openedFactRowSql('f', '$3')}
ORDER BY f.row_num, f.id`, [input.sourceId, input.slug, input.incoming])).map(row => row.preimage);
const extractor = (row: FactPreimage) => (row.source ?? '').startsWith('cli:extract-conversation-facts');
const { held } = await factsFenceHeld(tx, { sourceId: input.sourceId, slug: input.slug, rows: candidates.filter(row => !extractor(row)), prior: input.prior });
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 82e8427584..f598d49da6 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -29,6 +29,7 @@ import { propagateFactLowering } from '../trust/propagation.ts';
import { loadWriteGateConfig } from '../trust/gate-outcomes.ts';
import { fenceOwnerKey, readFenceBlocks, TAKE_FENCE_KIND } from '../generations/fence.ts';
import { projectFactFenceGeneration } from '../generations/adapters/fact-rows.ts';
+import { openedFactRowSql } from './context.ts';
import { fenceRowKeys, moveKeptRows, pageFenceRowKeys } from '../generations/fence-evidence.ts';
import { projectTakeFenceGeneration } from '../generations/adapters/take-rows.ts';
import { linksFenceProjectionRows, projectLinksFence } from '../links-fence-projection.ts';
@@ -737,14 +738,16 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
// Conversation-extractor rows share the page coordinate without a fence
// (#1928, as in the extract_facts reconcile); their replay owns them. A
// fence row that takes one of their row numbers wins that position.
- // #8819: only the rows the fact generation found a fence held (`retireIds`) expire.
+ // #8819: only the rows the fact generation found a fence held (`retireIds`) expire. #8194: never a row `gbrain repair
+ // open-facts` opens in place (context.ts openedFactRowSql); fence-guard moves it to world with its id.
const incoming = JSON.stringify(factRows.map(f => ({ row_num: f.row_num, fact: f.fact, visibility: f.visibility })));
const expireFacts = (ids: number[]) => () => tx.executeRaw(`UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULL
WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL AND f.id=ANY($4::bigint[])
AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%'
OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num))
AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text)
- WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)`, [sourceId, slug, incoming, ids]);
+ WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)
+ AND NOT ${openedFactRowSql('f', '$3')}`, [sourceId, slug, incoming, ids]);
// #6574: every fence row's fields refresh in one statement, not one round trip per row.
const fieldRows = JSON.stringify([...new Map(factRows.map(fact => [fact.row_num, fact])).values()].map(fact => ({ row_num: fact.row_num, kind: fact.kind, notability: fact.notability,
context: fact.context, valid_from: fact.valid_from?.toISOString() ?? null, valid_until: fact.valid_until?.toISOString() ?? null,
diff --git a/src/core/persistence/context.ts b/src/core/persistence/context.ts
index dd5c5f805b..49d17addca 100644
--- a/src/core/persistence/context.ts
+++ b/src/core/persistence/context.ts
@@ -15,6 +15,12 @@ const TRUST_SETTINGS = ['gbrain.write_trust_tier', 'gbrain.write_origin'] as con
const TRUST_PROMOTION_SETTING = 'gbrain.write_trust_promotion';
const TRUST_BACKFILL_SETTING = 'gbrain.write_trust_backfill';
const TRUST_KEEP_SETTING = 'gbrain.write_trust_keep';
+/**
+ * #8194: the fact ids an operator's `gbrain repair open-facts` opens in this transaction. Set only by withOpenFacts, which
+ * only that repair's maintenance intent and its unmanaged label door call; never keyed on gbrain.write_trust_keep, which
+ * agent fence edits also set.
+ */
+const OPEN_FACTS_SETTING = 'gbrain.write_open_facts';
/**
* Sets transaction-local settings around `fn` in one round trip each way. An
@@ -146,6 +152,25 @@ export function withTrustPromotion<T>(engine: Pick<BrainEngine, 'executeRaw'>, c
export function withTrustKeep<T>(engine: Pick<BrainEngine, 'executeRaw'>, tables: readonly TrustTable[], fn: () => Promise<T>): Promise<T> {
return withTransactionSettings(engine, [TRUST_KEEP_SETTING], outer => [[...new Set([...(outer[0] ? outer[0].split(',') : []), ...tables])].join(',')], fn);
}
+/**
+ * #8194: inside `fn`, the fence projection treats each of `factIds` whose incoming fence cell differs only private to world
+ * (same row number, same claim) as opened in place: fence-guard moves it with its new visibility keeping its id and tier,
+ * and the fact generation and the projection's expiry do not retire it (openedFactRowSql). Only `gbrain repair open-facts`
+ * calls it.
+ */
+export function withOpenFacts<T>(engine: Pick<BrainEngine, 'executeRaw'>, factIds: readonly number[], fn: () => Promise<T>): Promise<T> {
+ return withTransactionSettings(engine, [OPEN_FACTS_SETTING], () => [factIds.map(id => String(Number(id))).join(',')], fn);
+}
+/**
+ * #8194: SQL true for a stored fact row `f` that withOpenFacts names and whose cell in `incoming` (the projection's
+ * jsonb_to_recordset text of row_num, fact, visibility) is the same row number and claim at world while the row is private.
+ * False wherever the setting is unset, so every other write keeps today's behaviour.
+ */
+export function openedFactRowSql(f: string, incoming: string): string {
+ return `(${f}.visibility = 'private' AND ${f}.id::text = ANY(string_to_array(COALESCE(current_setting('${OPEN_FACTS_SETTING}', true), ''), ','))
+ AND EXISTS (SELECT 1 FROM jsonb_to_recordset(${incoming}::text::jsonb) AS o(row_num integer, fact text, visibility text)
+ WHERE o.row_num = ${f}.row_num AND o.fact = ${f}.fact AND o.visibility = 'world'))`;
+}
/** CEO-10: the deterministic backfill may move rows from `unknown` to any tier below user_confirmed. */
export function withTrustBackfill<T>(engine: Pick<BrainEngine, 'executeRaw'>, fn: () => Promise<T>): Promise<T> {
return withTransactionSettings(engine, [TRUST_BACKFILL_SETTING], () => ['on'], fn);
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index 0a547bd259..d5053c5740 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -254,14 +254,17 @@ export interface MaintenanceEventProjection { depth_slug: string; date: string;
* `labelEdit` (GST-2468): the label keys the write sets or removes; the canonical file keeps its bytes except those lines (page-prepare.ts labelEditFile).
*/
type MaintenancePageOptions = { requestId?: string; expectedRevision: string | null; file?: boolean;
- eventProjection?: MaintenanceEventProjection; derivation?: DerivationDeclaration; keepTrust?: true; labelEdit?: LabelEdit };
+ eventProjection?: MaintenanceEventProjection; derivation?: DerivationDeclaration; keepTrust?: true; labelEdit?: LabelEdit;
+ /** #8194: with keepTrust, the fence rows `gbrain repair open-facts` opens in place (repair/open-facts.ts openFactsPublication). */
+ openFacts?: Array<{ id: number; row_num: number | null; fact_md5: string }> };
/** A maintenance page publication's intent and request id; `batch` (G6) is the run's batch id, part of both. */
function maintenancePageRequest(authority: MaintenanceAuthority, slug: string, content: string, options: MaintenancePageOptions, batch?: string) {
const projection = options.eventProjection ? { event_projection: options.eventProjection } : {};
const derivation = options.derivation ? { derivation: options.derivation } : {};
const grouped = batch ? { maintenance_batch: batch } : {};
- const keep = { ...(options.keepTrust ? { keep_trust: true } : {}), ...(options.labelEdit ? { label_edit: options.labelEdit } : {}) };
+ const keep = { ...(options.keepTrust ? { keep_trust: true } : {}), ...(options.labelEdit ? { label_edit: options.labelEdit } : {}),
+ ...(options.keepTrust && options.openFacts ? { open_facts: options.openFacts } : {}) };
return { intent: { kind: 'managed_maintenance_page', content, expected_revision: options.expectedRevision, ...projection, ...derivation, ...grouped, ...keep },
requestId: options.requestId ?? maintenanceRequestId({ authority: authority.writer, slug, content, revision: options.expectedRevision, file: options.file ?? true,
...projection, ...derivation, ...grouped, ...keep }) };
@@ -676,6 +679,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, co
if (row.intent?.kind === 'managed_maintenance_agent_session_facts') return (await import('../repair/agent-session-facts.ts')).prepareAgentSessionFactsWrite(engine, row);
if (row.intent?.kind === 'managed_maintenance_restore_redacted_facts') return (await import('../repair/redacted-facts.ts')).prepareRedactedFactsRestore(engine, row);
if (row.intent?.kind === 'managed_maintenance_tighten_fact_visibility') return (await import('../repair/visibility.ts')).prepareFactVisibilityTighten(engine, row);
+ if (row.intent?.kind === 'managed_maintenance_open_fact_visibility') return (await import('../repair/open-facts.ts')).prepareOpenFactsIntent(engine, row);
if (row.intent?.kind === 'managed_maintenance_conversation_label_retire') return (await import('../repair/conversation-labels.ts')).prepareConversationLabelRetirement(engine, row);
if (row.intent?.kind === 'managed_maintenance_conversation_relink') return (await import('../facts/conversation-relink.ts')).prepareConversationRelink(engine, row);
if (row.intent?.kind === 'managed_maintenance_conversation_facts') return (await import('../facts/conversation-publication.ts')).prepareConversationFactsPublication(engine, row, config);
@@ -689,11 +693,14 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, co
const page = await preparePageMutation(engine, row.intent.expected_revision === null
? { ...row, intent: { ...row.intent, expected_revision: undefined } } : row, config, undefined, undefined, { clock });
// GST-2521: keep_trust is the owner's label door, which also raises the page's label guard.
- const prepared: PreparedMutation = row.intent.keep_trust === true ? { ...page, apply: (tx, preimage) => withTrustKeep(tx, ['pages'], async () => {
+ const kept: PreparedMutation = row.intent.keep_trust === true ? { ...page, apply: (tx, preimage) => withTrustKeep(tx, ['pages'], async () => {
const outcome = await page.apply(tx, preimage);
await raisePageLabelGuard(tx, row.source_id, row.slug);
return outcome;
}) } : page;
+ // #8194: only the owner's label door (keep_trust) may name fence rows `gbrain repair open-facts` opens in place.
+ const prepared = row.intent.keep_trust === true && row.intent.open_facts !== undefined
+ ? (await import('../repair/open-facts.ts')).openFactsPublication(row, kept) : kept;
const projection = row.intent.event_projection as MaintenanceEventProjection | undefined;
if (!projection) return prepared;
// #5523: the event page and its depth-page timeline row commit together in
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index db6182a30e..3ea659ba7a 100644
--- a/src/core/persistence/preview-approval.ts
+++ b/src/core/persistence/preview-approval.ts
@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';
/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */
export const APPROVAL_MAX_AGE_DAYS = 7;
-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'atom-fence-rows' | 'extractor-facts' | 'unwithdrawn-facts' | 'purged-page-facts' | 'conversation-labels' | 'captured-facts' | 'agent-session-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'moved-pages' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'segmented-tiling' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'contact-rows' | 'provenance' | 'secret-spans' | 'rows-behind' | 'facts-home' | 'private-labels' | 'lost-fence-rows';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'atom-fence-rows' | 'extractor-facts' | 'unwithdrawn-facts' | 'purged-page-facts' | 'conversation-labels' | 'captured-facts' | 'agent-session-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'moved-pages' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'segmented-tiling' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'contact-rows' | 'provenance' | 'secret-spans' | 'rows-behind' | 'facts-home' | 'private-labels' | 'lost-fence-rows' | 'open-facts';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index c785ae4c69..d2ed388aac 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -52,9 +52,10 @@ import { classifyItemFailure, ItemRun, type ItemFailure } from '../item-failure.
import type { ProgressReporter } from '../progress.ts';
import type { GenerationsSelection } from '../generations/repair.ts';
import type { PrivateLabelsLedger } from './private-labels.ts';
+import type { OpenFactsRequest } from './open-facts.ts';
import type { ReadersRequest } from './readers.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'purged-page-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'moved-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'lost-fence-rows', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'facts-home', 'access', 'private-labels'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'purged-page-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'moved-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'lost-fence-rows', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'facts-home', 'access', 'private-labels', 'open-facts'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
@@ -151,6 +152,8 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb
cwdPrefixes?: string[]; sessions?: string[]; principal?: string;
/** `private-labels`: the undo ledger the CLI keeps (its path, lines for --class restore, and the append). */
privateLabelsLedger?: PrivateLabelsLedger;
+ /** `open-facts` (#8194): the selection the CLI parsed and its undo ledger. */
+ openFacts?: OpenFactsRequest;
/** `visibility` (GST-2476): set the named pages' readers (`--readers`, `--allow-without-owner`, `--slugs-file`; repair/readers.ts). */
readers?: ReadersRequest }
@@ -379,7 +382,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s
prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;
provenance?: string; cursor?: string; progress?: ProgressReporter;
keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number; generations?: GenerationsSelection; day?: string; rules?: string[];
- cwdPrefixes?: string[]; sessions?: string[]; principal?: string; privateLabelsLedger?: PrivateLabelsLedger; readers?: ReadersRequest;
+ cwdPrefixes?: string[]; sessions?: string[]; principal?: string; privateLabelsLedger?: PrivateLabelsLedger; readers?: ReadersRequest; openFacts?: OpenFactsRequest;
spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;
/** GBRA-133: the CLI's termination signal; the apply stops before the next item with a result instead of dying mid-run. */
stop?: AbortSignal;
@@ -413,7 +416,8 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
...(opts.limit !== undefined ? { limit: opts.limit } : {}), ...(opts.generations ? { generations: opts.generations } : {}),
...(opts.day ? { day: opts.day } : {}), ...(opts.rules?.length ? { rules: opts.rules } : {}),
...(opts.cwdPrefixes?.length ? { cwdPrefixes: opts.cwdPrefixes } : {}), ...(opts.sessions?.length ? { sessions: opts.sessions } : {}), ...(opts.principal ? { principal: opts.principal } : {}),
- ...(opts.privateLabelsLedger ? { privateLabelsLedger: opts.privateLabelsLedger } : {}), ...(opts.readers ? { readers: opts.readers } : {}) };
+ ...(opts.privateLabelsLedger ? { privateLabelsLedger: opts.privateLabelsLedger } : {}), ...(opts.readers ? { readers: opts.readers } : {}),
+ ...(opts.openFacts ? { openFacts: opts.openFacts } : {}) };
const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);
const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;
const counters = await capacity(ctx);
diff --git a/src/core/repair/label-write.ts b/src/core/repair/label-write.ts
index 4c0f4fdc26..83bb698188 100644
--- a/src/core/repair/label-write.ts
+++ b/src/core/repair/label-write.ts
@@ -72,10 +72,11 @@ export async function importAtRevision(engine: BrainEngine, page: { source_id: s
* (`sync.write_through` off, a clone gbrain pulls, an unresolvable target, a write error) is held `file_backed` with
* nothing written, since a database-only write would come back from the file at the next sync. A page with no file on
* purpose (no checkout configured, a non-canonical target) or whose recorded file is gone writes the database only.
- * The revision written; null when the page moved.
+ * `afterImport` runs in the same transaction after the import and before the file is written, so what it throws leaves
+ * the page, the file and its own rows unwritten. The revision written; null when the page moved.
*/
export async function writeLabelFile(engine: BrainEngine, page: { source_id: string; slug: string }, write: { revision: string; content: string; edit: LabelEdit; embed: boolean;
- preview: string; path: string }): Promise<string | null | RepairItemOutcome> {
+ preview: string; path: string; afterImport?: (tx: BrainEngine) => Promise<void> }): Promise<string | null | RepairItemOutcome> {
const ref = `${page.source_id}:${page.slug}`;
const held = (why: string): RepairItemOutcome => ({ applied: false, outcome: 'file_backed', detail: { path: write.path },
reason: `${ref} has a file in its source's checkout (${write.path}) that this repair cannot write (${why}), and a database-only write would come back from the file `
@@ -89,7 +90,7 @@ export async function writeLabelFile(engine: BrainEngine, page: { source_id: str
`Run gbrain sync --source ${page.source_id}, then preview ${write.preview} again.`);
const before = file.target?.expectedFileBytes ?? null;
const snapshot = before === null ? null : await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });
- if (before === null || !snapshot) return importAtRevision(engine, page, write.revision, write.content, write.embed, write.preview);
+ if (before === null || !snapshot) return importAtRevision(engine, page, write.revision, write.content, write.embed, write.preview, write.afterImport);
if (snapshot.revision !== write.revision) return null;
const fit = labelEditFit(page.slug, Buffer.from(before, 'utf8'), write.content, write.edit, snapshot);
if (typeof fit !== 'string') throw labelEditRefused(page, fit.keys, write.edit);
@@ -97,6 +98,7 @@ export async function writeLabelFile(engine: BrainEngine, page: { source_id: str
let unwritable: string | undefined;
try {
return await importAtRevision(engine, page, write.revision, text, write.embed, write.preview, async tx => {
+ await write.afterImport?.(tx);
const written = await writePageThrough(tx, page.slug, { sourceId: page.source_id, expectedFileBytes: before, fileText: text });
if (written.written) return;
if (written.skipped !== 'file_changed') unwritable = written.skipped ?? written.error ?? 'the write failed';
diff --git a/src/core/repair/open-facts.ts b/src/core/repair/open-facts.ts
new file mode 100644
index 0000000000..613d7eae3d
--- /dev/null
+++ b/src/core/repair/open-facts.ts
@@ -0,0 +1,566 @@
+/**
+ * `gbrain repair open-facts` (Discussion #8194): opens facts stamped private before `facts.default_visibility world`.
+ * Operator-only (the trusted local CLI on the brain host; remote callers and member mode are refused), explicit-only
+ * (never from `--all`, the doctor or the remediation plan) and preview-bound.
+ *
+ * The preview lists one window of active private facts of one source created before `--created-before` (required), in
+ * fact id order after `--after <id>` (`--limit`, default OPEN_FACTS_WINDOW), by class:
+ * fenced a row of a page's `## Facts` fence
+ * unfenced a database-only row held on a page
+ * unpaged:<lane> a row with no holding page, or from a transcript lane (conversation extraction, capture hooks,
+ * connectors); listed apart and opened only when the operator names the lane with --class
+ * and counts every private fact of the selection by the reason it is left alone (openFactsReasonSql, one SQL expression
+ * shared by the preview and the locked apply): expired, superseded, a member page, withdrawn or purged at any visibility,
+ * a trust contest (any pending proposal; a rejected or undone widening), a holding, provenance or entity page that is
+ * derivation-private (the tighten repair's own predicate, tested against every page row with the slug, deleted or not),
+ * a missing holding page, an unresolved provenance slug (fail closed), or a quarantined page. Because the exclusion is
+ * the tighten repair's predicate, `gbrain repair visibility` never plans to close what this opened.
+ *
+ * `--apply --expect <hash>` opens exactly the previewed window; a fact that became eligible inside it since refuses
+ * `preview_changed`. Every write locks the holding, provenance and entity pages FOR SHARE and rechecks each fact under
+ * its row lock, so a page flipped private meanwhile keeps its fact private. Database-only rows change in place (a managed
+ * brain: the OPEN_FACTS_INTENT maintenance request; otherwise a maintenance transaction). A fenced row is opened by the
+ * label-only door with its cell set to world (strikeFenceRow): on a managed brain the publication names the rows
+ * (`open_facts`) and its projection runs under withOpenFacts, so fence-guard moves each row to world in place with its id
+ * and tier; elsewhere the page import does not re-project the fence, so the row is opened in place in the same
+ * transaction, before a file in the source's checkout is written, and a row the locked recheck keeps private rolls the
+ * whole page write back (`revision_conflict`). Anything not opened is reported `fact_left_private` with its reason and next step, never as applied.
+ *
+ * Every write is recorded ahead in the CLI's ledger (an `intent` line, then a `committed` line naming the facts it
+ * changed). `--undo <ledger>` previews the facts the ledger opened that are still world and unchanged (skipping one
+ * since expired, superseded, edited or gone) and re-privates exactly those on --apply --expect. Undo restores the label,
+ * not what remote callers already read.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import { serializePageToMarkdown } from '../markdown.ts';
+import { strikeFenceRow } from '../facts/forget.ts';
+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
+import { trustedCliRequired } from '../ops/op-fix.ts';
+import { MEMBER_PAGE_PREFIX } from '../access/member-facts.ts';
+import { quarantineFilterFragment } from '../quarantine.ts';
+import { derivationPrivateSql } from '../search/private-visibility.ts';
+import { isSegmentedPage } from '../page-body/page-shape.ts';
+import { authorizeWrite } from '../persistence/authority.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { withOpenFacts } from '../persistence/context.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import { digest } from '../persistence/digest.ts';
+import type { WriteRequest } from '../persistence/model.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { maintenancePreflight, publishMaintenancePage, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { filesInCheckout, importAtRevision, labelFileRefusal, writeLabelFile } from './label-write.ts';
+import { factProvenanceSlugSql, PLAN_STATEMENT_MS } from './visibility.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope } from './core.ts';
+
+export const OPEN_FACTS_INTENT = 'managed_maintenance_open_fact_visibility';
+/** Facts one preview lists and one `--apply --expect` opens (`--limit` sets it, up to OPEN_FACTS_WINDOW_MAX). */
+export const OPEN_FACTS_WINDOW = 1000;
+export const OPEN_FACTS_WINDOW_MAX = 10_000;
+export const OPEN_FACTS_DEFAULT_CLASSES: readonly string[] = ['fenced', 'unfenced'];
+/** Ids one database-only write carries. */
+const GROUP_MAX = 500;
+/** The slug a database-only write of facts with no holding page is admitted under. */
+const UNPAGED_SLUG = 'memory/unattributed';
+const bounded = { timeoutMs: PLAN_STATEMENT_MS };
+
+/** One ledger line: `intent` before a write, `committed` after it with the facts it changed. */
+export interface OpenFactsLedgerLine { at: string; brain_id: string; source_id: string; hash: string; request_id: string; action: 'open' | 'close'; phase: 'intent' | 'committed';
+ facts: Array<{ id: number; row_num: number | null; slug: string | null; fact_md5: string; visibility_before?: string }> }
+/** The undo ledger the CLI keeps (src/commands/repair-open-facts.ts): its path, parsed lines (untrusted) and the append. */
+export interface OpenFactsLedger { path: string; lines: unknown[]; unreadable: number; record(line: OpenFactsLedgerLine): void }
+/** What the CLI parsed for this kind. `undo`: the ledger path whose opened facts the run re-privates. */
+export interface OpenFactsRequest { createdBefore?: string; ids?: number[]; idsFile?: string; classes: string[]; undo?: string; ledger: OpenFactsLedger }
+
+interface Selection { source_id: string; created_before: string | null; classes: string[]; ids: number[] | null; ids_file: string | null; after: number; undo: string | null }
+interface FactRef { id: number; row_num: number | null; fact: string; holder: string | null }
+/** One write: the facts of one page's fence (`fence`), or database-only facts held on one slug. */
+interface Group { mode: 'open' | 'close'; source_id: string; slug: string; fence: boolean; cls: string; facts: FactRef[]; selection: Selection; upper: number | null }
+interface OpenItem extends RepairItem { group: Group; hash: string; ledger: OpenFactsLedger; brain_id: string }
+interface PlannedRow extends FactRef { cls: string; fence: boolean }
+
+const TRANSCRIPT_LANES = (f: string) => `(${f}.source LIKE 'cli:extract-conversation-facts%' OR ${f}.source IN ('hook:writeback', 'hook:compact', 'sweep:corpus')
+ OR ${f}.source LIKE 'transcript:%' OR ${f}.source LIKE 'connector:%')`;
+
+/** A fact's class: unpaged:<lane> (no holding page, or a transcript lane), fenced, or unfenced. */
+export const openFactClassSql = (f: string) => `(CASE WHEN ${f}.source_markdown_slug IS NULL OR ${TRANSCRIPT_LANES(f)} THEN 'unpaged:' || COALESCE(NULLIF(${f}.source, ''), 'unknown')
+ WHEN ${f}.row_num IS NOT NULL THEN 'fenced' ELSE 'unfenced' END)`;
+
+/** Any page row with the slug (deleted or not) that is derivation-private. */
+const anyPrivatePage = (f: string, slug: string, alias: string) =>
+ `EXISTS (SELECT 1 FROM pages ${alias} WHERE ${alias}.source_id = ${f}.source_id AND ${alias}.slug = ${slug} AND ${derivationPrivateSql(alias)})`;
+const livePage = (f: string, slug: string, alias: string, extra = 'true') =>
+ `EXISTS (SELECT 1 FROM pages ${alias} WHERE ${alias}.source_id = ${f}.source_id AND ${alias}.slug = ${slug} AND ${alias}.deleted_at IS NULL AND ${extra})`;
+
+/**
+ * Why a private fact `f` stays private, or NULL when it may open: the one exclusion expression the preview, the reason
+ * counts and the locked apply share. A trust contest is any pending proposal on the row (a hold, a forget, a supersession)
+ * or a widening (`before_state.visibility`) the owner rejected or undid: an owner's decision is never overridden.
+ */
+export function openFactsReasonSql(f: string): string {
+ const prov = `(${factProvenanceSlugSql(f)})`;
+ const member = (expr: string) => `left(${expr}, ${MEMBER_PAGE_PREFIX.length}) = '${MEMBER_PAGE_PREFIX}'`;
+ return `(CASE
+ WHEN ${f}.expired_at IS NOT NULL THEN 'expired'
+ WHEN ${f}.superseded_by IS NOT NULL THEN 'superseded'
+ WHEN ${member(`${f}.source_markdown_slug`)} OR ${member(`${f}.entity_slug`)} OR ${member(prov)} THEN 'member_page'
+ WHEN EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id = ${f}.source_id
+ AND w.fact_hash IN (gbrain_fact_fingerprint(${f}.fact), gbrain_fact_fingerprint_v1(${f}.fact)) AND (w.subject = '*' OR w.subject = ${f}.entity_slug))
+ OR EXISTS (SELECT 1 FROM fact_purges x WHERE x.source_id = ${f}.source_id AND x.fact_hash = gbrain_fact_fingerprint(${f}.fact)
+ AND (x.subject = '*' OR x.subject = ${f}.entity_slug)) THEN 'withdrawn'
+ WHEN EXISTS (SELECT 1 FROM trust_proposals tp WHERE ((tp.target_table = 'facts' AND tp.target_id = ${f}.id) OR (tp.related_table = 'facts' AND tp.related_id = ${f}.id))
+ AND (tp.status = 'pending' OR (tp.action = 'supersede_fact' AND tp.status IN ('rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL))) THEN 'contested'
+ WHEN ${f}.source_markdown_slug IS NOT NULL AND ${anyPrivatePage(f, `${f}.source_markdown_slug`, 'oh')} THEN 'holding_page_private'
+ WHEN ${f}.source_markdown_slug IS NOT NULL AND NOT ${livePage(f, `${f}.source_markdown_slug`, 'oh')} THEN 'holding_page_missing'
+ WHEN ${f}.source_markdown_slug IS NOT NULL AND ${livePage(f, `${f}.source_markdown_slug`, 'oh', `NOT ${quarantineFilterFragment('oh')}`)} THEN 'holding_page_quarantined'
+ WHEN ${prov} IS NOT NULL AND ${anyPrivatePage(f, prov, 'op')} THEN 'provenance_private'
+ WHEN ${prov} IS NOT NULL AND NOT ${livePage(f, prov, 'op')} THEN 'provenance_unresolved'
+ WHEN ${prov} IS NOT NULL AND ${livePage(f, prov, 'op', `NOT ${quarantineFilterFragment('op')}`)} THEN 'provenance_quarantined'
+ WHEN ${f}.entity_slug IS NOT NULL AND ${anyPrivatePage(f, `${f}.entity_slug`, 'oe')} THEN 'entity_page_private'
+ ELSE NULL END)`;
+}
+
+/** The selection's private facts, before reasons: one source, created before the cut, the named ids. */
+const BASE = (f: string) => `${f}.source_id = $1 AND ${f}.visibility = 'private' AND ${f}.created_at < $2::timestamptz AND ($3::bigint[] IS NULL OR ${f}.id = ANY($3::bigint[]))`;
+
+/** One keyset window of eligible facts: ids in (after, upper], the selected classes, every exclusion in the statement. */
+async function planWindow(engine: BrainEngine, sel: Selection, limit: number, upper: number | null): Promise<PlannedRow[]> {
+ const rows = await engine.executeRaw<{ id: number; row_num: number | null; fact: string; source_markdown_slug: string | null; cls: string }>(
+ `SELECT f.id, f.row_num, f.fact, f.source_markdown_slug, ${openFactClassSql('f')} AS cls
+ FROM facts f WHERE ${BASE('f')} AND f.id > $4 AND ($5::bigint IS NULL OR f.id <= $5::bigint)
+ AND ${openFactClassSql('f')} = ANY($6::text[]) AND ${openFactsReasonSql('f')} IS NULL
+ ORDER BY f.id LIMIT $7`, [sel.source_id, sel.created_before, sel.ids, sel.after, upper, sel.classes, limit], bounded);
+ return rows.map(row => {
+ const rowNum = row.row_num === null ? null : Number(row.row_num);
+ return { id: Number(row.id), row_num: rowNum, fact: row.fact, holder: row.source_markdown_slug, cls: row.cls, fence: row.cls === 'fenced' };
+ });
+}
+
+/** Every private fact of the selection (any class, any id) counted by class and by the reason it stays private; null when it overran its bound. */
+async function countReasons(engine: BrainEngine, sel: Selection): Promise<{ eligible: Record<string, number>; excluded: Record<string, number> } | null> {
+ let rows: Array<{ cls: string; reason: string; n: number }>;
+ try {
+ rows = await engine.executeRaw(`SELECT cls, reason, count(*)::int AS n FROM (SELECT ${openFactClassSql('f')} AS cls, COALESCE(${openFactsReasonSql('f')}, 'eligible') AS reason
+ FROM facts f WHERE ${BASE('f')}) x GROUP BY cls, reason ORDER BY cls, reason`, [sel.source_id, sel.created_before, sel.ids], bounded);
+ } catch (error) {
+ if ((error as { code?: string } | null)?.code === '57014') return null;
+ throw error;
+ }
+ const eligible: Record<string, number> = {};
+ const excluded: Record<string, number> = {};
+ for (const row of rows) {
+ if (row.reason === 'eligible') eligible[row.cls] = (eligible[row.cls] ?? 0) + Number(row.n);
+ else excluded[row.reason] = (excluded[row.reason] ?? 0) + Number(row.n);
+ }
+ return { eligible, excluded };
+}
+
+/** Rows as writes: one per page fence, one per holding slug of database-only rows (at most GROUP_MAX ids each). */
+function groupRows(mode: Group['mode'], sel: Selection, rows: PlannedRow[], upper: number | null): Group[] {
+ const groups: Group[] = [];
+ const open = new Map<string, Group>();
+ for (const row of rows) {
+ const slug = row.holder ?? UNPAGED_SLUG;
+ const key = `${row.fence ? 'fence' : 'db'}\0${slug}\0${row.fence ? '' : row.cls}`;
+ let group = open.get(key);
+ if (!group || (!row.fence && group.facts.length >= GROUP_MAX)) {
+ group = { mode, source_id: sel.source_id, slug, fence: row.fence, cls: row.cls, facts: [], selection: sel, upper };
+ open.set(key, group);
+ groups.push(group);
+ }
+ group.facts.push({ id: row.id, row_num: row.row_num, fact: row.fact, holder: row.holder });
+ }
+ return groups;
+}
+
+const md5 = (text: string) => createHash('md5').update(text).digest('hex');
+const factLabel = (group: Group, fact: FactRef) => group.fence ? `fact ${fact.id} (fenced row ${fact.row_num})` : `fact ${fact.id} (${group.cls.startsWith('unpaged:') ? 'unpaged' : 'unfenced'})`;
+const hashParts = (scope: RepairScope, sel: Selection, groups: Group[], upper: number | null) => ({ kind: 'open-facts-v1', brain_id: scope.brain_id, selection: sel, upper,
+ groups: groups.map(g => [g.mode, g.slug, g.fence, g.cls, g.facts.map(f => [f.id, f.row_num, md5(f.fact)])]) });
+const selectionArgs = (sel: Selection) => sel.undo ? ['--undo', sel.undo]
+ : ['--created-before', sel.created_before!, ...(sel.classes.join() === [...OPEN_FACTS_DEFAULT_CLASSES].sort().join() ? [] : sel.classes.flatMap(c => ['--class', c])),
+ ...(sel.ids_file ? ['--ids-file', sel.ids_file] : []), ...(sel.after ? ['--after', String(sel.after)] : [])];
+/** The selection flags the printed apply command repeats (`--after` and `--limit` are the runner's). */
+export const openFactsApplyArgs = (request: OpenFactsRequest): string[] => request.undo ? ['--undo', request.undo]
+ : [...(request.createdBefore ? ['--created-before', request.createdBefore] : []), ...request.classes.flatMap(c => ['--class', c]), ...(request.idsFile ? ['--ids-file', request.idsFile] : [])];
+/** One shell word: a lane named with spaces stays one --class value in a printed command. */
+const sh = (arg: string) => /^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`;
+const previewCommand = (sel: Selection) => `gbrain repair open-facts --source ${sel.source_id} ${selectionArgs(sel).map(sh).join(' ')}`;
+
+function selectionOf(scope: RepairScope, opts?: RepairPlanOptions): { sel: Selection; request: OpenFactsRequest } {
+ if (opts?.remote !== false) throw trustedCliRequired('gbrain repair open-facts widens what remote callers read, so it runs only from the CLI on the brain host; remote callers cannot run it.');
+ const request = opts.openFacts;
+ if (!request) throw opError('invalid_params', 'gbrain repair open-facts needs its ledger and selection, and this caller passed none.',
+ 'Run gbrain repair open-facts from the CLI on the brain host, naming one source with --source and the cut with --created-before, e.g. --created-before 2026-06-01T00:00:00Z; gbrain sources list --json lists the sources.');
+ if (scope.source_ids.length !== 1) throw opError('invalid_params', 'gbrain repair open-facts opens facts in one named source.', 'Name one source with --source (gbrain sources list --json lists them).',
+ { reason: 'source_required' });
+ if (!request.undo && !request.createdBefore) throw createdBeforeRequired();
+ return { request, sel: { source_id: scope.source_ids[0]!, created_before: request.undo ? null : request.createdBefore!,
+ classes: request.undo ? [] : request.classes.length ? [...new Set(request.classes)].sort() : [...OPEN_FACTS_DEFAULT_CLASSES].sort(),
+ ids: request.ids?.length ? [...new Set(request.ids)].sort((a, b) => a - b) : null, ids_file: request.idsFile ?? null,
+ after: request.undo ? 0 : opts.afterPage ?? 0, undo: request.undo ?? null } };
+}
+
+/** `created_before_required`: the instant facts.default_visibility became world is the operator's to name. */
+export function createdBeforeRequired(): OperationError {
+ return opError('invalid_params', 'gbrain repair open-facts needs --created-before <ISO-8601>.',
+ 'Pass the instant facts.default_visibility became world on this brain, e.g. --created-before 2026-06-01T00:00:00Z; facts created after it stay as written.', { reason: 'created_before_required' });
+}
+
+/** `member_mode_refused`: a CLI under GBRAIN_ENFORCED_MEMBER acts as a member and never opens facts (the CLI checks it before the run). */
+export function memberModeRefused(): OperationError {
+ return opError('permission_denied', 'gbrain repair open-facts is refused under GBRAIN_ENFORCED_MEMBER: a member CLI cannot widen what other callers read.',
+ 'Run it as the brain host\'s operator, without GBRAIN_ENFORCED_MEMBER set.', { reason: 'member_mode_refused' });
+}
+
+interface LedgerOpened { row_num: number | null; slug: string | null; fact_md5: string; intent: { at: string; visibility_before: string | null } | null }
+
+/**
+ * The facts a ledger records as opened in this brain and source, refusing a ledger that belongs elsewhere. The latest line
+ * per fact decides: a committed open is still to undo, a committed close is undone. An open whose `intent` line is its only
+ * record (its write confirmed after the run gave up waiting, or the run died before its committed line) counts with the
+ * intent's time and the visibility the fact had then, which planUndo checks before closing it.
+ */
+function ledgerOpened(ledger: OpenFactsLedger, brainId: string, sourceId: string): Map<number, LedgerOpened> {
+ const lines = ledger.lines.map(raw => raw as Partial<OpenFactsLedgerLine> | null)
+ .filter((line): line is Partial<OpenFactsLedgerLine> => !!line && typeof line === 'object' && (line.phase === 'committed' || line.phase === 'intent') && Array.isArray(line.facts));
+ const foreignBrain = lines.find(line => line.brain_id !== brainId);
+ if (foreignBrain) {
+ throw opError('invalid_params', `The ledger ${ledger.path} records brain ${String(foreignBrain.brain_id)}, not this brain (${brainId}), so nothing was planned.`,
+ 'Run the undo on the brain that ledger belongs to (its GBRAIN_HOME and database), or pass this brain\'s own ledger, which the apply printed.', { reason: 'undo_ledger_wrong_brain' });
+ }
+ if (lines.length && !lines.some(line => line.source_id === sourceId)) {
+ const recorded = [...new Set(lines.map(line => String(line.source_id)))].sort();
+ throw opError('invalid_params', `The ledger ${ledger.path} records source ${recorded.join(', ')}, not ${sourceId}, so nothing was planned.`,
+ `Rerun the undo with the source the ledger records, e.g. --source ${recorded[0]}.`, { reason: 'undo_ledger_wrong_source' });
+ }
+ const latest = new Map<number, LedgerOpened & { action: string; committed: boolean }>();
+ for (const line of lines) {
+ if (line.source_id !== sourceId) continue;
+ for (const fact of line.facts!) {
+ if (!fact || !Number.isSafeInteger(fact.id) || typeof fact.fact_md5 !== 'string') continue;
+ const entry = { action: String(line.action), row_num: Number.isSafeInteger(fact.row_num) ? fact.row_num : null, slug: typeof fact.slug === 'string' ? fact.slug : null, fact_md5: fact.fact_md5 };
+ if (line.phase === 'committed') latest.set(fact.id, { ...entry, committed: true, intent: null });
+ else if (line.action === 'open' && !(latest.get(fact.id)?.committed && latest.get(fact.id)?.action === 'open')) {
+ latest.set(fact.id, { ...entry, committed: false, intent: { at: String(line.at), visibility_before: typeof fact.visibility_before === 'string' ? fact.visibility_before : null } });
+ }
+ }
+ }
+ return new Map([...latest].flatMap(([id, { action, committed: _c, ...entry }]) => action === 'open' ? [[id, entry] as const] : []));
+}
+
+/** --undo: the opened facts still world and unchanged, grouped as writes, and the count of each one skipped by reason. */
+async function planUndo(engine: BrainEngine, scope: RepairScope, sel: Selection, ledger: OpenFactsLedger) {
+ const opened = ledgerOpened(ledger, scope.brain_id, sel.source_id);
+ const rows = opened.size ? await engine.executeRaw<{ id: number; row_num: number | null; fact: string; visibility: string; source_markdown_slug: string | null;
+ expired: boolean; superseded: boolean; fact_md5: string; cls: string; accepted_at: string | null }>(`SELECT f.id, f.row_num, f.fact, f.visibility, f.source_markdown_slug, f.expired_at IS NOT NULL AS expired,
+ f.superseded_by IS NOT NULL AS superseded, md5(f.fact) AS fact_md5, ${openFactClassSql('f')} AS cls,
+ (SELECT max(tp.decided_at) FROM trust_proposals tp WHERE tp.status = 'accepted'
+ AND ((tp.target_table = 'facts' AND tp.target_id = f.id) OR (tp.related_table = 'facts' AND tp.related_id = f.id)))::text AS accepted_at
+ FROM facts f WHERE f.source_id = $1 AND f.id = ANY($2::bigint[]) ORDER BY f.id`, [sel.source_id, [...opened.keys()]], bounded) : [];
+ const skipped: Record<string, number> = { gone: opened.size - rows.length };
+ const keep: PlannedRow[] = [];
+ for (const row of rows) {
+ const recorded = opened.get(Number(row.id))!;
+ const rowNum = row.row_num === null ? null : Number(row.row_num);
+ const intent = recorded.intent;
+ const reason = row.expired ? 'expired' : row.superseded ? 'superseded' : row.visibility !== 'world' ? 'already_private'
+ : row.fact_md5 !== recorded.fact_md5 || rowNum !== recorded.row_num || row.source_markdown_slug !== recorded.slug ? 'changed'
+ : intent && intent.visibility_before !== 'private' ? 'world_before_run'
+ : intent && row.accepted_at !== null && Date.parse(row.accepted_at) >= Date.parse(intent.at) ? 'widened_by_proposal' : null;
+ if (reason) { skipped[reason] = (skipped[reason] ?? 0) + 1; continue; }
+ keep.push({ id: Number(row.id), row_num: rowNum, fact: row.fact, holder: row.source_markdown_slug, cls: row.cls, fence: row.cls === 'fenced' });
+ }
+ return { groups: groupRows('close', sel, keep, null), skipped: Object.fromEntries(Object.entries(skipped).filter(([, n]) => n > 0)) };
+}
+
+const listingOf = (groups: Group[]) => groups.flatMap(group => group.facts.map(fact => ({ item: `${group.source_id}:${group.slug}`, class: group.cls, detail: factLabel(group, fact) })));
+
+export const openFactsRepair: RepairHandler = {
+ kind: 'open-facts',
+ embeds: false,
+ outcomeItemsLimit: 100,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const { sel, request } = selectionOf(scope, opts);
+ const command = previewCommand(sel);
+ const toItems = (groups: Group[], hash: string): OpenItem[] => groups.map((group, index) => ({ cursor: { phase: 0, id: index }, source_id: group.source_id, slug: group.slug,
+ chars: 0, action: `${group.mode === 'open' ? 'open' : 're-private'} ${group.facts.length} ${group.cls} fact(s)`, group, hash, ledger: request.ledger, brain_id: scope.brain_id }));
+ if (opts?.apply) {
+ if (!opts.expect) throw opError('invalid_params', 'gbrain repair open-facts --apply changes only the set a preview printed (opening a fact widens remote reads).',
+ `Preview first: ${command} --json, then rerun it with --apply --expect and the preview_hash it printed.`);
+ const approved = await loadApprovedSet<Group>(engine, { command: 'open-facts', hash: opts.expect, previewCommand: command,
+ emptyHash: async () => previewHash(hashParts(scope, sel, [], null)) });
+ if (approved.items.some(group => digest(group.selection) !== digest(sel))) throw previewChangedError(opts.expect, command);
+ if (!sel.undo) {
+ // A fact that became eligible inside the approved window since the preview is a changed set.
+ const known = new Set(approved.items.flatMap(group => group.facts.map(f => f.id)));
+ const upper = approved.items[0]?.upper ?? null;
+ if ((await planWindow(engine, sel, OPEN_FACTS_WINDOW_MAX + 1, upper)).some(row => !known.has(row.id))) throw previewChangedError(opts.expect, command);
+ }
+ return { items: toItems(approved.items, opts.expect).filter(item => afterCursor(item.cursor, after)), preview_hash: opts.expect, residuals: {} };
+ }
+ if (sel.undo) {
+ const { groups, skipped } = await planUndo(engine, scope, sel, request.ledger);
+ const hash = previewHash(hashParts(scope, sel, groups, null));
+ if (groups.length) await saveApprovedSet<Group>(engine, { command: 'open-facts', hash }, groups);
+ return { items: toItems(groups, hash), preview_hash: hash, residuals: {},
+ warnings: ['Re-privating restores the label only: anything a remote caller read while these facts were world stays read.',
+ ...(request.ledger.unreadable ? [`${request.ledger.unreadable} ledger line(s) could not be read and are not planned.`] : [])],
+ listing: listingOf(groups), details: { mode: 'undo', ledger: request.ledger.path, skipped, listed: groups.reduce((n, g) => n + g.facts.length, 0) } };
+ }
+ const size = Math.min(Math.max(1, opts?.limit ?? OPEN_FACTS_WINDOW), OPEN_FACTS_WINDOW_MAX);
+ const window = await planWindow(engine, sel, size, null);
+ const upper = window.length >= size ? window[window.length - 1]!.id : null;
+ const groups = groupRows('open', sel, window, upper);
+ const hash = previewHash(hashParts(scope, sel, groups, upper));
+ if (groups.length) await saveApprovedSet<Group>(engine, { command: 'open-facts', hash }, groups);
+ const counts = await countReasons(engine, sel);
+ const samples: Record<string, string[]> = {};
+ for (const row of window) if ((samples[row.cls] ??= []).length < 3) samples[row.cls]!.push(row.fact);
+ const next = upper === null ? null : `${previewCommand({ ...sel, after: upper })}${opts?.limit ? ` --limit ${size}` : ''}`;
+ const notNamed = Object.entries(counts?.eligible ?? {}).filter(([cls]) => !sel.classes.includes(cls));
+ return { items: toItems(groups, hash), preview_hash: hash,
+ residuals: Object.fromEntries(Object.entries(counts?.excluded ?? {}).map(([reason, n]) => [`left_private_${reason}`, n])),
+ warnings: [
+ 'Opening a fact widens what remote callers that are not the brain owner can read, and that is one-way for anything they read before an undo. '
+ + `Each opened fact is recorded in ${request.ledger.path}; undo with: gbrain repair open-facts --source ${sel.source_id} --undo ${request.ledger.path}`,
+ ...(next ? [`This preview lists one window of ${window.length} fact(s); more may follow it. Apply this window (or decide not to), then preview the next one: ${next}`] : []),
+ ...(counts ? [] : [`The counts by reason did not finish within the ${PLAN_STATEMENT_MS} ms statement bound and are not listed; the window is.`]),
+ ...(notNamed.length ? [`${notNamed.map(([cls, n]) => `${n} ${cls}`).join(', ')} fact(s) are not in this preview: they come from no page the brain can judge, or from a class not named. `
+ + `Name one to preview it, e.g. --class ${sh(notNamed[0]![0])}`] : []),
+ ],
+ listing: listingOf(groups),
+ details: { mode: 'open', ledger: request.ledger.path, created_before: sel.created_before, eligible: counts?.eligible ?? null, excluded: counts?.excluded ?? null, samples,
+ window: { size, listed: window.length, after: sel.after, next_after: upper, next_preview: next } } };
+ },
+ async apply(ctx, raw): Promise<RepairItemOutcome> {
+ const item = raw as OpenItem;
+ return item.group.fence ? applyFence(ctx, item) : applyDatabase(ctx, item);
+ },
+ async report(ctx, _scope, result, opts) {
+ if (result.mode === 'apply' && opts.expect && result.complete && !result.stopped && !result.failed.length && !result.pending?.length) {
+ await clearApprovedSet(ctx.engine, { command: 'open-facts', hash: opts.expect });
+ }
+ return result.mode === 'apply' && opts.openFacts ? { details: { ...result.details, ledger: opts.openFacts.ledger.path } } : {};
+ },
+ render(details) {
+ const line = (values: unknown) => Object.entries((values ?? {}) as Record<string, number>).map(([key, value]) => `${key}=${value}`).join(', ') || 'none';
+ const samples = (details.samples ?? {}) as Record<string, string[]>;
+ return [
+ ...(details.mode === 'open' ? [` facts created before: ${String(details.created_before)} (UTC; a date alone is read as midnight UTC)`, ` eligible by class: ${line(details.eligible)}`, ` left private by reason: ${line(details.excluded)}`] : []),
+ ...(details.mode === 'undo' ? [` skipped (changed since it was opened): ${line(details.skipped)}`] : []),
+ ...Object.entries(samples).map(([cls, claims]) => ` sample ${cls}: ${claims.map(claim => JSON.stringify(claim)).join('; ')}`),
+ ...(details.ledger ? [` ledger: ${String(details.ledger)}`] : []),
+ ];
+ },
+};
+
+/** The ledger entries of a group's facts. */
+const ledgerFacts = (group: Group, ids?: ReadonlySet<number>) => group.facts.filter(f => !ids || ids.has(f.id))
+ .map(f => ({ id: f.id, row_num: f.row_num, slug: f.holder, fact_md5: md5(f.fact) }));
+/** The intent line, with each fact's visibility read just before the write (undo from an intent line closes only a fact this run opened). */
+async function recordIntent(engine: BrainEngine, item: OpenItem, requestId: string): Promise<void> {
+ const before = new Map((await engine.executeRaw<{ id: number; visibility: string }>('SELECT id, visibility FROM facts WHERE source_id = $1 AND id = ANY($2::bigint[])',
+ [item.group.source_id, item.group.facts.map(f => f.id)])).map(row => [Number(row.id), row.visibility]));
+ const facts = ledgerFacts(item.group).map(f => ({ ...f, visibility_before: before.get(f.id) ?? 'missing' }));
+ try { item.ledger.record({ at: new Date().toISOString(), brain_id: item.brain_id, source_id: item.group.source_id, hash: item.hash, request_id: requestId, action: item.group.mode, phase: 'intent', facts }); }
+ catch (error) {
+ throw opError('storage_error', `${item.group.source_id}:${item.group.slug} was not written: the undo ledger ${item.ledger.path} did not take its intent line (${error instanceof Error ? error.message : String(error)}).`,
+ `Make ${item.ledger.path} writable by this user, then rerun the same apply command; nothing was changed and the approved preview is kept.`);
+ }
+}
+
+/** The item's outcome once its write returned: the facts it changed (committed to the ledger), and any left as they were. */
+function settle(item: OpenItem, requestId: string, changed: readonly number[], why: string): RepairItemOutcome {
+ const done = new Set(changed.map(Number));
+ const left = item.group.facts.filter(f => !done.has(f.id)).map(f => f.id);
+ const opening = item.group.mode === 'open';
+ let ledgerError: string | undefined;
+ if (done.size) {
+ try { item.ledger.record({ at: new Date().toISOString(), brain_id: item.brain_id, source_id: item.group.source_id, hash: item.hash, request_id: requestId, action: item.group.mode, phase: 'committed', facts: ledgerFacts(item.group, done) }); }
+ catch (error) { ledgerError = error instanceof Error ? error.message : String(error); }
+ }
+ const next = opening ? `preview again (gbrain repair open-facts --source ${item.group.source_id} --created-before ${item.group.selection.created_before}); each fact left private is counted there by its reason`
+ : `gbrain repair visibility --source ${item.group.source_id} --class facts`;
+ if (!done.size) return { applied: false, outcome: opening ? 'fact_left_private' : 'fact_left_world', reason: `${why}; next: ${next}`, detail: { fact_ids: left.join(','), ledger: item.ledger.path } };
+ const notes = [left.length ? `${left.length} fact(s) were left as they were: ${why}` : '', ledgerError ? `the ledger did not take the commit line (${ledgerError}); its intent line is there` : ''].filter(Boolean);
+ return { applied: true, outcome: opening ? 'opened' : 'reprivated', ...(notes.length ? { reason: notes.join('; ') } : {}),
+ detail: { fact_ids: [...done].join(','), ...(left.length ? { left: left.join(',') } : {}), ledger: item.ledger.path } };
+}
+
+/** Item failures that leave the item's facts as they were, reported as its outcome instead of failing the run. */
+const ITEM_REFUSALS = new Set(['revision_conflict', 'source_changed', 'label_edit_refused', 'page_body_segmented', 'canonical_file_missing']);
+const refusal = (error: unknown) => error instanceof OperationError && (ITEM_REFUSALS.has(error.code) || ITEM_REFUSALS.has(String(error.detail ?? ''))) ? error : null;
+const CHANGED = 'it changed since the preview (a page it names turned private or went away, the fact was withdrawn, contested, edited or retired), so the locked recheck left it';
+
+type PinnedRow = { id: number; row_num: number | null; fact_md5: string };
+const pinned = (facts: readonly FactRef[]): PinnedRow[] => facts.map(f => ({ id: f.id, row_num: f.row_num, fact_md5: md5(f.fact) }));
+
+/** Locks every page the facts name (holding, provenance, entity; every row with the slug) FOR SHARE, in page id order. */
+async function lockNamedPages(tx: BrainEngine, sourceId: string, ids: readonly number[]): Promise<void> {
+ await tx.executeRaw(`SELECT p.id FROM pages p WHERE p.source_id = $1 AND p.slug IN (
+ SELECT v.s FROM facts f CROSS JOIN LATERAL (VALUES (f.source_markdown_slug), (${factProvenanceSlugSql('f')}), (f.entity_slug)) AS v(s)
+ WHERE f.source_id = $1 AND f.id = ANY($2::bigint[]) AND v.s IS NOT NULL)
+ ORDER BY p.id FOR SHARE OF p`, [sourceId, ids]);
+}
+
+/** The pinned facts still eligible to open, each locked FOR UPDATE, read after the named pages are locked. */
+async function lockEligible(tx: BrainEngine, sourceId: string, rows: readonly PinnedRow[]): Promise<number[]> {
+ await lockNamedPages(tx, sourceId, rows.map(r => r.id));
+ const locked = await tx.executeRaw<{ id: number }>(`SELECT f.id FROM facts f WHERE f.source_id = $1 AND f.id = ANY($2::bigint[]) ORDER BY f.id FOR UPDATE OF f`, [sourceId, rows.map(r => r.id)]);
+ if (!locked.length) return [];
+ const eligible = await tx.executeRaw<{ id: number }>(`SELECT f.id FROM facts f JOIN jsonb_to_recordset($2::text::jsonb) AS r(id bigint, row_num integer, fact_md5 text) ON r.id = f.id
+ WHERE f.source_id = $1 AND f.row_num IS NOT DISTINCT FROM r.row_num AND md5(f.fact) = r.fact_md5 AND f.visibility = 'private'
+ AND ${openFactsReasonSql('f')} IS NULL`, [sourceId, JSON.stringify(rows)]);
+ return eligible.map(row => Number(row.id));
+}
+
+/**
+ * Changes the pinned facts still eligible in place, in the caller's transaction: open (private to world) only those
+ * lockEligible keeps; close (world to private) those unchanged since their ledger line and still active.
+ */
+async function changeRows(tx: BrainEngine, sourceId: string, mode: Group['mode'], rows: readonly PinnedRow[]): Promise<number[]> {
+ if (!rows.length) return [];
+ if (mode === 'open') {
+ const ids = await lockEligible(tx, sourceId, rows);
+ if (!ids.length) return [];
+ return (await tx.executeRaw<{ id: number }>(`UPDATE facts SET visibility = 'world' WHERE source_id = $1 AND id = ANY($2::bigint[]) AND visibility = 'private' RETURNING id`,
+ [sourceId, ids])).map(row => Number(row.id));
+ }
+ return (await tx.executeRaw<{ id: number }>(`UPDATE facts f SET visibility = 'private' FROM jsonb_to_recordset($2::text::jsonb) AS r(id bigint, row_num integer, fact_md5 text)
+ WHERE f.source_id = $1 AND f.id = r.id AND f.row_num IS NOT DISTINCT FROM r.row_num AND md5(f.fact) = r.fact_md5 AND f.visibility = 'world'
+ AND f.expired_at IS NULL AND f.superseded_by IS NULL RETURNING f.id`, [sourceId, JSON.stringify(rows)])).map(row => Number(row.id));
+}
+
+const requestIdOf = (item: OpenItem, revision: string | null) => {
+ const h = digest(['open-facts-write-v1', item.hash, item.group.mode, item.group.source_id, item.group.slug, item.group.fence, item.group.facts.map(f => f.id), revision]);
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
+};
+
+/** Database-only facts: one in-place UPDATE under the page locks (a managed brain: the OPEN_FACTS_INTENT maintenance request). */
+async function applyDatabase(ctx: OperationContext, item: OpenItem): Promise<RepairItemOutcome> {
+ const { group } = item;
+ const rows = pinned(group.facts);
+ if (!await managedPersistenceEnabled(ctx.engine)) {
+ const requestId = requestIdOf(item, null);
+ await recordIntent(ctx.engine, item, requestId);
+ return settle(item, requestId, await maintenanceTransaction(ctx.engine, tx => changeRows(tx, group.source_id, group.mode, rows)), CHANGED);
+ }
+ const authority = (await maintenancePreflight(ctx.engine, group.source_id))!;
+ const holder = await ctx.engine.readPageSnapshot(group.slug, { sourceId: group.source_id });
+ const requestId = requestIdOf(item, holder?.revision ?? null);
+ await recordIntent(ctx.engine, item, requestId);
+ try {
+ const receipt = await submitDatabaseMaintenanceIntent(ctx.engine, authority, group.slug,
+ { kind: OPEN_FACTS_INTENT, action: group.mode, expected_revision: holder?.revision ?? null, rows }, requestId);
+ return settle(item, requestId, ((receipt.changed as number[] | undefined) ?? []).map(Number), CHANGED);
+ } catch (error) {
+ const refused = refusal(error);
+ if (!refused) throw error;
+ return settle(item, requestId, [], refused.message);
+ }
+}
+
+/**
+ * A page's fenced facts: the cells set to world (close: private) by one label-only write. A managed brain publishes it
+ * through the maintenance door naming the rows it opens (openFactsPublication); elsewhere the page is imported and the
+ * rows changed in place in the same transaction, before a file in the source's checkout is written; an open whose locked
+ * recheck keeps a row private throws `revision_conflict`, so neither the page, the file nor any row changes.
+ */
+async function applyFence(ctx: OperationContext, item: OpenItem): Promise<RepairItemOutcome> {
+ const { group } = item;
+ const from = group.mode === 'open' ? 'private' : 'world', to = group.mode === 'open' ? 'world' : 'private';
+ const snapshot = await ctx.engine.readPageSnapshot(group.slug, { sourceId: group.source_id });
+ if (!snapshot) return settle(item, '', [], 'its page is gone');
+ if (isSegmentedPage(snapshot.page)) return settle(item, '', [], 'its page is stored in segments, which this repair does not rewrite; edit the facts fence by hand on the brain host');
+ let body = snapshot.page.compiled_truth ?? '';
+ const struck: FactRef[] = [];
+ for (const fact of group.facts) {
+ let hit = false;
+ const next = strikeFenceRow(body, fact.row_num!, row => row.claim === fact.fact && row.visibility === from ? (hit = true, { ...row, visibility: to }) : row);
+ if (next === null || !hit) continue;
+ body = next;
+ struck.push(fact);
+ }
+ if (!struck.length) return settle(item, '', [], 'its rows were not found in the page\'s facts fence as previewed, or the fence does not parse cleanly');
+ const content = serializePageToMarkdown({ ...snapshot.page, compiled_truth: body }, snapshot.tags);
+ const edit = { set: {}, remove: [] };
+ const rows = pinned(struck);
+ const requestId = requestIdOf(item, snapshot.revision);
+ try {
+ if (await managedPersistenceEnabled(ctx.engine)) {
+ const authority = (await maintenancePreflight(ctx.engine, group.source_id))!;
+ const refused = await labelFileRefusal(ctx.engine, snapshot, content, edit);
+ if (refused) return settle(item, requestId, [], refused.error.message);
+ await recordIntent(ctx.engine, item, requestId);
+ await publishMaintenancePage(ctx.engine, authority, group.slug, content,
+ { expectedRevision: snapshot.revision, requestId, keepTrust: true, labelEdit: edit, ...(group.mode === 'open' ? { openFacts: rows } : {}) });
+ const settled = await ctx.engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_id = $1 AND id = ANY($2::bigint[]) AND visibility = $3 AND expired_at IS NULL`,
+ [group.source_id, rows.map(r => r.id), to]);
+ return settle(item, requestId, settled.map(r => Number(r.id)), CHANGED);
+ }
+ const path = (await filesInCheckout(ctx.engine, [Number(snapshot.page.id)])).get(Number(snapshot.page.id));
+ await recordIntent(ctx.engine, item, requestId);
+ let changed: number[] = [];
+ const inPlace = async (tx: BrainEngine) => {
+ changed = await changeRows(tx, group.source_id, group.mode, rows);
+ if (group.mode === 'open' && changed.length !== rows.length) {
+ throw opError('revision_conflict', `${group.source_id}:${group.slug} was not written: ${CHANGED}.`, 'Preview gbrain repair open-facts again; the facts are listed with their current state.');
+ }
+ };
+ if (path) {
+ const written = await writeLabelFile(ctx.engine, group, { revision: snapshot.revision, content, edit, embed: false, preview: 'gbrain repair open-facts', path, afterImport: inPlace });
+ if (written !== null && typeof written === 'object') return settle(item, requestId, [], written.reason ?? written.outcome);
+ if (written === null) return settle(item, requestId, [], 'its page changed after it was read');
+ } else if (await importAtRevision(ctx.engine, group, snapshot.revision, content, false, 'gbrain repair open-facts', inPlace) === null) {
+ return settle(item, requestId, [], 'its page changed after it was read');
+ }
+ return settle(item, requestId, changed, CHANGED);
+ } catch (error) {
+ const refused = refusal(error);
+ if (!refused) throw error;
+ return settle(item, requestId, [], refused.message);
+ }
+}
+
+const validRows = (value: unknown): value is PinnedRow[] => Array.isArray(value) && value.length > 0
+ && value.every(r => r && Number.isSafeInteger(r.id) && (r.row_num === null || Number.isSafeInteger(r.row_num)) && typeof r.fact_md5 === 'string');
+
+/** Preparer for `managed_maintenance_open_fact_visibility`: the named database-only facts change in place under the page locks. */
+export async function prepareOpenFactsIntent(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
+ const p = row.intent as { action?: unknown; rows?: unknown } | null;
+ if (!p || (p.action !== 'open' && p.action !== 'close') || !validRows(p.rows)) {
+ throw opError('invalid_params', 'The open-facts intent does not name its facts.',
+ `Request ${row.request_id} in source ${row.source_id} does not name the facts to change, so nothing changed. Preview gbrain repair open-facts again and apply it after the user approves.`);
+ }
+ const mode = p.action, rows = p.rows;
+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ return { observedRevision: snapshot?.revision ?? null, noop: true,
+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },
+ apply: async tx => ({ status: 'completed', changed: await changeRows(tx, row.source_id, mode, rows) }) };
+}
+
+/**
+ * The managed label door's publication of a page whose fence cells this repair set to world (`open_facts` on a
+ * keep_trust maintenance page intent): every named row is rechecked under the page and row locks first, the projection
+ * runs under withOpenFacts so fence-guard moves each row to world in place, and a row that changed, or that the
+ * projection did not move, rolls the whole publication back (`revision_conflict`).
+ */
+export function openFactsPublication(row: WriteRequest, prepared: PreparedMutation): PreparedMutation {
+ const rows = (row.intent as { open_facts?: unknown } | null)?.open_facts;
+ if (!validRows(rows)) throw opError('invalid_params', 'The open-facts publication does not name its facts.',
+ `Request ${row.request_id} in source ${row.source_id} does not name the fence rows it opens, so nothing changed. Preview gbrain repair open-facts again.`);
+ const ids = rows.map(r => r.id);
+ const conflict = (what: string) => opError('revision_conflict', `${row.source_id}:${row.slug} was not written: ${what}.`,
+ 'Preview gbrain repair open-facts again; the facts are listed with their current state.');
+ return { ...prepared, apply: (tx, preimage) => withOpenFacts(tx, ids, async () => {
+ if ((await lockEligible(tx, row.source_id, rows)).length !== rows.length) throw conflict('a fence row changed since the preview, or a page it names turned private');
+ const outcome = await prepared.apply(tx, preimage);
+ const [moved] = await tx.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts WHERE source_id = $1 AND id = ANY($2::bigint[]) AND visibility = 'world' AND expired_at IS NULL`,
+ [row.source_id, ids]);
+ if (Number(moved?.n ?? 0) !== rows.length) throw conflict('a fence row was not opened in place');
+ return outcome;
+ }) };
+}
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 9c2227b114..1c2e0c1788 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -97,6 +97,7 @@ import { secretSpansRepair } from './secret-spans.ts';
import { rowsBehindRepair } from './rows-behind.ts';
import { factsHomeRepair } from './facts-home.ts';
import { privateLabelsRepair, type PrivateLabelsLedger } from './private-labels.ts';
+import { openFactsApplyArgs, openFactsRepair, type OpenFactsRequest } from './open-facts.ts';
import type { ReadersRequest } from './readers.ts';
import { generationsRepair, generationsSelectionArgv, type GenerationsSelection } from '../generations/repair.ts';
import { lostFenceRowsRepair } from './lost-fence-rows.ts';
@@ -119,6 +120,11 @@ export interface RepairKindSpec {
explicit_only?: true;
/** The preview prints a hash and `--apply --expect <hash>` applies exactly that set (accepted with or without `explicit_only`). */
preview_bound?: true;
+ /**
+ * `unlisted`: an explicit-only kind whose preview needs inputs only the operator can name, so no command a surface prints
+ * would run as pasted; `--all`, the no-kind preview and the remediation plan leave it out of their explicit-only lists.
+ */
+ unlisted?: true;
/** `destructive`: the apply rewrites user files or retires stored rows, so it also needs the user's consent (`--yes` with the preview hash, or a terminal prompt). */
consent?: 'destructive';
/** The consent payload's wording for a destructive kind: what the apply does and how to undo it (default: the frontmatter file rewrite). */
@@ -723,6 +729,18 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ '(file_backed). Each change is recorded ahead of its write in ~/.gbrain/repair/private-labels/<brain>.jsonl (under $GBRAIN_HOME/.gbrain/ if set), '
+ 'and --class restore re-adds access and visibility: private from it. Runs only when named; never on upgrade.',
},
+ 'open-facts': {
+ handler: openFactsRepair, embeds: 'none', checks: [], explicit_only: true, preview_bound: true, unlisted: true,
+ summary: 'Open facts stamped private before facts.default_visibility world (#8194), which widens what remote callers that are not the brain owner can read. '
+ + 'Operator-only: runs from the CLI on the brain host, never for a remote caller or under GBRAIN_ENFORCED_MEMBER. Needs --source and --created-before <ISO-8601> '
+ + '(the instant the default became world, with its offset; a date alone is read as midnight UTC). The preview lists one window (--limit, default 1000; --after <id> for the next) of active private facts by class '
+ + '(fenced, unfenced; unpaged:<lane> for facts with no page or from a transcript lane, opened only with --class <that class>; --ids-file narrows to listed ids) '
+ + 'and counts every fact it leaves private by reason: expired, superseded, member page, withdrawn or purged, a trust contest, a private, missing or '
+ + 'quarantined holding, provenance or entity page, an unresolved provenance page. --apply --expect <hash> opens exactly that window, keeping each fact\'s '
+ + 'id, provenance and trust tier, rechecked under the page locks; a fact it could not open is reported fact_left_private. Each change is recorded ahead '
+ + 'of its write in ~/.gbrain/repair/open-facts/<brain>.jsonl (under $GBRAIN_HOME/.gbrain/ if set); --undo <ledger> previews re-privating what it opened '
+ + '(the label only: what was read stays read). Runs only when named; never on upgrade.',
+ },
'generations': {
handler: generationsRepair, embeds: 'effect', checks: ['generation_retirements', 'generation_held', 'generation_pending'], explicit_only: true, preview_bound: true, consent: 'destructive',
consentText: {
@@ -796,7 +814,7 @@ export function repairPreviewCommand(kind: RepairKind, opts: { source?: string }
export interface ExplicitRepairNotice { kind: RepairKind; code: 'explicit_kind_required'; preview_command: string; docs: string }
export function explicitRepairNotices(opts: { source?: string } = {}): ExplicitRepairNotice[] {
- return EXPLICIT_REPAIR_REGISTRY.map(spec => ({ kind: spec.kind, code: 'explicit_kind_required' as const,
+ return EXPLICIT_REPAIR_REGISTRY.filter(spec => !spec.unlisted).map(spec => ({ kind: spec.kind, code: 'explicit_kind_required' as const,
preview_command: repairPreviewCommand(spec.kind, opts), docs: ERROR_CATALOGUE.explicit_kind_required.docs }));
}
@@ -841,7 +859,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number; stop?: AbortSignal; recordDatabaseStops?: boolean;
prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string; provenance?: string; cursor?: string; progress?: ProgressReporter;
keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number; generations?: GenerationsSelection; day?: string; rules?: string[];
- cwdPrefixes?: string[]; sessions?: string[]; principal?: string; privateLabelsLedger?: PrivateLabelsLedger; readers?: ReadersRequest } = {}): Promise<RepairResult> {
+ cwdPrefixes?: string[]; sessions?: string[]; principal?: string; privateLabelsLedger?: PrivateLabelsLedger; readers?: ReadersRequest; openFacts?: OpenFactsRequest } = {}): Promise<RepairResult> {
const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;
const spec = repairSpec(kind, opts.registry);
return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag, spec,
@@ -850,11 +868,12 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
...(run.afterPage !== undefined ? ['--after', String(run.afterPage)] : []), ...(run.generations ? generationsSelectionArgv(run.generations) : []), ...(run.day ? ['--day', run.day] : []), ...(run.rules?.length ? ['--rules', run.rules.join(',')] : []),
...(kind === 'agent-session-facts' ? agentSessionFlagArgs(run).map(arg => shellQuote(arg)) : []),
...(run.readers ? [...(run.readers.slugsFile ? ['--slugs-file', run.readers.slugsFile.path] : []), '--readers', run.readers.readers,
- ...(run.readers.allowWithoutOwner ? ['--allow-without-owner'] : [])].map(arg => shellQuote(arg)) : [])],
+ ...(run.readers.allowWithoutOwner ? ['--allow-without-owner'] : [])].map(arg => shellQuote(arg)) : []),
+ ...(run.openFacts ? openFactsApplyArgs(run.openFacts).map(arg => shellQuote(arg)) : [])],
explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, includeCrossEntity: run.includeCrossEntity, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,
maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, ...(run.stop ? { stop: run.stop } : {}), ...(run.recordDatabaseStops ? { recordDatabaseStops: true } : {}), prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass, since: run.since,
held: run.held, side: run.side, state: run.state, provenance: run.provenance, cursor: run.cursor, progress: run.progress, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage, generations: run.generations, day: run.day, rules: run.rules,
- cwdPrefixes: run.cwdPrefixes, sessions: run.sessions, principal: run.principal, privateLabelsLedger: run.privateLabelsLedger, readers: run.readers });
+ cwdPrefixes: run.cwdPrefixes, sessions: run.sessions, principal: run.principal, privateLabelsLedger: run.privateLabelsLedger, readers: run.readers, openFacts: run.openFacts });
},
};
}
diff --git a/src/core/repair/visibility.ts b/src/core/repair/visibility.ts
index 28d86405a2..f615a269af 100644
--- a/src/core/repair/visibility.ts
+++ b/src/core/repair/visibility.ts
@@ -214,7 +214,7 @@ export async function planVisibilityRepair(engine: BrainEngine, sourceIds: strin
* session (`put_page:<slug>`, `sync:<slug>`), else the slug a page-write or
* extract_facts lane records first in `context`.
*/
-function factProvenanceSlugSql(f: string): string {
+export function factProvenanceSlugSql(f: string): string {
return `regexp_replace(COALESCE(
CASE WHEN ${f}.source_session ~ '^(put_page|sync):' THEN regexp_replace(${f}.source_session, '^(put_page|sync):', '') END,
CASE WHEN ${f}.source IN ('mcp:put_page','sync:import','file_upload','code_import','hook:writeback','mcp:extract_facts')
diff --git a/src/core/trust/fence-guard.ts b/src/core/trust/fence-guard.ts
index 5b2304a02d..d0843cfac0 100644
--- a/src/core/trust/fence-guard.ts
+++ b/src/core/trust/fence-guard.ts
@@ -18,6 +18,11 @@
* row's visibility and its proposal carries the widening, which only the
* owner's accept applies (GST-2511); until then later writes of the same
* fence keep that contested row narrower.
+ * - Operator open (#8194): only inside `gbrain repair open-facts`
+ * (persistence/context.ts withOpenFacts), a named private row whose cell is
+ * now world at the same row number and claim is guarded at any tier and
+ * moves back in place as world, keeping its id and tier. Every other
+ * widening keeps the rules above.
* - Row gate (ENG-1): every new fence row is gated like other fact writers at
* the writer's tier; a held row is not inserted (the hold keeps it), a
* flagged row records its receipt after insert.
@@ -28,7 +33,7 @@
* (trust/held-removals.ts).
*/
import type { BrainEngine, NewFact } from '../engine.ts';
-import { currentWriteTrust } from '../persistence/context.ts';
+import { currentWriteTrust, openedFactRowSql } from '../persistence/context.ts';
import type { WriteGateConfig } from '../write-gate.ts';
import { decideFactWrite, recordFlaggedRow, recordWriteGateHold, type GatedRowDecision } from '../write-gate-store.ts';
import { gateInput } from './gate-outcomes.ts';
@@ -62,14 +67,17 @@ export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input
AND ${trustRankSql("tp.before_state->'old'->>'tier'")} > ${WRITER_RANK})
AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS w(row_num integer, fact text, visibility text)
WHERE w.row_num = f.row_num AND w.fact = f.fact AND w.visibility = 'world')`;
- const guarded = (await tx.executeRaw<{ id: number; row_num: number; fact: string; visibility: string; trust_tier: string; above: boolean }>(
- `SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, ${trustRankSql('f.trust_tier')} > ${WRITER_RANK} AS above FROM facts f
+ // #8194: a row `gbrain repair open-facts` opens (withOpenFacts: only private to world, same row number and claim) is guarded at
+ // any tier, so it is detached before the expiry and moves back in place as world, keeping its id and tier.
+ const opened = openedFactRowSql('f', '$3');
+ const guarded = (await tx.executeRaw<{ id: number; row_num: number; fact: string; visibility: string; trust_tier: string; above: boolean; opened: boolean }>(
+ `SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, ${trustRankSql('f.trust_tier')} > ${WRITER_RANK} AS above, ${opened} AS opened FROM facts f
WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL
AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%'
OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num))
AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text)
WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility)
- AND (${trustRankSql('f.trust_tier')} > ${WRITER_RANK} OR (${held}))
+ AND (${trustRankSql('f.trust_tier')} > ${WRITER_RANK} OR (${held}) OR ${opened})
ORDER BY f.row_num FOR UPDATE`, [sourceId, slug, incoming])).filter(row => !input.kept?.includes(Number(row.id)));
if (guarded.length) await tx.executeRaw('UPDATE facts SET row_num = NULL WHERE id = ANY($1::bigint[])', [guarded.map(g => Number(g.id))]);
await expire();
@@ -83,6 +91,13 @@ export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input
const moves: Array<{ id: number; row_num: number; visibility: string }> = [];
for (const g of guarded) {
const free = rows.filter(r => r.fact === g.fact && !occupied.has(r.row_num));
+ const reopened = g.opened ? free.find(r => r.row_num === Number(g.row_num) && r.visibility === 'world') : undefined;
+ if (reopened) {
+ moves.push({ id: Number(g.id), row_num: reopened.row_num, visibility: 'world' });
+ occupied.add(reopened.row_num);
+ rows = rows.filter(r => r !== reopened);
+ continue;
+ }
if (!g.above) {
const target = free.find(r => r.row_num === Number(g.row_num));
if (!target) continue;
diff --git a/test/fixtures/fold-hook-noop-6712.json b/test/fixtures/fold-hook-noop-6712.json
index 164355cab4..3b76f86508 100644
--- a/test/fixtures/fold-hook-noop-6712.json
+++ b/test/fixtures/fold-hook-noop-6712.json
@@ -33,8 +33,8 @@
"UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS NULL RETURNING id",
"UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND source_path=$3 AND database_only_reason='origin_twin'",
"UPDATE pages SET source_kind=$3,ingested_via=$4,ingested_at=$5::timestamptz WHERE source_id=$1 AND slug=$2",
- "SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) ORDER BY f.row_num, f.id",
- "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) AS above FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND ((CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) OR (f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.action = 'supersede_fact' AND tp.related_table = 'facts' AND tp.related_id = f.id AND tp.status IN ('pending', 'rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL AND (CASE tp.before_state->'old'->>'tier' WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END)) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS w(row_num integer, fact text, visibility text) WHERE w.row_num = f.row_num AND w.fact = f.fact AND w.visibility = 'world'))) ORDER BY f.row_num FOR UPDATE",
+ "SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) AND NOT (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) ORDER BY f.row_num, f.id",
+ "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) AS above, (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) AS opened FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND ((CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) OR (f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.action = 'supersede_fact' AND tp.related_table = 'facts' AND tp.related_id = f.id AND tp.status IN ('pending', 'rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL AND (CASE tp.before_state->'old'->>'tier' WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END)) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS w(row_num integer, fact text, visibility text) WHERE w.row_num = f.row_num AND w.fact = f.fact AND w.visibility = 'world')) OR (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world'))) ORDER BY f.row_num FOR UPDATE",
"DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
"UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
"SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
@@ -99,8 +99,8 @@
"INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since, projected_byte_start, projected_byte_end) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector, CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END, c.projected_byte_start, c.projected_byte_end FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text, projected_byte_start bigint, projected_byte_end bigint) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, projected_byte_start = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.projected_byte_start ELSE COALESCE(EXCLUDED.projected_byte_start, content_chunks.projected_byte_start) END, projected_byte_end = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.projected_byte_end ELSE COALESCE(EXCLUDED.projected_byte_end, content_chunks.projected_byte_end) END, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image), embedding_pending_since = CASE WHEN EXCLUDED.\"embedding\" IS NOT NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL THEN COALESCE(content_chunks.embedding_pending_since, now()) WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN now() ELSE content_chunks.embedding_pending_since END",
"UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND database_only_reason='unbound_source'",
"WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges) wd",
- "SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) ORDER BY f.row_num, f.id",
- "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) AS above FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND ((CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) OR (f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.action = 'supersede_fact' AND tp.related_table = 'facts' AND tp.related_id = f.id AND tp.status IN ('pending', 'rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL AND (CASE tp.before_state->'old'->>'tier' WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END)) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS w(row_num integer, fact text, visibility text) WHERE w.row_num = f.row_num AND w.fact = f.fact AND w.visibility = 'world'))) ORDER BY f.row_num FOR UPDATE",
+ "SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) AND NOT (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) ORDER BY f.row_num, f.id",
+ "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) AS above, (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) AS opened FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND ((CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) OR (f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.action = 'supersede_fact' AND tp.related_table = 'facts' AND tp.related_id = f.id AND tp.status IN ('pending', 'rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL AND (CASE tp.before_state->'old'->>'tier' WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END)) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS w(row_num integer, fact text, visibility text) WHERE w.row_num = f.row_num AND w.fact = f.fact AND w.visibility = 'world')) OR (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world'))) ORDER BY f.row_num FOR UPDATE",
"DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
"UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
"SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
@@ -159,9 +159,9 @@
"INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since, projected_byte_start, projected_byte_end) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector, CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END, c.projected_byte_start, c.projected_byte_end FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text, projected_byte_start bigint, projected_byte_end bigint) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\"",
"SELECT id, slug, source_path, deleted_at FROM pages WHERE source_id=$1 AND slug=$2",
"UPDATE pages SET source_kind=$3,ingested_via=$4,ingested_at=$5::timestamptz WHERE source_id=$1 AND slug=$2",
- "SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) ORDER BY f.row_num, f.id",
+ "SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) AND NOT (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) ORDER BY f.row_num, f.id",
"SELECT local_path, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1",
- "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) AS above FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND ((CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) OR (f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.action = 'supersede_fact' AND tp.related_table = 'facts' AND tp.related_id = f.id AND tp.status IN ('pending', 'rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL AND (CASE tp.before_state->'old'->>'tier' WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' TH",
+ "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) AS above, (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) AS opened FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND ((CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) OR (f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.a",
"SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
"DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
"UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
@@ -234,8 +234,8 @@
"UPDATE pages SET chunker_version=$5, text_projection_revision=CASE WHEN knowledge_revision=$4::uuid THEN knowledge_revision ELSE text_projection_revision END, search_vector=CASE WHEN knowledge_revision=$4::uuid THEN setweight(to_tsvector('english',gbrain_fts_input(COALESCE(title,''))),'A') || setweight(to_tsvector('english',gbrain_fts_input(left($3::text,65536))),'C') ELSE search_vector END WHERE source_id=$1 AND slug=$2 RETURNING id",
"SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count FROM op_checkpoints WHERE op=$1 AND fingerprint=$2",
"INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()",
- "SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) ORDER BY f.row_num, f.id",
- "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) AS above FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND ((CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) OR (f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.action = 'supersede_fact' AND tp.related_table = 'facts' AND tp.related_id = f.id AND tp.status IN ('pending', 'rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL AND (CASE tp.before_state->'old'->>'tier' WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' TH",
+ "SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) AND NOT (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) ORDER BY f.row_num, f.id",
+ "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) AS above, (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) AS opened FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND ((CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) OR (f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.a",
"DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
"UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
"SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
diff --git a/test/fold-hook-noop-6712.test.ts b/test/fold-hook-noop-6712.test.ts
index b427968124..8a509921ed 100644
--- a/test/fold-hook-noop-6712.test.ts
+++ b/test/fold-hook-noop-6712.test.ts
@@ -19,7 +19,8 @@
* PGLite here; Postgres through test/e2e/fold-hook-noop-6712-postgres.test.ts.
* Pinned additions since that commit (neither is hook work): GBRA-217 names `change_reason` in the canonical import's
* page_versions insert (null when the commit carries no reason trailer) and adds the valid-time advisory's read of the
- * written page after put_page's apply (persistence/valid-time-advisory.ts).
+ * written page after put_page's apply (persistence/valid-time-advisory.ts). #8194 adds the open-facts clause
+ * (`gbrain.write_open_facts`, trust/fence-guard.ts) to the fence guard's two fact reads; same statements, same order.
* CAPTURE_FOLD_NOOP=1 rewrites the fixture for the engine under test (only ever from the pre-hook commit).
*/
import { describe, expect, test } from 'bun:test';
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 5de6205db0..625802d756 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -612,6 +612,7 @@ test/repair-frontmatter-keys-sweep-6454.test.ts
test/repair-frontmatter.test.ts
test/repair-ghost-database-ahead-gbra133.test.ts
test/repair-lost-fence-rows.test.ts
+test/repair-open-facts-8194.test.ts
test/repair-private-labels-batch.test.ts
test/repair-purged-page-facts-8859.test.ts
test/repair-quoted-markers-8059.test.ts
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index 1e761de029..7a220630b1 100644
--- a/test/repair-explicit-only.test.ts
+++ b/test/repair-explicit-only.test.ts
@@ -24,8 +24,10 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { withEnv } from './helpers/with-env.ts';
-const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'purged-page-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'moved-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'lost-fence-rows', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'facts-home', 'private-labels'];
+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'purged-page-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'moved-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'lost-fence-rows', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'facts-home', 'private-labels', 'open-facts'];
// GBRA-161: the generations preview carries its ledger kind and the restore window, so the printed command runs as is.
+// open-facts (#8194) needs --source and --created-before, which only the operator can name, so no surface lists it.
+const LISTED = EXPLICIT.filter(kind => kind !== 'open-facts');
const PREVIEW = (kind: RepairKind): string => kind === 'generations' ? 'gbrain repair generations --kind atom --since 30d' : `gbrain repair ${kind}`;
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));
@@ -108,7 +110,7 @@ describe('surfaces that list instead of run', () => {
for (const args of [['--all', '--json'], ['--json']]) {
const out = JSON.parse(await captured(args)) as { results: Array<{ kind: string }>; explicit_kinds: Array<{ kind: string; code: string; preview_command: string }> };
expect(out.results.map(r => r.kind)).toEqual(AUTO_REPAIR_REGISTRY.map(spec => spec.kind));
- expect(out.explicit_kinds).toEqual(EXPLICIT.map(kind => ({ kind, code: 'explicit_kind_required', preview_command: PREVIEW(kind),
+ expect(out.explicit_kinds).toEqual(LISTED.map(kind => ({ kind, code: 'explicit_kind_required', preview_command: PREVIEW(kind),
docs: 'docs/guides/repair.md#explicit-only-repair-kinds' })));
}
expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair accepted-takes; gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair atoms-restore; gbrain repair atom-fence-rows; gbrain repair extractor-facts; gbrain repair unwithdrawn-facts; gbrain repair purged-page-facts; gbrain repair conversation-labels; gbrain repair captured-facts; gbrain repair agent-session-facts; gbrain repair redacted-facts; gbrain repair loop-facts');
@@ -148,7 +150,7 @@ describe('surfaces that list instead of run', () => {
expect((await planRepairSteps(engine)).some(step => EXPLICIT.includes(step.kind))).toBe(false);
const plan = await withEnv({ GBRAIN_HOME: home }, () => computeRemediationPlan(engine, { repairs: {} }));
expect(plan.repair_steps!.some(step => EXPLICIT.includes(step.kind))).toBe(false);
- expect(plan.explicit_repairs!.map(n => [n.kind, n.code, n.preview_command])).toEqual(EXPLICIT.map(kind => [kind, 'explicit_kind_required', PREVIEW(kind)]));
+ expect(plan.explicit_repairs!.map(n => [n.kind, n.code, n.preview_command])).toEqual(LISTED.map(kind => [kind, 'explicit_kind_required', PREVIEW(kind)]));
const text = renderRemediationPlanLines(plan, 90).join('\n');
expect(text).toContain('Explicit-only repairs');
expect(text).toContain(' stale-atoms: gbrain repair stale-atoms');
diff --git a/test/repair-open-facts-8194.test.ts b/test/repair-open-facts-8194.test.ts
new file mode 100644
index 0000000000..170f48aec0
--- /dev/null
+++ b/test/repair-open-facts-8194.test.ts
@@ -0,0 +1,709 @@
+/**
+ * Discussion #8194 (GBRA-575): `gbrain repair open-facts`, the operator-only repair that opens facts stamped private
+ * before `facts.default_visibility world`.
+ *
+ * 1. Protects: an operator on the brain host can open legacy private facts in one named source, preview first, then
+ * `--apply --expect <hash>`, keeping each fact's id, provenance, creation time and trust tier; a remote source-granted
+ * caller recalls them afterwards and not before; facts on private, reader-restricted, folder-ruled, quarantined or member
+ * pages, from a private or unresolved provenance page, expired, superseded, withdrawn or purged at any visibility, in a
+ * trust contest (pending, rejected or undone widening, pending forget), and transcript-lane rows stay private; the
+ * tighten repair plans nothing for what was opened; `--undo` re-privates exactly what the ledger recorded. Managed and
+ * unmanaged, repo-less.
+ * 2. Fails when: the preview writes anything, the apply opens a fact outside the previewed set, a fact changes id or tier,
+ * an excluded fact opens, `gbrain repair visibility` would close an opened fact, the kind runs from `--all` or a remote
+ * caller, a remote put_page or remember widening over a private row is no longer held (#9196, GST-2511), or a page
+ * flipped private during the apply leaves its fact world.
+ * 3. Real seams: the gbrain repair CLI module (parse and dispatch), MCP operation handlers and dispatch with remote=true and
+ * a source-granted token, PGLite (Postgres too when DATABASE_URL is set, with a second session for the race).
+ * Red before the build: the kind does not exist yet. The pins (remote rewrite, #9196 holds) are green today.
+ */
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { createHash, randomUUID } from 'node:crypto';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import postgres from '#postgres';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import type { Principal } from '../src/core/persistence/model.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { registerLocalWriter, readLocalWriter } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withCoordinatedWrite, withTrustPromotion } from '../src/core/persistence/context.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { REPAIR_KINDS, resolveRepairScope, runRepair } from '../src/core/repair/core.ts';
+import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairSpec } from '../src/core/repair/registry.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { parseFactsFence, renderFactsTable } from '../src/core/facts-fence.ts';
+import { insertTrustProposal, listTrustProposals } from '../src/core/trust/proposals.ts';
+import { proposeRevision } from '../src/core/access/policy.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+
+const engines: BrainEngine[] = [];
+const urls = new Map<BrainEngine, string>();
+const home = mkdtempSync(join(tmpdir(), 'gbrain-open-facts-'));
+let closePostgres: (() => Promise<void>) | undefined;
+const quiet = { info() {}, warn() {}, error() {} };
+/** Every fact the fixtures write is older than this instant (--created-before is required). */
+const CUT = '2999-01-01T00:00:00.000Z';
+
+beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); urls.set(pg.engine, pg.databaseUrl); closePostgres = pg.close;
+ }
+}), 120_000);
+afterAll(async () => {
+ resetGateway();
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+interface Brain { engine: BrainEngine; sourceId: string; remote: OperationContext; local: OperationContext }
+/** A source on a shared-shaped brain (no owner, no members) with a token granted only that source. */
+async function brain(engine: BrainEngine, managed: boolean): Promise<Brain> {
+ const sourceId = `open-${randomUUID().slice(0, 8)}`;
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await engine.setConfig('brain.audience', 'shared');
+ await registerLocalWriter(engine, 'cli');
+ const minted = await mintLegacyToken(engine, { name: `token-${sourceId}`, scopes: ['read', 'write'], sourceGrant: [sourceId], takesHolders: ['world'] });
+ await readsUnscopedOnPurpose(engine, minted.id);
+ if (managed) await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const base = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId, dryRun: false, logger: quiet };
+ await readLocalWriter(engine, 'cli');
+ return {
+ engine, sourceId,
+ remote: { ...base, remote: true, transport: 'http', takesHoldersAllowList: ['world'],
+ auth: { token: '', clientId: minted.id, principal: { kind: 'legacy_token', id: minted.id } as Principal, sourceId, allowedSources: [sourceId], scopes: ['read', 'write'] } },
+ local: { ...base, remote: false },
+ } as Brain;
+}
+const run = (ctx: OperationContext, op: string, params: Record<string, unknown>) =>
+ operationsByName[op].handler(ctx, { request_id: randomUUID(), ...params }) as Promise<Record<string, any>>;
+
+type Row = [number, string, 'private' | 'world'];
+const fence = (rows: Row[]) => ['## Facts', '', '<!--- gbrain:facts:begin -->',
+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',
+ ...rows.map(([n, claim, vis]) => `| ${n} | ${claim} | fact | 1.0 | ${vis} | medium | 2026-09-01 | | fixture | |`),
+ '<!--- gbrain:facts:end -->'].join('\n');
+const pageText = (slug: string, front: string, rows: Row[]) =>
+ `---\ntype: company\ntitle: ${slug}\n${front}---\n\n# ${slug}\n\nOrchardline body.\n\n${fence(rows)}\n`;
+const page = (b: Brain, slug: string, front: string, rows: Row[]) =>
+ run(b.local, 'put_page', { slug, content: pageText(slug, front, rows) });
+
+/** A database-only private fact (no fence row), as older extraction lanes stored them. */
+async function dbOnly(b: Brain, fact: string, holder: string | null, opts: { expired?: boolean; source?: string; context?: string; supersededBy?: number; entity?: string | null } = {}): Promise<number> {
+ const rows = await b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], () => tx.executeRaw<{ id: number }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_markdown_slug, context, superseded_by, expired_at)
+ VALUES ($1, $2, $3, 'fact', 'private', $4, $5, $6, $7, ${opts.expired ? 'now()' : 'NULL'}) RETURNING id`, // gbrain-allow-direct-insert: legacy database-only fact fixture
+ [b.sourceId, opts.entity === undefined ? holder : opts.entity, fact, opts.source ?? 'mcp:extract_facts', holder, opts.context ?? null, opts.supersededBy ?? null]), TEST_WRITE_ATTRIBUTION));
+ return Number(rows[0].id);
+}
+const coordinated = (b: Brain, sql: string, params: unknown[]) =>
+ b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));
+const facts = async (b: Brain, claim: string) => b.engine.executeRaw<{ id: number; visibility: string; row_num: number | null; created_at: string; source: string; trust_tier: string; context: string | null }>(
+ 'SELECT id::int AS id, visibility, row_num, created_at::text AS created_at, source, trust_tier, context FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL ORDER BY id', [b.sourceId, claim]);
+const visibilityOf = async (b: Brain, id: number) => (await b.engine.executeRaw<{ visibility: string }>('SELECT visibility FROM facts WHERE id=$1', [id]))[0]?.visibility;
+async function remoteRecall(b: Brain, entity: string): Promise<string> {
+ __resetPrivateVisibilityCacheForTests();
+ return JSON.stringify(await run(b.remote, 'recall', { entity }));
+}
+async function cli(engine: BrainEngine, args: string[]): Promise<string> {
+ const lines: string[] = [];
+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });
+ try { await runRepairCommand(engine, args); } finally { log.mockRestore(); }
+ return lines.join('\n');
+}
+const expectHash = (out: string) => out.match(/--expect ([0-9a-f]{16,})/)?.[1];
+/** The open-facts result of a --json run. */
+async function openFacts(b: Brain, args: string[]): Promise<Record<string, any>> {
+ return JSON.parse(await cli(b.engine, ['open-facts', '--source', b.sourceId, ...args, '--json'])).results[0];
+}
+const preview = (b: Brain, extra: string[] = []) => openFacts(b, ['--created-before', CUT, ...extra]);
+async function previewAndApply(b: Brain, extra: string[] = []) {
+ const planned = await preview(b, extra);
+ const applied = planned.preview_hash ? await openFacts(b, ['--created-before', CUT, ...extra, '--apply', '--expect', planned.preview_hash]) : null;
+ return { planned, applied };
+}
+async function confirmFact(b: Brain, id: number) {
+ await b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], () => withTrustPromotion(tx, 'user_confirmed', () =>
+ tx.executeRaw(`UPDATE facts SET trust_tier='user_confirmed' WHERE id=$1`, [id])), TEST_WRITE_ATTRIBUTION));
+}
+const fenceCell = async (b: Brain, slug: string, rowNum: number) => {
+ const [stored] = await b.engine.executeRaw<{ body: string }>('SELECT compiled_truth AS body FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [b.sourceId, slug]);
+ return parseFactsFence(stored!.body).facts.find(f => f.rowNum === rowNum);
+};
+
+describe('repair open-facts: registration and who may run it (test 7)', () => {
+ test('the kind exists, runs only when named and never from --all or the remediation plan', () => {
+ expect(REPAIR_KINDS as readonly string[]).toContain('open-facts');
+ expect(EXPLICIT_REPAIR_REGISTRY.map(s => s.kind)).toContain('open-facts');
+ expect(AUTO_REPAIR_REGISTRY.map(s => s.kind)).not.toContain('open-facts');
+ const spec = REPAIR_REGISTRY.find(s => s.kind === 'open-facts')!;
+ expect(spec).toMatchObject({ explicit_only: true, preview_bound: true, embeds: 'none', checks: [] });
+ expect(explicitRepairNotices().find(n => n.kind === 'open-facts')).toBeUndefined();
+ expect(explicitRepairNotices({ source: 'default' }).find(n => n.kind === 'open-facts')).toBeUndefined();
+ });
+
+ test('a remote caller, an unnamed run and member mode are refused; --created-before is required with a coded error', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0]!;
+ const b = await brain(engine, false);
+ const scope = await resolveRepairScope(engine, b.sourceId);
+ const spec = repairSpec('open-facts' as never);
+ await expect(runRepair(b.remote, spec.handler, scope, { apply: false, explicit: true, spec })).rejects.toMatchObject({ code: 'permission_denied' });
+ await expect(runRepair(b.local, spec.handler, scope, { apply: false, spec })).rejects.toMatchObject({ code: 'explicit_kind_required' });
+ await expect(withEnv({ GBRAIN_ENFORCED_MEMBER: 'alice-example' }, () => cli(engine, ['open-facts', '--source', b.sourceId, '--created-before', CUT])))
+ .rejects.toMatchObject({ code: 'permission_denied', reason: 'member_mode_refused' });
+ await expect(cli(engine, ['open-facts', '--source', b.sourceId])).rejects.toMatchObject({ code: 'invalid_params', reason: 'created_before_required' });
+ await expect(cli(engine, ['open-facts', '--source', b.sourceId, '--created-before', 'yesterday'])).rejects.toMatchObject({ code: 'invalid_params', reason: 'created_before_invalid' });
+ await expect(cli(engine, ['open-facts', '--source', b.sourceId, '--created-before', CUT, '--class', 'everything'])).rejects.toMatchObject({ code: 'invalid_params', reason: 'class_invalid' });
+ await expect(cli(engine, ['open-facts', '--source', b.sourceId, '--created-before', CUT, '--ids-file', join(home, 'missing-ids.txt')])).rejects.toMatchObject({ code: 'invalid_params', reason: 'ids_file_unreadable' });
+ await expect(cli(engine, ['open-facts', '--created-before', CUT])).rejects.toMatchObject({ code: 'invalid_params', reason: 'source_required' });
+ }), 120_000);
+});
+
+for (const managed of [false, true]) {
+ describe(`repair open-facts on a shared brain with no owner (${managed ? 'managed' : 'unmanaged'}, repo-less)`, () => {
+ test('tests 1-3, 6, 9: opens exactly the previewed legacy private facts, keeps ids, and leaves every excluded fact private', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine, managed);
+ await page(b, 'companies/acme-example', '', [[1, 'Acme Example orchardline revenue grew', 'private'], [2, 'Acme Example is in Springfield', 'world']]);
+ await page(b, 'secret/plan-example', 'visibility: private\n', [[1, 'Orchardline merger plan', 'private']]);
+ await page(b, 'people/alice-example', 'readable_by: [alice-example]\n', [[1, 'Alice Example orchardline salary', 'private']]);
+ const loose = await dbOnly(b, 'Acme Example orchardline database-only legacy fact', 'companies/acme-example', { context: 'companies/acme-example extracted' });
+ await dbOnly(b, 'Orchardline fact held on a private page', 'secret/plan-example');
+ const expired = await dbOnly(b, 'Orchardline expired fact', 'companies/acme-example', { expired: true });
+
+ const [fencedBefore] = await facts(b, 'Acme Example orchardline revenue grew');
+ const [looseBefore] = await facts(b, 'Acme Example orchardline database-only legacy fact');
+ expect(fencedBefore.visibility).toBe('private');
+ expect(looseBefore.visibility).toBe('private');
+ expect(await remoteRecall(b, 'companies/acme-example')).not.toContain('orchardline revenue grew');
+
+ const planned = await preview(b);
+ const hash = planned.preview_hash as string;
+ expect(hash).toMatch(/^[0-9a-f]{16,}$/);
+ expect(planned.apply_command).toContain(`--created-before ${CUT}`);
+ expect(planned.details.eligible).toMatchObject({ fenced: 1, unfenced: 1 });
+ expect(planned.details.excluded).toMatchObject({ holding_page_private: 3, expired: 1 });
+ expect(planned.details.samples.fenced).toEqual(['Acme Example orchardline revenue grew']);
+ expect(planned.listing.map((l: { detail: string }) => l.detail).sort()).toEqual([`fact ${fencedBefore.id} (fenced row 1)`, `fact ${loose} (unfenced)`].sort());
+ // The preview wrote nothing.
+ expect((await facts(b, 'Acme Example orchardline revenue grew'))[0].visibility).toBe('private');
+ expect(await visibilityOf(b, loose)).toBe('private');
+
+ const applied = await openFacts(b, ['--created-before', CUT, '--apply', '--expect', hash]);
+ expect(applied.applied).toBe(2);
+ expect(applied.outcomes?.fact_left_private).toBeUndefined();
+
+ expect((await facts(b, 'Acme Example orchardline revenue grew')).map(f => [f.id, f.visibility, f.row_num, f.trust_tier]))
+ .toEqual([[fencedBefore.id, 'world', 1, fencedBefore.trust_tier]]);
+ expect((await fenceCell(b, 'companies/acme-example', 1))).toMatchObject({ claim: 'Acme Example orchardline revenue grew', visibility: 'world' });
+ expect((await facts(b, 'Acme Example orchardline database-only legacy fact')).map(f => [f.id, f.visibility, f.created_at, f.source, f.context, f.trust_tier]))
+ .toEqual([[loose, 'world', looseBefore.created_at, looseBefore.source, looseBefore.context, looseBefore.trust_tier]]);
+ for (const claim of ['Orchardline merger plan', 'Alice Example orchardline salary', 'Orchardline fact held on a private page']) {
+ expect((await facts(b, claim)).map(f => f.visibility)).toEqual(['private']);
+ }
+ expect(await visibilityOf(b, expired)).toBe('private');
+ expect((await engine.executeRaw('SELECT 1 FROM trust_proposals WHERE target_id = ANY($1::bigint[]) OR related_id = ANY($1::bigint[])', [[fencedBefore.id, loose]])).length).toBe(0);
+
+ const recalled = await remoteRecall(b, 'companies/acme-example');
+ expect(recalled).toContain('orchardline revenue grew');
+ expect(recalled).toContain('orchardline database-only legacy fact');
+ __resetPrivateVisibilityCacheForTests();
+ const dispatched = await dispatchToolCall(engine, 'recall', { entity: 'companies/acme-example' }, { remote: true, transport: 'http', auth: b.remote.auth, sourceId: b.sourceId,
+ takesHoldersAllowList: ['world'] }) as { content: Array<{ text: string }> };
+ expect(dispatched.content[0]!.text).toContain('orchardline database-only legacy fact');
+
+ const tighten = await cli(engine, ['visibility', '--source', b.sourceId, '--json']);
+ expect(tighten).not.toContain(`fact ${fencedBefore.id} `);
+ expect(tighten).not.toContain(`fact ${loose} `);
+
+ // A second preview lists nothing: every opened fact is world, every excluded one still excluded.
+ const again = await preview(b);
+ expect(again.affected).toBe(0);
+ }
+ }), 240_000);
+
+ test('test 1: a changed set refuses the stale hash and opens nothing', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine, managed);
+ await page(b, 'companies/acme-example', '', [[1, 'Acme Example is in Springfield', 'world']]);
+ await dbOnly(b, 'Orchardline stale-hash fact one', 'companies/acme-example');
+ const hash = expectHash(await cli(engine, ['open-facts', '--source', b.sourceId, '--created-before', CUT]));
+ expect(hash).toBeTruthy();
+ await dbOnly(b, 'Orchardline stale-hash fact two', 'companies/acme-example');
+ await expect(cli(engine, ['open-facts', '--source', b.sourceId, '--created-before', CUT, '--apply', '--expect', hash!])).rejects.toMatchObject({ code: 'preview_changed' });
+ expect((await facts(b, 'Orchardline stale-hash fact one')).map(f => f.visibility)).toEqual(['private']);
+ expect((await facts(b, 'Orchardline stale-hash fact two')).map(f => f.visibility)).toEqual(['private']);
+ }
+ }), 120_000);
+
+ test('tests 4, 14: every excluded fact is counted by reason and never opened', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine, managed);
+ await page(b, 'companies/acme-example', '', [[1, 'Acme Example is in Springfield', 'world']]);
+ await page(b, 'secret/plan-example', 'visibility: private\n', [[1, 'Orchardline merger plan', 'private']]);
+ await page(b, 'companies/folder-example', '', [[1, 'Orchardline folder fact', 'private']]);
+ await page(b, 'companies/quarantine-example', '', [[1, 'Orchardline quarantined fact', 'private']]);
+ await page(b, 'secret/old-example', 'visibility: private\n', []);
+ await coordinated(b, "UPDATE pages SET deleted_at=now() WHERE source_id=$1 AND slug='secret/old-example'", [b.sourceId]);
+ await proposeRevision(engine, b.sourceId, [{ id: 'folder', prefix: 'companies/folder-example', readable_by: ['member:alice-example'] }], { origin: 'cli', store: 'database' });
+ expect(await engine.executeRaw("SELECT slug FROM pages WHERE source_id=$1 AND folder_rule_ids IS NOT NULL", [b.sourceId])).toEqual([{ slug: 'companies/folder-example' }]);
+ await coordinated(b, `UPDATE pages SET frontmatter = frontmatter || '{"quarantine":{"reason":"junk_pattern","detail":"fixture","assessed_at":"2026-09-01T00:00:00Z"}}'::jsonb WHERE source_id=$1 AND slug='companies/quarantine-example'`, [b.sourceId]);
+ const acme = 'companies/acme-example';
+ const ids: Record<string, number> = {
+ provenance_private: await dbOnly(b, 'Orchardline fact extracted from a private page', acme, { context: 'secret/plan-example extracted' }),
+ provenance_unresolved: await dbOnly(b, 'Orchardline fact from a renamed page', acme, { context: 'gone/renamed-example extracted' }),
+ holding_deleted_private: await dbOnly(b, 'Orchardline fact on a deleted private page', 'secret/old-example'),
+ member_page: await dbOnly(b, 'Orchardline member note', 'memory/members/alice-example'),
+ withdrawn_world: await dbOnly(b, 'Orchardline claim forgotten as world', acme),
+ purged_world: await dbOnly(b, 'Orchardline claim purged as world', acme),
+ pending_forget: await dbOnly(b, 'Orchardline claim with a pending forget', acme),
+ contest_pending: await dbOnly(b, 'Orchardline contested pending', acme),
+ contest_rejected: await dbOnly(b, 'Orchardline contested rejected', acme),
+ contest_undone: await dbOnly(b, 'Orchardline contested undone', acme),
+ transcript: await dbOnly(b, 'Orchardline transcript capture', acme, { source: 'hook:writeback' }),
+ conversation: await dbOnly(b, 'Orchardline conversation extract', acme, { source: 'cli:extract-conversation-facts:v2' }),
+ };
+ ids.superseded = await dbOnly(b, 'Orchardline superseded claim', acme, { supersededBy: ids.member_page });
+ ids.newer_side = await dbOnly(b, 'Orchardline contested newer side', acme);
+ const [folder] = await facts(b, 'Orchardline folder fact');
+ const [quarantined] = await facts(b, 'Orchardline quarantined fact');
+ const open = await dbOnly(b, 'Orchardline plain legacy fact', acme);
+ await coordinated(b, "INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ($1, 'world', $2, gbrain_fact_fingerprint($3))",
+ [b.sourceId, acme, 'Orchardline claim forgotten as world']);
+ await coordinated(b, "INSERT INTO fact_purges (source_id, visibility, subject, fact_hash) VALUES ($1, 'world', '*', gbrain_fact_fingerprint($2))",
+ [b.sourceId, 'Orchardline claim purged as world']);
+ await engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], async () => {
+ await insertTrustProposal(tx, { action: 'forget', sourceId: b.sourceId, target: { table: 'facts', id: ids.pending_forget! }, proposer: 'fixture', before: {} });
+ for (const [key, status] of [['contest_pending', 'pending'], ['contest_rejected', 'rejected'], ['contest_undone', 'undone']] as const) {
+ const { id } = await insertTrustProposal(tx, { action: 'supersede_fact', sourceId: b.sourceId, target: { table: 'facts', id: ids[key]! },
+ related: { table: 'facts', id: key === 'contest_pending' ? ids.newer_side! : ids[key]! }, proposer: 'fence_projection', before: { visibility: { from: 'private', to: 'world' } } });
+ if (status !== 'pending') await tx.executeRaw('UPDATE trust_proposals SET status=$2, decided_at=now() WHERE id=$1', [id, status]);
+ }
+ }, TEST_WRITE_ATTRIBUTION));
+
+ const planned = await preview(b);
+ expect(planned.details.excluded).toMatchObject({ provenance_private: 1, provenance_unresolved: 1, holding_page_private: 3, member_page: 1,
+ withdrawn: 2, contested: 5, superseded: 1, holding_page_quarantined: 1 });
+ expect(planned.details.eligible).toMatchObject({ unfenced: 1, 'unpaged:hook:writeback': 1, 'unpaged:cli:extract-conversation-facts:v2': 1 });
+ expect(planned.listing.map((l: { detail: string }) => l.detail)).toEqual([`fact ${open} (unfenced)`]);
+ await openFacts(b, ['--created-before', CUT, '--apply', '--expect', planned.preview_hash]);
+ expect(await visibilityOf(b, open)).toBe('world');
+ for (const [key, id] of Object.entries({ ...ids, folder: folder!.id, quarantined: quarantined!.id })) {
+ expect([key, await visibilityOf(b, id)]).toEqual([key, 'private']);
+ }
+ }
+ }), 240_000);
+
+ test('test 5: unpaged facts are listed apart by lane and open only when the lane is named', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine, managed);
+ const mail = await dbOnly(b, 'Orchardline mail extract with no page', null, { source: 'mail:extract', entity: null });
+ const capture = await dbOnly(b, 'Orchardline capture with no page', null, { source: 'hook:compact', entity: null });
+ const first = await previewAndApply(b);
+ expect(first.planned.affected).toBe(0);
+ expect(first.planned.details.eligible).toMatchObject({ 'unpaged:mail:extract': 1, 'unpaged:hook:compact': 1 });
+ expect(await visibilityOf(b, mail)).toBe('private');
+ const named = await previewAndApply(b, ['--class', 'unpaged:mail:extract']);
+ expect(named.planned.listing.map((l: { class: string }) => l.class)).toEqual(['unpaged:mail:extract']);
+ expect(await visibilityOf(b, mail)).toBe('world');
+ expect(await visibilityOf(b, capture)).toBe('private');
+ }
+ }), 120_000);
+
+ test('test 5, undo: --undo re-privates an opened unpaged fact', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine, managed);
+ const mail = await dbOnly(b, 'Orchardline mail extract opened then undone', null, { source: 'mail:extract', entity: null });
+ const { applied } = await previewAndApply(b, ['--class', 'unpaged:mail:extract']);
+ expect(await visibilityOf(b, mail)).toBe('world');
+ const ledger = applied!.details.ledger as string;
+ const undo = await openFacts(b, ['--undo', ledger]);
+ expect(undo.listing).toEqual([expect.objectContaining({ class: 'unpaged:mail:extract' })]);
+ const undone = await openFacts(b, ['--undo', ledger, '--apply', '--expect', undo.preview_hash]);
+ expect(undone.applied).toBe(1);
+ expect(await visibilityOf(b, mail)).toBe('private');
+ }
+ }), 120_000);
+
+ test('test 12: a same-tier and an above-tier fenced row each keep id and tier', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine, managed);
+ await page(b, 'companies/tier-example', '', [[1, 'Orchardline same-tier row', 'private'], [2, 'Orchardline confirmed row', 'private'], [3, 'Orchardline world row', 'world']]);
+ const [same] = await facts(b, 'Orchardline same-tier row');
+ const [above] = await facts(b, 'Orchardline confirmed row');
+ await confirmFact(b, above!.id);
+ const { applied } = await previewAndApply(b);
+ expect(applied!.applied).toBe(1);
+ expect((await facts(b, 'Orchardline same-tier row')).map(f => [f.id, f.visibility, f.row_num, f.trust_tier])).toEqual([[same!.id, 'world', 1, same!.trust_tier]]);
+ expect((await facts(b, 'Orchardline confirmed row')).map(f => [f.id, f.visibility, f.row_num, f.trust_tier])).toEqual([[above!.id, 'world', 2, 'user_confirmed']]);
+ expect(await listTrustProposals(engine, { sourceId: b.sourceId, status: 'all' })).toEqual([]);
+ expect((await fenceCell(b, 'companies/tier-example', 2))?.visibility).toBe('world');
+ }
+ }), 120_000);
+
+ test('tests 8, 15: --undo re-privates exactly the opened facts, skipping a row superseded or expired since', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine, managed);
+ await page(b, 'companies/undo-example', '', [[1, 'Orchardline undo fenced row', 'private']]);
+ const kept = await dbOnly(b, 'Orchardline undo kept', 'companies/undo-example');
+ const superseded = await dbOnly(b, 'Orchardline undo superseded later', 'companies/undo-example');
+ const expiring = await dbOnly(b, 'Orchardline undo expired later', 'companies/undo-example');
+ const [fenced] = await facts(b, 'Orchardline undo fenced row');
+ const { applied } = await previewAndApply(b);
+ expect(applied!.applied).toBeGreaterThan(0);
+ const ledger = applied!.details.ledger as string;
+ expect(ledger).toContain(home);
+ for (const id of [kept, superseded, expiring, fenced!.id]) expect(await visibilityOf(b, id)).toBe('world');
+ const replacement = await dbOnly(b, 'Orchardline undo replacement', 'companies/undo-example');
+ await coordinated(b, 'UPDATE facts SET superseded_by=$2 WHERE id=$1', [superseded, replacement]);
+ await coordinated(b, 'UPDATE facts SET expired_at=now() WHERE id=$1', [expiring]);
+ const undo = await openFacts(b, ['--undo', ledger]);
+ expect(undo.details.skipped).toMatchObject({ superseded: 1, expired: 1 });
+ expect(undo.listing.map((l: { detail: string }) => l.detail).sort()).toEqual([`fact ${fenced!.id} (fenced row 1)`, `fact ${kept} (unfenced)`].sort());
+ await openFacts(b, ['--undo', ledger, '--apply', '--expect', undo.preview_hash]);
+ expect(await visibilityOf(b, kept)).toBe('private');
+ expect((await facts(b, 'Orchardline undo fenced row')).map(f => f.visibility)).toEqual(['private']);
+ expect((await fenceCell(b, 'companies/undo-example', 1))?.visibility).toBe('private');
+ expect(await visibilityOf(b, superseded)).toBe('world');
+ expect(await visibilityOf(b, replacement)).toBe('private');
+ }
+ }), 180_000);
+
+ test('test 15: two applies across a window cursor open each fact once', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine, managed);
+ await page(b, 'companies/window-example', '', [[1, 'Acme Example is in Springfield', 'world']]);
+ const one = await dbOnly(b, 'Orchardline window fact one', 'companies/window-example');
+ const two = await dbOnly(b, 'Orchardline window fact two', 'companies/window-example');
+ const first = await previewAndApply(b, ['--limit', '1']);
+ expect(first.planned.listing.map((l: { detail: string }) => l.detail)).toEqual([`fact ${one} (unfenced)`]);
+ expect(first.planned.details.window.next_after).toBe(one);
+ expect(await visibilityOf(b, two)).toBe('private');
+ const second = await previewAndApply(b, ['--limit', '1', '--after', String(one)]);
+ expect(second.planned.listing.map((l: { detail: string }) => l.detail)).toEqual([`fact ${two} (unfenced)`]);
+ expect(second.applied!.applied).toBe(1);
+ expect([await visibilityOf(b, one), await visibilityOf(b, two)]).toEqual(['world', 'world']);
+ expect((await preview(b)).affected).toBe(0);
+ }
+ }), 120_000);
+
+ test('test 15: --ids-file narrows the set to the named facts', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine, managed);
+ await page(b, 'companies/ids-example', '', [[1, 'Acme Example is in Springfield', 'world']]);
+ const named = await dbOnly(b, 'Orchardline named by id', 'companies/ids-example');
+ const other = await dbOnly(b, 'Orchardline not named', 'companies/ids-example');
+ const file = join(home, `ids-${b.sourceId}.txt`);
+ writeFileSync(file, `# curated\n${named}\n`);
+ await previewAndApply(b, ['--ids-file', file]);
+ expect([await visibilityOf(b, named), await visibilityOf(b, other)]).toEqual(['world', 'private']);
+ }
+ }), 120_000);
+ });
+}
+
+describe('test 13: a repo-less keyless PGLite brain opens the stored fenced row in place', () => {
+ test('the stored fenced row becomes world with the same id, its cell reads world, and nothing reports it opened while it stays private', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0]!;
+ const b = await brain(engine, false);
+ expect(await engine.executeRaw('SELECT p.enabled, s.local_path FROM persistence_brain p, sources s WHERE p.singleton=1 AND s.id=$1', [b.sourceId]))
+ .toEqual([{ enabled: false, local_path: null }]);
+ await page(b, 'companies/keyless-example', '', [[1, 'Orchardline keyless row', 'private']]);
+ const [before] = await facts(b, 'Orchardline keyless row');
+ const { applied } = await previewAndApply(b);
+ const [after] = await facts(b, 'Orchardline keyless row');
+ expect(after!.id).toBe(before!.id);
+ expect(applied!.applied).toBe(1);
+ expect(after!.visibility).toBe('world');
+ expect((await fenceCell(b, 'companies/keyless-example', 1))?.visibility).toBe('world');
+ }), 120_000);
+});
+
+/**
+ * Test 16 (review round 1 on PR #9523): a fenced open writes the page, its checkout file and the row in one transaction,
+ * the row first. A fact the locked recheck keeps private (here a pending forget filed after the preview) rolls the page
+ * and the file back, and a file write that fails rolls the row back; either way the apply reports fact_left_private and
+ * never opened while the file, the stored cell or the row is still private. Unmanaged PGLite brain, with and without a
+ * checkout holding the page's file.
+ */
+describe('test 16: the fenced open is one transaction with its page, its checkout file and its row', () => {
+ const slug = 'companies/filed-example';
+ const fileCell = (path: string) => parseFactsFence(readFileSync(path, 'utf8')).facts.find(f => f.rowNum === 1)?.visibility;
+ async function filedBrain(withFile: boolean, claim: string) {
+ const b = await brain(engines[0]!, false);
+ let file: string | null = null;
+ await page(b, slug, '', [[1, claim, 'private']]);
+ if (withFile) {
+ const root = mkdtempSync(join(home, 'checkout-'));
+ mkdirSync(join(root, 'companies'), { recursive: true });
+ await b.engine.executeRaw('UPDATE sources SET local_path=$2 WHERE id=$1', [b.sourceId, root]);
+ const stored = (await b.engine.readPageSnapshot(slug, { sourceId: b.sourceId }))!;
+ file = join(root, slug + '.md');
+ writeFileSync(file, serializePageToMarkdown(stored.page, stored.tags));
+ await coordinated(b, 'UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [b.sourceId, slug, slug + '.md']);
+ }
+ const [before] = await facts(b, claim);
+ expect(before!.visibility).toBe('private');
+ return { b, file, before: before!, text: file ? readFileSync(file, 'utf8') : null };
+ }
+ const forgetAfterPreview = (b: Brain, id: number) => b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], () =>
+ insertTrustProposal(tx, { action: 'forget', sourceId: b.sourceId, target: { table: 'facts', id }, proposer: 'fixture', before: {} }), TEST_WRITE_ATTRIBUTION));
+ const leftPrivate = (applied: Record<string, any>, b: Brain) => {
+ expect(applied.applied).toBe(0);
+ expect(applied.outcome_items).toEqual([expect.objectContaining({ item: `${b.sourceId}:${slug}`, outcome: 'fact_left_private' })]);
+ expect(applied.outcome_items[0].reason).toBeTruthy();
+ };
+
+ test('(a) a page with its file in the checkout: the file cell, the stored cell and the row read world, with the same id', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { b, file, before } = await filedBrain(true, 'Orchardline filed row');
+ const { applied } = await previewAndApply(b);
+ expect(applied!.applied).toBe(1);
+ expect(applied!.outcome_items).toEqual([expect.objectContaining({ item: `${b.sourceId}:${slug}`, outcome: 'opened' })]);
+ const [after] = await facts(b, 'Orchardline filed row');
+ expect(after).toMatchObject({ id: before.id, visibility: 'world', trust_tier: before.trust_tier });
+ expect((await fenceCell(b, slug, 1))?.visibility).toBe('world');
+ expect(fileCell(file!)).toBe('world');
+ }), 120_000);
+
+ for (const withFile of [true, false]) {
+ test(`(b) ${withFile ? 'with' : 'without'} a checkout file: a fact the locked recheck keeps private leaves the file, the stored cell and the row private`, async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { b, file, before, text } = await filedBrain(withFile, 'Orchardline contested row');
+ const planned = await preview(b);
+ expect(planned.preview_hash).toBeTruthy();
+ await forgetAfterPreview(b, before.id);
+ leftPrivate(await openFacts(b, ['--created-before', CUT, '--apply', '--expect', planned.preview_hash]), b);
+ expect(await visibilityOf(b, before.id)).toBe('private');
+ expect((await fenceCell(b, slug, 1))?.visibility).toBe('private');
+ if (file) expect(readFileSync(file, 'utf8')).toBe(text!);
+ }), 120_000);
+ }
+
+ test.skipIf(process.getuid?.() === 0)('(b) a checkout file write that fails after the row update rolls the row back and reports fact_left_private', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { b, file, before, text } = await filedBrain(true, 'Orchardline unwritable row');
+ const dir = join(file!, '..');
+ chmodSync(dir, 0o555);
+ let applied: Record<string, any> | null;
+ try { ({ applied } = await previewAndApply(b)); } finally { chmodSync(dir, 0o755); }
+ leftPrivate(applied!, b);
+ expect(await visibilityOf(b, before.id)).toBe('private');
+ expect((await fenceCell(b, slug, 1))?.visibility).toBe('private');
+ expect(readFileSync(file!, 'utf8')).toBe(text!);
+ }), 120_000);
+});
+
+/**
+ * Test 17 (review round 2 on PR #9523, the owner's grant of one scoped fix): --undo reads the ledger it is given and refuses
+ * a missing one or one that records another brain or source; an open whose intent line is its only record (its write
+ * confirmed after the run stopped waiting) is closed unless the fact was world before that run or an accepted trust
+ * proposal widened it since; a date-only --created-before is midnight UTC whatever the session time zone; a lane with
+ * spaces can be named. Unmanaged PGLite brain.
+ */
+describe('test 17: undo reads the named ledger, intent-only opens, the UTC cut and spaced lanes', () => {
+ const slug = 'companies/undo-example';
+ const factMd5 = (claim: string) => createHash('md5').update(claim).digest('hex');
+ const ledgerLines = (path: string) => readFileSync(path, 'utf8').split('\n').filter(Boolean).map(text => JSON.parse(text));
+ const writeLedger = (lines: object[]) => {
+ const path = join(mkdtempSync(join(home, 'ledger-')), 'open-facts.jsonl');
+ writeFileSync(path, lines.map(line => JSON.stringify(line)).join('\n') + '\n');
+ return path;
+ };
+ /** An unfenced private fact on a page, opened by a real apply; its own ledger lines and the default ledger's path. */
+ async function opened(claim: string) {
+ const b = await brain(engines[0]!, false);
+ await page(b, slug, '', []);
+ const id = await dbOnly(b, claim, slug);
+ const { applied } = await previewAndApply(b);
+ expect(applied!.applied).toBe(1);
+ expect(await visibilityOf(b, id)).toBe('world');
+ const ledger = applied!.details.ledger as string;
+ const mine = ledgerLines(ledger).filter(line => line.source_id === b.sourceId);
+ return { b, id, ledger, mine, intent: mine.find(line => line.phase === 'intent')!, committed: mine.find(line => line.phase === 'committed')! };
+ }
+ const undo = async (b: Brain, ledger: string) => {
+ const planned = await openFacts(b, ['--undo', ledger]);
+ const applied = planned.preview_hash && planned.listing?.length ? await openFacts(b, ['--undo', ledger, '--apply', '--expect', planned.preview_hash]) : null;
+ return { planned, applied };
+ };
+
+ test('--undo plans from the file it names, not the default ledger', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { b, id, ledger, mine, committed } = await opened('Orchardline fact undone from a copied ledger');
+ const copy = writeLedger(mine);
+ writeFileSync(ledger, readFileSync(ledger, 'utf8') + JSON.stringify({ ...committed, at: new Date().toISOString(), action: 'close' }) + '\n');
+ const { planned, applied } = await undo(b, copy);
+ expect(planned.details.ledger).toBe(copy);
+ expect(applied!.applied).toBe(1);
+ expect(await visibilityOf(b, id)).toBe('private');
+ }), 120_000);
+
+ test('a missing ledger, or one that records another brain or another source, refuses with a typed reason', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { b, id, intent } = await opened('Orchardline fact behind a foreign ledger');
+ const brainId = (await resolveRepairScope(b.engine, b.sourceId)).brain_id;
+ await expect(cli(b.engine, ['open-facts', '--source', b.sourceId, '--undo', join(home, 'no-such-ledger.jsonl')])).rejects.toMatchObject({ code: 'invalid_params', reason: 'undo_ledger_missing' });
+ await expect(cli(b.engine, ['open-facts', '--source', b.sourceId, '--undo', writeLedger([{ ...intent, brain_id: 'brain-elsewhere' }])]))
+ .rejects.toMatchObject({ code: 'invalid_params', reason: 'undo_ledger_wrong_brain' });
+ const otherSource = writeLedger([{ ...intent, brain_id: brainId, source_id: 'source-elsewhere' }]);
+ const refused = await cli(b.engine, ['open-facts', '--source', b.sourceId, '--undo', otherSource]).then(() => null, (error: unknown) => error as Record<string, any>);
+ expect(refused).toMatchObject({ code: 'invalid_params', reason: 'undo_ledger_wrong_source' });
+ expect(String(refused!.fix ?? refused!.next ?? JSON.stringify(refused))).toContain('--source source-elsewhere');
+ expect(await visibilityOf(b, id)).toBe('world');
+ }), 120_000);
+
+ test('an open recorded only by its intent line is closed: the late-commit case', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { b, id, intent } = await opened('Orchardline fact whose commit line never came');
+ expect(intent.facts).toEqual([expect.objectContaining({ id, fact_md5: factMd5('Orchardline fact whose commit line never came'), visibility_before: 'private' })]);
+ const { applied } = await undo(b, writeLedger([intent]));
+ expect(applied!.applied).toBe(1);
+ expect(await visibilityOf(b, id)).toBe('private');
+ }), 120_000);
+
+ test('an intent-only fact that was world before that run, or that an accepted proposal widened since, is skipped and reported', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const before = await opened('Orchardline fact already world before the run');
+ const worldBefore = await undo(before.b, writeLedger([{ ...before.intent, facts: before.intent.facts.map((f: object) => ({ ...f, visibility_before: 'world' })) }]));
+ expect(worldBefore.planned.details.skipped).toEqual({ world_before_run: 1 });
+ expect(worldBefore.applied).toBeNull();
+ expect(await visibilityOf(before.b, before.id)).toBe('world');
+
+ const widened = await opened('Orchardline fact widened by an accepted proposal');
+ const ledger = writeLedger([widened.intent]);
+ await widened.b.engine.transaction(tx => withCoordinatedWrite(tx, [widened.b.sourceId], async () => {
+ const { id } = await insertTrustProposal(tx, { action: 'supersede_fact', sourceId: widened.b.sourceId, target: { table: 'facts', id: widened.id }, proposer: 'fixture',
+ before: { visibility: { from: 'private', to: 'world' } } });
+ await tx.executeRaw("UPDATE trust_proposals SET status='accepted', decided_at=now() WHERE id=$1", [id]);
+ }, TEST_WRITE_ATTRIBUTION));
+ const later = await undo(widened.b, ledger);
+ expect(later.planned.details.skipped).toEqual({ widened_by_proposal: 1 });
+ expect(later.applied).toBeNull();
+ expect(await visibilityOf(widened.b, widened.id)).toBe('world');
+ }), 120_000);
+
+ test('a date-only --created-before is midnight UTC in any session time zone, the preview prints it, and a time without an offset refuses', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const b = await brain(engines[0]!, false);
+ await page(b, slug, '', []);
+ const id = await dbOnly(b, 'Orchardline fact saved at five UTC on the cut day', slug);
+ await coordinated(b, "UPDATE facts SET created_at='2026-06-01T05:00:00Z' WHERE id=$1", [id]);
+ await b.engine.executeRaw("SET TIME ZONE 'Pacific/Honolulu'");
+ try {
+ const dateOnly = await openFacts(b, ['--created-before', '2026-06-01']);
+ expect(dateOnly.details.created_before).toBe('2026-06-01T00:00:00.000Z');
+ expect(dateOnly.listing ?? []).toEqual([]);
+ const afterFive = await openFacts(b, ['--created-before', '2026-06-01T06:00:00+00:00']);
+ expect(afterFive.details.created_before).toBe('2026-06-01T06:00:00.000Z');
+ expect(afterFive.listing.map((l: { detail: string }) => l.detail)).toEqual([`fact ${id} (unfenced)`]);
+ } finally { await b.engine.executeRaw('RESET TIME ZONE'); }
+ await expect(cli(b.engine, ['open-facts', '--source', b.sourceId, '--created-before', '2026-06-01T00:00:00'])).rejects.toMatchObject({ code: 'invalid_params', reason: 'created_before_invalid' });
+ }), 120_000);
+
+ test('--class unpaged:<lane> takes a lane whose name has spaces', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const b = await brain(engines[0]!, false);
+ const id = await dbOnly(b, 'Orchardline note from a lane with spaces', null, { source: 'mail extract', entity: null });
+ const planned = await preview(b);
+ expect(planned.details.eligible).toMatchObject({ 'unpaged:mail extract': 1 });
+ expect(planned.warnings.join('\n')).toContain("--class 'unpaged:mail extract'");
+ const { applied } = await previewAndApply(b, ['--class', 'unpaged:mail extract']);
+ expect(applied!.applied).toBe(1);
+ expect(await visibilityOf(b, id)).toBe('world');
+ }), 120_000);
+});
+
+describe('test 11: the #9196 / GST-2511 holds still apply to every other widening', () => {
+ const row = (n: number, claim: string, visibility = 'world') => ({ rowNum: n, claim, kind: 'fact', confidence: 1, visibility, notability: 'medium', active: true });
+ const body = (rows: ReturnType<typeof row>[]) => `Profile.\n\n## Facts\n\n${renderFactsTable(rows as never)}`;
+ const note = (title: string, text: string) => `---\ntype: note\ntitle: ${title}\n---\n${text}\n`;
+ test('a remote put_page that writes world over a confirmed private row is held private (GST-2511)', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ for (const managed of [true, false]) {
+ const b = await brain(engine, managed);
+ const slug = 'people/kim-example';
+ await run(b.local, 'put_page', { slug, content: note('Kim', body([row(1, 'Kim lives in Turin'), row(2, 'Kim keeps bees', 'private')])) });
+ for (const r of await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [b.sourceId, slug])) await confirmFact(b, Number(r.id));
+ const current = await run(b.remote, 'get_page', { slug, include_content: true });
+ const widened = await run(b.remote, 'put_page', { slug, content: note('Kim', body([row(1, 'Kim lives in Turin'), row(2, 'Kim keeps bees')])), expected_revision: current.revision });
+ expect(widened.contested?.proposal_ref).toMatch(/^tp\d+$/);
+ expect((await facts(b, 'Kim keeps bees')).map(f => f.visibility)).toEqual(['private', 'private']);
+ expect(await remoteRecall(b, slug)).not.toContain('Kim keeps bees');
+ }
+ }
+ }), 120_000);
+
+ test('a remote remember fence append of a confirmed private claim leaves the confirmed row private and files no open', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine, true);
+ const slug = 'people/lia-example';
+ await run(b.local, 'put_page', { slug, content: note('Lia', body([row(1, 'Lia lives in Turin'), row(2, 'Lia keeps bees', 'private')])) });
+ for (const r of await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [b.sourceId, slug])) await confirmFact(b, Number(r.id));
+ const [confirmed] = await facts(b, 'Lia keeps bees');
+ await run(b.remote, 'remember', { fact: 'Lia keeps bees', provenance: 'chat', entity: slug });
+ const rows = await facts(b, 'Lia keeps bees');
+ expect(rows.find(f => f.id === confirmed!.id)).toMatchObject({ visibility: 'private', trust_tier: 'user_confirmed' });
+ expect(rows.filter(f => f.id !== confirmed!.id && f.trust_tier === 'user_confirmed')).toEqual([]);
+ }
+ }), 120_000);
+});
+
+describe('test 15: a page flipped private while the apply waits leaves its fact private (Postgres, two sessions)', () => {
+ test('the locked recheck reads the committed flip', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines.find(e => urls.has(e));
+ if (!engine) return;
+ const b = await brain(engine, false);
+ await page(b, 'companies/race-example', '', [[1, 'Acme Example is in Springfield', 'world']]);
+ const raced = await dbOnly(b, 'Orchardline raced fact', 'companies/race-example');
+ const planned = await preview(b);
+ expect(planned.listing.map((l: { detail: string }) => l.detail)).toEqual([`fact ${raced} (unfenced)`]);
+ const other = postgres(urls.get(engine)!, { max: 1, prepare: false });
+ try {
+ let release!: () => void;
+ const held = new Promise<void>(resolve => { release = resolve; });
+ const flip = other.begin(async sql => {
+ await sql.unsafe(`UPDATE pages SET frontmatter = frontmatter || '{"visibility":"private"}'::jsonb WHERE source_id=$1 AND slug='companies/race-example'`, [b.sourceId]);
+ await held;
+ });
+ await new Promise(resolve => setTimeout(resolve, 200));
+ const apply = openFacts(b, ['--created-before', CUT, '--apply', '--expect', planned.preview_hash]);
+ await new Promise(resolve => setTimeout(resolve, 1500));
+ release();
+ await flip;
+ const applied = await apply;
+ expect(applied.applied).toBe(0);
+ expect(await visibilityOf(b, raced)).toBe('private');
+ } finally { await other.end(); }
+ }), 120_000);
+});
+
+describe('remote page rewrite keeps hidden private fence rows (Discussion #8194, second half; test 10, a pin, green today)', () => {
+ test('a remote put_page that rewrites only the body keeps the private row in the page and the database with the same id', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ for (const managed of [false, true]) {
+ const b = await brain(engine, managed);
+ await page(b, 'companies/beta-example', '', [[1, 'Beta Example orchardline private row', 'private'], [2, 'Beta Example world row', 'world']]);
+ const [before] = await facts(b, 'Beta Example orchardline private row');
+ expect(before.visibility).toBe('private');
+ const read = await run(b.remote, 'get_page', { slug: 'companies/beta-example', include_content: true });
+ expect(String(read.content)).not.toContain('orchardline private row');
+ await run(b.remote, 'put_page', { slug: 'companies/beta-example', expected_revision: read.revision, content_origin: 'user_said',
+ content: String(read.content).replace('Orchardline body.', 'Orchardline body, rewritten.') });
+ expect((await facts(b, 'Beta Example orchardline private row')).map(f => [f.id, f.visibility, f.row_num])).toEqual([[before.id, 'private', 1]]);
+ const [stored] = await engine.executeRaw<{ body: string }>('SELECT compiled_truth AS body FROM pages WHERE source_id=$1 AND slug=$2', [b.sourceId, 'companies/beta-example']);
+ expect(stored.body).toContain('Beta Example orchardline private row');
+ expect(stored.body).toContain('Orchardline body, rewritten.');
+ }
+ }
+ }), 180_000);
+});
diff --git a/test/trust-write-gate-drift.test.ts b/test/trust-write-gate-drift.test.ts
index bd6f76b19e..4d675d68ca 100644
--- a/test/trust-write-gate-drift.test.ts
+++ b/test/trust-write-gate-drift.test.ts
@@ -75,6 +75,7 @@ const EXEMPT: Record<string, string> = {
'src/core/repair/atoms-restore.ts': 'restores an owner-approved retired atom to its own earlier version (lifecycle); no new text',
'src/core/repair/take-supersession.ts': 'owner repair of take supersession pointers',
'src/core/repair/timeline-comments.ts': 'owner repair of timeline comment markup',
+ 'src/core/repair/open-facts.ts': 'operator-only local CLI repair (remote callers and member mode refused) behind a preview hash and --expect: only flips existing fact rows from private to world, and back on --undo (no new text); fenced rows rewrite only the visibility cell of their page through the label write (writeLabelFile, importAtRevision)',
'src/core/repair/visibility.ts': 'owner repair behind a preview: only tightens existing fact rows from world to private (no new text); fenced rows and page labels publish through put_page, which runs the gate',
'src/core/schema-pack/page-to-alias.ts': 'schema-pack retype of existing pages',
'src/core/schema-pack/page-to-link.ts': 'schema-pack retype of existing pages',