Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Privacy label repairs keep a page trusted and edit only the label lines (GST-2468)
garrytan8eb3ac6dd497
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a112377797..fe53922fc5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,21 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**Making a page private through an operator repair no longer lowers its trust or rewrites its file.** On a managed brain, an operator who added `visibility: private` to one page through a local `put_page`, or ran `gbrain repair visibility`, saw the page drop from "your notes" (operator_curated) to "written by an agent", a pending `lower_page` proposal only a typed token could settle, and a re-rendered file: a `slug` key removed, a `source_kind` value overwritten with `put_page`, keys reordered, and provenance stamps and a `trust_tier` marker added. Both repairs and `gbrain repair private-labels` now write through one label-only door: the page keeps its tier, no proposal is filed, and its file changes only on the label lines, with every other key, its order and the body kept byte for byte. A new slug-bound form, `gbrain repair visibility --slug <page>`, is the operator's single-page way to make a page private (preview first, then `--apply --expect <hash>`). A plain `put_page`, local or remote, is still an agent edit and lowers the page as before. `gbrain trust backfill --label-lowerings` lists every `lower_page` proposal as label-only or content, counted by proposer, so an operator can see which lowerings came from label-only writes; it changes nothing, and raising a page back stays a trust decision.++### Itemized changes++- `src/core/persistence/label-edit.ts` (new): the `label_edit` intent (`set` and `remove` over `visibility`, `access`, `confidentiality`) and the line editor that applies it to a file's frontmatter, or declines a label line it cannot edit as one line.+- `src/core/persistence/page-prepare.ts`: a `managed_maintenance_page` write that carries `label_edit` publishes the canonical file's own bytes with only its label lines edited (`labelEditFile`), keeping its body when it reads as the write's body, and refuses instead of re-rendering when no line edit reads back as the write.+- `src/core/persistence/prepared-maintenance.ts`: maintenance page publications carry `labelEdit`.+- `src/core/repair/label-write.ts` (new): the label-only write door both repairs use (the maintenance door with `keep_trust` on a managed brain; the import under the page lock and `withTrustKeep` otherwise); `filesInCheckout` and `importAtRevision` moved here from `private-labels.ts`.+- `src/core/repair/visibility.ts`: page and fenced-fact items write through the label door instead of `put_page`; on a brain without managed persistence a page whose file sits in a checkout is held (`file_backed`) and a segmented page is held (`segmented_page`); new `--slug` selection (class `pages`), preview-bound, tighten-only.+- `src/core/repair/private-labels.ts`: clears and restores carry their label edit, so the file loses or regains only those lines.+- `src/core/trust/label-lowerings.ts` (new), `src/cli/commands/trust.ts`: `gbrain trust backfill --label-lowerings [--source ID] [--json]`, read-only.+- Tests: `test/label-only-repairs.test.ts` (managed Git source and repo-less brain, PGLite and Postgres).+## [0.60.678.0] - 2026-11-11**Pushes from an unmanaged checkout now scan every commit they publish for secrets, not only the files they just wrote.** Four gbrain pushes from a checkout that is not a managed worktree carried earlier local commits to the remote unscanned: the access-policy commit, the durability-scaffolding commit, `gbrain sources push` (which scanned only its own staged files, then pushed the whole branch tip, even with nothing new to commit) and the first push of `gbrain bootstrap repo` after the remote branch was gone (which scanned only the current tree). A credential a script committed with plain `git commit`, including one a later commit removed or one in a commit message, went out with them. Each now runs the range scan managed publishes use over what the remote lacks (the whole history when the remote has no such branch) and refuses `publish_secret_found` or `publish_scan_unreadable`, with nothing pushed and the local commits kept. `gbrain sources push` pushes the exact commit it scanned, leased on the remote tip it read, so a remote rewound in between is scanned again. An allowlist edit that `gbrain sources push` or `gbrain bootstrap repo` commits itself, after scanning it, still publishes; one a script committed is left to the user. Remoteless checkouts, managed worktrees and repo-less brains are unchanged, and the policy command's retry hint keeps `--scan-secrets`.diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex 35f7a2c745..772804ae61 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -42,3 +42,4 @@ The #6188 fence check and fence repair live in [fence repair](core-fence-repair.- `src/core/postgres-engine/reserved-transactions.ts` with `isPersistenceDeclaration` (`src/core/persistence/protocol.ts`) — BEGIN pipelining. `isPersistenceDeclaration` (GBRA-156) accepts exactly the `protocol.ts` declarations (transaction-local `set_config` calls and the brain row FOR SHARE). Admission, the FIFO claim, the effect claims and source guards, the receipt true-up, the single publication (`coordinator.ts`) and the consumer's lent lane transactions (`consumer.ts` `onLane`, through `reservedTransactions`) pass it as `TransactionOptions.pipelineFirst`, so behind a transaction-mode pooler the declaration goes out with BEGIN (one round trip less per transaction) while every later statement still waits for BEGIN's answer; if BEGIN fails, only the declaration has run, in autocommit, where it changes nothing. A reserved transaction gates every statement its body can reach, savepoint and nested-transaction bodies and `file()` included. A sync lane group's publication passes none: its begun mark must follow BEGIN's answer (`sync-lanes.ts` `awaitLaneBegin`). Tests: `test/persistence-pipeline-first.test.ts` (the predicate and the reviewed call sites), `test/e2e/pgbouncer-transaction-pipeline-6930.test.ts`.- `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 `invalid_params`; the file is never re-rendered under a label edit. `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, which callers hold as `file_backed`.diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.mdindex c781a8a551..fc76613272 100644--- a/docs/architecture/key-files/security.md+++ b/docs/architecture/key-files/security.md@@ -35,6 +35,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/trust/taint.ts`, `derived-gate.ts`, `timeline-projection.ts` (#5575 derived rows; the rest of `src/core/trust/` is above): `taint.ts` (I2, ENG-3/ENG-7): `readTaintInputs`/`deriveTrust` read the stored tiers of every row a deriver placed in its prompt (a vanished input reads `unknown`); `derivedWriteTrust` caps model output at `agent_written` and a deterministic projection (fence or timeline parse) at `operator_curated`; `recordTaintEdges` writes the complete `derivation_inputs` edges; `lowerToDerivedTier`/`lowerDerivedPage` (and `lowerDerivedPageIn`, the same inside a caller's coordinated transaction) lower a derived row whose republish changed no content column; `derivedMaintenanceTransaction` is the unmanaged deriver seam; `declareDerivation`/`declaredWriteTrust` carry a derivation in a maintenance or facts intent (the preparer stamps it, never above `agent_written`); `readDerivedTaintShare` is the doctor CEO-24 diagnostic. `derived-gate.ts`: the derivers' row-level write gate at the declared tier (`derivedGateConfig`, `applyGateDecision`: insert + flag receipt, hold, or skip a reject; `recordTimelineFlag`). `timeline-projection.ts`: `gbrain extract` timeline walks stamped per page tier and gated; `addProjectedPageTimeline` writes one page's own timeline as one batch that holds the live page FOR SHARE and refuses a missing one (`requirePages`), falling back row by row when the database refuses the batch (#6805). Tests: `test/trust-taint.test.ts`, `test/trust-taint-origin.test.ts` (PGLite and Postgres), `test/trust-taint-dream.test.ts`.- `src/core/trust/claim.ts` + `claim-state.ts` + `claim-notice.ts`, `src/commands/trust-claim.ts`: #5575 legacy content. `gbrain trust claim-sources` (local CLI; typed source id on a TTY, `--yes` never counts, non-TTY refuses `confirmation_required` with a tell_user_to_run fix) records a claim in `sources.config` (`trust_tier: operator_curated`, `trust_claimed_at`, `trust_claim_lifted_at`) and lifts the source's legacy `unknown` rows (ids at or below `write_gate.scan_baseline`) through `trust/backfill.ts` scoped to the claimed sources (own cursor, `write_origin.channel` `trust_claim`), lowered by `frontmatterTrustCapsSql` (channel.ts, pinned to `frontmatterTrustCaps`) and every backfill signal, never above operator_curated; connector sources refuse. Doctor `trust_sources_unclaimed`, `gbrain post-upgrade` and the behavior-change notice name the claim (`actor: user`, tell_user_to_run); doctor `trust_scan`'s fix is the user's to run; the scan refuses while a lift is pending; explain and review show pending rows as owner tier. `claim-sources --relower [--dry-run]` (`relowerClaimedRows`, backfill.ts) is the lower-only #6533 repair: `trust_claim` rows whose page rule now ranks below their stored tier (legacy `extracted_by: extract_atoms-*` atoms) drop to it, pages first with child rows following through the relower-mode page taint, receipt `write_origin.channel` `trust_relower`; the dry run reports the same rows; doctor `trust_sources_unclaimed` names it. Guide: `docs/guides/memory-trust.md`. Tests: `test/trust-claim.test.ts`, `test/trust-claim-relower.test.ts`.- `src/core/trust/marker-repair.ts`: #6550 `gbrain trust backfill --repair-unknown-markers` (local CLI, `src/cli/commands/trust.ts`). `previewMarkerRepair` lists live pages whose frontmatter `trust_tier` is `unknown` while the row is higher, with evidence (first `page_versions` snapshot showing the marker vs the fixed release `UNKNOWN_MARKER_FIX_RELEASE`: its commit time bounds the first run, `upgrade-state.json` can name it; whether the oldest kept version had the marker), an `assessment` (`consistent_with_6550` only when a pre-fix snapshot shows it and the first import did not, else `ambiguous`), pages already lowered through the marker (with their revert command), a `preview_hash` and the apply argv naming only the consistent pages. `applyMarkerRepair` refuses `preview_changed` unless the fresh preview hashes to `--expect`, then calls `page-handlers.ts` `repairPageMarker` per named slug: the `trust_owner_page` mode `repair_marker` (refused for remote requests) rewrites the marker to `repairedMarker(stored tier)` (none at owner tiers) at the previewed revision and keeps the tier. `review.ts` adds a `repair` command to `lower_page` items an `unknown` marker caused. Pinned by `test/trust-channel-writes.test.ts` (#6550 repair) and `test/trust-cli.test.ts`.+- `src/core/trust/label-lowerings.ts`: GST-2468 `gbrain trust backfill --label-lowerings` (local CLI, `src/cli/commands/trust.ts`), read-only. `listLabelLowerings` reads every `lower_page` proposal with the `page_versions` row its `before_state.version_id` names and the live page, and classes it `label_only` (only `LABEL_KEYS` and the stamp keys differ, a label among them), `content` or `unreadable`, counted by proposer; `changed_since` when the page moved past the proposal's recorded revision. Writes nothing.- `src/core/trust/provenance-drift.ts`, `src/core/repair/provenance.ts`, `src/commands/doctor/checks/provenance-stamp-drift.ts`: #7891 / #7918. `analyzePageDrift` (pure) walks a page's `page_versions` plus its live row; each transition's writer is the older snapshot's `archived_write_request_id` (joined to `persistence_requests.id` for `authority.remote`, else the principal kind; none: `unattributed`). Verdicts: `remote`, `ambiguous`, `local`, `needs_review` (a later local write changed the same stamp) and `restamp` (a classified page whose live caps rank above its stored tier). A restore puts each stamp back to the server-written column or the value before the first non-local change, and stamps min(lost cap, live caps, stored tier) with `stampTrustMarker`, so it only lowers. `scanProvenanceDrift` is bounded (`DRIFT_SCAN_LIMIT` per source) and degrades to `pre_trust` / `pre_attribution`. The doctor check is read-only; the repair kind is explicit-only and preview-bound (`provenance-v1` hash, approved set) and writes through `trust_owner_page` mode `restore_provenance` (`restorePageProvenance` in `page-handlers.ts`, local CLI only, re-checked against `plannedDigest`, files `lower_page` with proposer `provenance_repair`) or `repair_marker` for `restamp`. A page sync holds is listed `held` by the preview and skipped `held` by the apply, both through `pageHolds` (#8009), so the apply writes what the preview counted. Both repair modes render the page to its file on a classic checkout (`writePageThrough` with the preimage bytes). #7917: `recordAgentPageLowering` also files for derived publications and for callers that name a proposer; `prepareMaintenanceMutation` and `derivedMaintenanceTransaction` (rows carrying `prior`) call it. #7918: `derivationWriteTrust` rates a present but unreadable declaration `unknown`.- `src/core/write-gate.ts` + `src/core/write-gate-patterns.ts` — the #5575 blocking write gate, separate from observe-only `guardrails.ts` (never imported). Deterministic and model-free (P8): `WRITE_GATE_PATTERNS` (bounded clones of the detection-grade `think/sanitize.ts` `INJECTION_DETECTION_PATTERNS`, the exported transcript `IMPERATIVE_RES`, plus standing-instruction (incl. agent-addressed rules with long run-ups, concealment and act-without-asking clauses), exfiltration (incl. passive "must be emailed to <address>" rules and direct cc/bcc) and credential patterns; families `override`, `standing_instruction`, `exfiltration`, `credential`). `detectInstructionLike` decodes tag characters, strips invisibles and NFKC-folds compatibility forms only when present, finds anchor words in one allocation-light hash pass (one tight loop per word), then runs each pattern only on 4 KB windows (overlap `MAX_MATCH_CHARS` + `MAX_PRECEDING_CHARS`) holding its anchors, tracked as sliding per-window anchor counts, and inside a window only within the pattern's longest match (`write-gate-regex.ts`, the analysis the regex lint uses) of its own anchor words, except `WHOLE_WINDOW_PATTERNS`; `preceded` regexes check context before a rare-token match, a `neg` group rejects negated matches. `assessPageForGate` (title, body minus managed fence table rows, frontmatter strings), `assessFactForGate` (fact, context, value, provenance, pre-sanitized `source_text`), `assessTakeForGate` and `assessTimelineForGate` scan every attacker-controllable field plus origin strings. Verdicts by tier: owner tiers never assessed; `external_untrusted` -> `write_gate.external_mode` (`flag` default per the paid eval, `quarantine` opt-in, `reject`, `off`), detector error -> quarantine; `agent_written`/`unknown` -> `flag` (`write_gate.agent_mode=off`), detector error -> allow. `writeGateOutcome` is the DX-1 `gate` shape; `writeHeldError` / `writeGateRejectedError` build the `write_held` / `write_gate_rejected` refusals (families only, no pattern names). `scripts/check-write-gate-regex.ts` (in verify) proves every pattern bounded. `assessPageForGate` / `assessWriteGate` take an optional `WriteGateWork` accumulator (`createWriteGateWork`) the detector fills per assessment with the work it did (normalization and anchor-pass input units, windows, pattern checks past the prefilter, regex executions, searched characters); nothing is kept between calls (#6490). Tests: `test/write-gate.test.ts`, `test/write-gate-perf.slow.test.ts` (quiet-round absolute p95 with the receipt insert, 5 MB linear bounds), `test/write-gate-work-counters-6490.test.ts` (the counters pinned per corpus; four mutants fail it: disabled prefilter, REACH x8, a per-window normalization pass, a pattern anchored on `the`), `test/write-gate-anchor-ranges.test.ts` (sampled matches of every narrowed pattern hold an anchor word within its longest match), and `test/write-gate-detector-differential.test.ts` (identical hits to the pre-optimization detector v2 kept as `test/helpers/write-gate-detector-reference.ts`, over the detector corpora, BrainBench fixtures, docs/skills and a seeded random corpus).diff --git a/docs/guides/memory-trust.md b/docs/guides/memory-trust.mdindex 958ec43eee..e02c15dc83 100644--- a/docs/guides/memory-trust.md+++ b/docs/guides/memory-trust.md@@ -271,6 +271,26 @@ The marker becomes the page's stored tier (pages at "your notes" or higherget no marker), and the page keeps its tier. This runs on the local CLI only.Run the preview again to verify: repaired pages no longer show.+## Label lowerings++A privacy label is not content. `gbrain repair visibility` (including+`--slug <page>` for one page) and `gbrain repair private-labels` keep a+page's tier, file no `lower_page` item, and change only the label lines of its+file. A `put_page` that adds the same label is an agent edit and lowers the+page, because a local agent with a shell is indistinguishable from you.++```bash+gbrain trust backfill --label-lowerings [--source <id>] [--json] # read-only+```++It lists every `lower_page` item and compares the version the lowering+replaced with the page now: `label_only` when only `visibility`, `access` or+`confidentiality` and the server's stamps (`trust_tier`, `source_kind`,+`ingested_via`, `ingested_at`) changed, `content` otherwise, and+`unreadable` when the replaced version is gone. Counts are grouped by proposer+(`agent_page_edit:put_page`, `derived_page:submit_job`, ...). It changes no+tier: raising a page back is your decision in `gbrain trust review`.+## Scan older memory (only when you agree)```bashdiff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 1b2b107cd3..d9b067e4cc 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -78,8 +78,20 @@ concept-provenance links), reports progress on stderr, lists one window```bashgbrain repair visibility --class facts # one class: facts, events, aliases or lineagegbrain repair visibility --class facts --apply --expect <hash> # exactly that window+gbrain repair visibility --slug notes/a-example # make named pages private (repeatable)+gbrain repair visibility --slug notes/a-example --apply --expect <hash>```+Every visibility write is label-only: the page keeps its trust tier, files no+`lower_page` proposal, and its file changes only on the `visibility` line (a fact+item: its fence row). A file that cannot take the change without being+re-rendered (a label with a block value or a duplicate key, no frontmatter+block) is refused with nothing written; make that edit by hand. `--slug` is the operator's way to make one page private;+a `put_page` that adds the label is an agent edit and lowers the page. On a brain+without managed persistence, a page whose file sits in its source's checkout is+held (`file_backed`) with the file edit to make, since a database-only write+would be undone by the next sync.+The apply touches only the listed items and resumes after its last applieditem if it stops. Apply the window (or decide not to), then preview again forthe next one. Each plan statement is bounded at 120 s; a class that overruns is@@ -2175,7 +2187,10 @@ refused. On a brain without managed persistence the repair writes only thedatabase, so a page whose file sits in its source's checkout is held withoutcome `file_backed`. The next sync or re-import would put the label back fromthe file, so edit the file's frontmatter, commit it, and run-`gbrain sync --source <id>`. Repo-less pages clear as usual.+`gbrain sync --source <id>`. Repo-less pages clear as usual. A clear or restore+changes only the label lines of the page's file and keeps its trust tier; a+restore whose label value isn't a plain word is held as `label_not_plain`, so+add that label to the file by hand.**Windows and resume.** `--limit <n>` sets the window size (default 1000, atmost 10000). When more pages remain past the window, the preview says so: applydiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 728118c9e0..5dcf782ac0 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -48,5 +48,5 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1530 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1734 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1)+src/core/behavior-change-notice.ts 1735 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move)src/commands/auth.ts 1503 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot movediff --git a/src/cli/commands/trust.ts b/src/cli/commands/trust.tsindex 2667f47955..a3f4aac838 100644--- a/src/cli/commands/trust.ts+++ b/src/cli/commands/trust.ts@@ -1,6 +1,6 @@/*** `gbrain trust`: the memory-trust noun (#5575, DX-7). This module dispatches- * `backfill` (A8, DX-5; `--repair-unknown-markers`, #6550 trust/marker-repair.ts), `scan` (DX-6) and `claim-sources` (legacy content, trust/claim.ts),+ * `backfill` (A8, DX-5; `--repair-unknown-markers`, #6550 trust/marker-repair.ts; `--label-lowerings`, GST-2468 trust/label-lowerings.ts), `scan` (DX-6) and `claim-sources` (legacy content, trust/claim.ts),* and hands the owner subcommands (review, confirm,* release, drop, revert, explain, allow, disable) to src/commands/trust.ts.* The record is startup: 'observational', so `backfill --dry-run` and `claim-sources --dry-run` run on a@@ -31,6 +31,10 @@ export const TRUST_BACKFILL_USAGE = [' preview whose hash you pass to --expect. The marker becomes the stored tier (none at owner tiers); the tier',' stays. Local CLI only. Docs: docs/guides/memory-trust.md#repair-unknown-markers','',+ 'Usage: gbrain trust backfill --label-lowerings [--source ID] [--json]',+ ' Read-only. Lists every lower_page proposal with whether its lowering write changed only privacy labels (visibility,',+ ' access, confidentiality) and server stamps, counted by proposer. Changes no tier. Docs: docs/guides/memory-trust.md#label-lowerings',+ '','Usage: gbrain trust scan [--batch-size N] [--json]',' Runs the write gate\'s deterministic detector over agent-written and lower rows written before the gate,',' recording a receipt for each instruction-like row, so it reads as flagged (and, under trust.agent_activation',@@ -131,6 +135,20 @@ export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchCscan.complete ? ' Complete. Flagged rows carry their flag wherever they are read (and stay out of proactive context under trust.agent_activation suppress) until confirmed (gbrain trust review).' : ` Continue with: ${scan.resume_command}`].join('\n'));return;}+ if (rest.includes('--label-lowerings')) {+ await ctx.completeStartup?.(engine);+ const at = rest.indexOf('--source');+ const source = rest.find(arg => arg.startsWith('--source='))?.slice('--source='.length) ?? (at >= 0 ? rest[at + 1] : null);+ if (source !== null && (!source || source.startsWith('-'))) {+ await refuse(args, '--source needs a source id.', 'Run gbrain trust backfill --label-lowerings --source <id>, or omit --source to list every source.');+ return;+ }+ const { listLabelLowerings, renderLabelLowerings } = await import('../../core/trust/label-lowerings.ts');+ const report = await listLabelLowerings(engine, { sourceId: source });+ if (jsonRequested(args)) await writeStdoutFinal(`${JSON.stringify(report, null, 2)}\n`);+ else console.log(renderLabelLowerings(report));+ return;+ }if (rest.includes('--repair-unknown-markers')) {await ctx.completeStartup?.(engine);await runMarkerRepair(engine, rest, args);diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 7e76cffd51..2eab1f51c3 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -211,7 +211,7 @@ const VALUE_FLAGS = new Set(['--rules', '--source', '--limit', '--expect', '--onconst 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', 'timeline-order', 'contact-rows', 'provenance', 'secret-spans', 'segmented-tiling'], '--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', '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'],'--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'],diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 626319db48..6b9e75d701 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1535,6 +1535,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.676.0', id: 'opt_in_receipt_caps_gbra108', text: 'gbrain\'s own receipt bookkeeping no longer refuses, pauses or throttles writes by default: the cumulative caps on permanent request ids and reserved receipt bytes (`persistence.limits.{principal,brain}_{lifetime_ids,terminal_bytes}`, 2,000,000 / 8,000,000 ids and 16 GiB / 64 GiB before) apply only when set, so `write_quota_exhausted`, `write_quota_insufficient`, `write_capacity_backpressure`, `write_capacity_low` and a sync\'s `capacity_paused` happen only under a cap the operator chose. Instead, while receipts not yet compacted reserve more than `persistence.housekeeping.receipt_target_bytes` (default 8 GiB, 0 off; compacted receipts never count) and the retention is the default, the compaction pass also compacts settled page writes and refused maintenance and managed sync page writes older than 7 days (job receipts, a subagent\'s own page writes, connector writes and every other refusal keep their intent until the retention window), the `/metrics` `gbrain_write_capacity_*` gauges appear only for a cap that is set, and the retention pass no longer drops a caller\'s refused write that `gbrain repair failed-writes` could still replay (it waits until a later write resolves it, or `gbrain repair receipt-compaction --include-failures` drops it), and doctor `persistence_capacity` warns the host operator. A cap already set is unchanged; `gbrain config unset` removes one. On a brain several hosts write to, this holds once every host runs this version: an older gbrain still enforces its old caps and 30-day retention, and raising a cap as its refusal suggests turns the cap on for every host.' },{ since: '0.60.676.0', id: 'write_capacity_low_saved_gst2107', text: 'The `write_capacity_low` notice a write receipt carries now opens with "This write was saved" and its fix is the read-only `gbrain doctor --only persistence_capacity --json` (actor agent) instead of a `gbrain config set` cap raise for the user, so an agent reading the end of a successful write no longer reports it as refused. The one-more-year value doctor, the notice snapshot and `/metrics` recommend now uses the 7-day mean rate, so one bulk day is no longer projected for a year; days-to-exhaustion still uses the larger of the mean and the last 24 hours. A `write_quota_exhausted`, `write_quota_insufficient` or background-pause refusal names the same value doctor does instead of sizing the year from the latest 1,000 admissions.' },{ since: '0.60.676.0', id: 'ingest_backfill_409_recovery_gst2112', text: 'A `revision_backfill_pending` refusal (a write to a page the revision backfill has not reached, including the 409 a webhook capture to such a page gets from `POST /ingest`) now names the command that resumes the backfill, `gbrain apply-migrations --force-schema` on the brain host, instead of `gbrain apply-migrations --yes`, which does not resume it once the schema is current. A capture answered 409 stores and queues nothing, so its sender sends it again after the backfill; an `ingest_capture` job already queued for such a page goes straight to dead and is re-run with `gbrain jobs retry <id>`.' },+ { since: 'TBD', id: 'label_only_operator_repairs_gst2468', text: '`gbrain repair visibility` and `gbrain repair private-labels` now write a page through a label-only door: the page keeps its trust tier, files no `lower_page` proposal, and its file changes only on the label lines (other keys, their order and the body are kept). Before, `repair visibility` wrote through `put_page`, which lowered the page to agent_written and re-rendered its frontmatter. On a brain without managed persistence, a page whose file sits in its source checkout is now held (`file_backed`) with the file edit to make, as `private-labels` already did. New `gbrain repair visibility --slug <page>` makes named pages private, preview first. New read-only `gbrain trust backfill --label-lowerings` lists `lower_page` proposals as label-only or content by proposer. A plain `put_page` still lowers as an agent edit.' },{ since: '0.60.678.0', id: 'unmanaged_push_history_scan_8902', text: 'Four pushes from a checkout that is not a managed worktree now scan every local commit they publish for secrets, not only what they just wrote: the access-policy commit (`gbrain access rule` and the other policy writers), the durability-scaffolding commit of `gbrain sources harden`, `gbrain sources push`, and the first push of `gbrain bootstrap repo` (the whole history, since the remote has no such branch yet). A credential that a commit made with plain `git commit` added, even one a later commit removed, or one in a commit message, now refuses `publish_secret_found` naming the file, line, rule and commit (never the value), and nothing is pushed; history the scan cannot read in full refuses `publish_scan_unreadable`. The local commits stay where they are. `gbrain sources push` now pushes the exact commit it scanned, leased on the remote tip it read, and an allowlist (`.gbrain-scan-allow`) edit it commits itself still publishes; one a script committed is left for the user to review and push. Remove the value from the unpublished commits, or allowlist a false positive by fingerprint, then rerun.' },];diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 2e39a28afa..4d6e6b602f 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', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--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', '--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', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--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', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--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', '--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', '--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', '--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', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--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', '--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', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--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', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--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', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--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-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--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', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--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', '--root', '--routing', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--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', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--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', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--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', '--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', '--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', '--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', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--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', '--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', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--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', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--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', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--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-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--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', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--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', '--root', '--routing', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--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', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--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', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--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', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -78,7 +78,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--catalog', '--count', '--diff-filter', '--dir', '--enable', '--end-of-options', '--env', '--force-with-lease', '--gbrain-bin', '--get', '--harness', '--help', '--instructions', '--instructions-only', '--is-ancestor', '--jq', '--json', '--limit', '--name-only', '--no-instructions', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--remove', '--scope', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--verify', '--workspace', '--yes'],'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-stdio-member', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--reason', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--scan-secrets', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-stdio-member', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--reason', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--scan-secrets', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-content', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--serves', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdio-member', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],@@ -139,7 +139,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--images', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--stale', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--as', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],- 'trust': ['--accept-all', '--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--legacy-lock', '--no-accept-pending', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],+ 'trust': ['--accept-all', '--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--label-lowerings', '--legacy-lock', '--no-accept-pending', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--check-downgrade', '--check-only', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'wakeshift': ['--apply', '--brain', '--expect', '--help', '--json', '--key-stdin', '--max-cost', '--max-usd', '--non-interactive', '--source', '--trust', '--url', '--yes'],diff --git a/src/core/persistence/label-edit.ts b/src/core/persistence/label-edit.tsnew file mode 100644index 0000000000..ae599f4e70--- /dev/null+++ b/src/core/persistence/label-edit.ts@@ -0,0 +1,66 @@+/**+ * GST-2468: a label-only maintenance page write (`managed_maintenance_page` with `label_edit`) changes the page's+ * privacy labels and nothing else, so its canonical file keeps its own bytes: only the label lines are removed, replaced+ * or appended to the frontmatter block (page-prepare.ts labelEditFile). The edit names `set` (a key and its plain+ * scalar value) and `remove` (keys), both among LABEL_KEYS. The editor reads no YAML: a label line it cannot edit+ * as one line (a block or multi-line value, a duplicate key, a value that needs quoting, no frontmatter block) returns+ * null, and the write refuses instead of re-rendering the file.+ */+import { opError } from '../ops/contract.ts';++/** The frontmatter keys a label edit may touch: visibility and the privacy aliases (search/private-visibility.ts PRIVACY_ALIASES). */+export const LABEL_KEYS: readonly string[] = ['visibility', 'access', 'confidentiality'];+const PLAIN_VALUE = /^[A-Za-z][A-Za-z0-9_-]*$/;+/** A value a label edit can write as one unquoted line. */+export const isPlainLabelValue = (value: unknown): value is string => typeof value === 'string' && PLAIN_VALUE.test(value);++export interface LabelEdit { set: Record<string, string>; remove: string[] }++/** The intent's label_edit, validated, or undefined when the intent carries none. */+export function readLabelEdit(value: unknown): LabelEdit | undefined {+ if (value === undefined || value === null) return undefined;+ const edit = value as { set?: unknown; remove?: unknown };+ const set = edit.set ?? {}, remove = edit.remove ?? [];+ const valid = typeof set === 'object' && set !== null && !Array.isArray(set) && Array.isArray(remove)+ && Object.entries(set).every(([key, v]) => LABEL_KEYS.includes(key) && isPlainLabelValue(v))+ && remove.every(key => typeof key === 'string' && LABEL_KEYS.includes(key) && !Object.hasOwn(set, key));+ if (!valid) throw opError('invalid_params', 'The label edit names a key or value a label edit cannot write.',+ `A label edit sets or removes only ${LABEL_KEYS.join(', ')}, each value a plain word. This is a gbrain planning defect: report it with the gbrain version; nothing was written.`);+ return { set: { ...set as Record<string, string> }, remove: [...new Set(remove as string[])] };+}++/** frontmatter with the edit applied (key order kept, a new key last). */+export function labelEditedFrontmatter(frontmatter: Record<string, unknown>, edit: LabelEdit): Record<string, unknown> {+ return Object.assign(Object.fromEntries(Object.entries(frontmatter).filter(([key]) => !edit.remove.includes(key))), edit.set);+}++const keyLine = (key: string) => new RegExp(`^${key}[ \t]*:(?:[ \t]|\r?\n|$)`);++/**+ * text with the edit applied to its frontmatter lines, and the file's head through the closing --- line, or null when+ * a label line cannot be edited as one line. Every other byte is kept: key order, other keys, comments, line endings, the body.+ */+export function spliceLabelLines(text: string, edit: LabelEdit): { text: string; head: string } | null {+ const bom = text.startsWith('\uFEFF') ? '\uFEFF' : '';+ const lines = text.slice(bom.length).split(/(?<=\n)/);+ if (!/^---[ \t]*\r?\n$/.test(lines[0] ?? '')) return null;+ const close = lines.findIndex((line, index) => index > 0 && /^---[ \t]*(?:\r?\n)?$/.test(line));+ if (close < 0) return null;+ const block = lines.slice(1, close);+ for (const key of [...edit.remove, ...Object.keys(edit.set)]) {+ const at = block.flatMap((line, index) => keyLine(key).test(line) ? [index] : []);+ if (at.length > 1) return null;+ if (!at.length) continue;+ const value = block[at[0]!]!.slice(block[at[0]!]!.indexOf(':') + 1).trim();+ if (!value || /^[|>&*!]/.test(value) || /^[ \t]+\S/.test(block[at[0]! + 1] ?? '')) return null;+ }+ const kept = block.filter(line => !edit.remove.some(key => keyLine(key).test(line)));+ const eol = lines[0]!.endsWith('\r\n') ? '\r\n' : '\n';+ for (const [key, value] of Object.entries(edit.set)) {+ const at = kept.findIndex(line => keyLine(key).test(line));+ if (at >= 0) kept[at] = `${key}: ${value}${kept[at]!.endsWith('\r\n') ? '\r\n' : '\n'}`;+ else kept.push(`${key}: ${value}${eol}`);+ }+ const head = bom + lines[0] + kept.join('') + lines[close];+ return { text: head + lines.slice(close + 1).join(''), head };+}diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 40089b1973..afb6489e6e 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -91,6 +91,7 @@ import { parseFenceRepairReceipt } from '../fence-repair/receipt.ts';import { fenceRepairCommit } from './effect-model.ts';import { withoutSafetyAssessments } from './reconcile-safety.ts';import { POLICY_KEYS } from './reconcile-additive.ts';+import { readLabelEdit, spliceLabelLines, type LabelEdit } from './label-edit.ts';import { protectedReconcileKey } from './reconcile-merge.ts';import { PROTECTED_FRONTMATTER_KEYS } from '../frontmatter-recovery.ts';import { preparePagePurge, purgePageInTransaction, type PreparedPagePurge } from './page-purge.ts';@@ -269,6 +270,26 @@ async function frontmatterDriftWrite(engine: BrainEngine, slug: string, fileTextreturn digest(check.frontmatter) === digest(file.frontmatter) && check.title === file.title && check.type === incoming.type && digest(check.tags) === digest(file.tags)&& check.compiled_truth === incoming.compiled_truth && (check.timeline ?? '') === (incoming.timeline ?? '') ? spliced : null;}+/**+ * GST-2468: the file a label-only maintenance write publishes over a canonical file that holds the page (fileMatchesSnapshot):+ * the file's own bytes with only its label lines edited (label-edit.ts spliceLabelLines), keeping its body when it reads as+ * the write's body, else its head over the write's body (a fact row's visibility cell in the fence). Either must read back+ * as `content`, the file the write would otherwise render; a label line that cannot be edited as a line refuses, so the+ * file is never re-rendered under a label edit.+ */+function labelEditFile(slug: string, before: Buffer | FileBytes, content: string, edit: LabelEdit, snapshot: PageSnapshot, activePack?: ParseOpts['activePack']): string {+ const read = (text: string, file: boolean) => {+ const parsed = parseMarkdown(text, slug, { activePack });+ return digest(canonical({ ...parsed, frontmatter: withoutSafetyAssessments(parsed.frontmatter), type: file ? importedFileType(parsed, snapshot.page, false) : parsed.type }, parsed.tags));+ };+ const spliced = before instanceof Buffer ? spliceLabelLines(before.toString('utf8'), edit) : null;+ const contentHead = /^\uFEFF?---\r?\n[\s\S]*?\r?\n---[ \t]*\r?\n/.exec(content);+ const expected = read(content, false);+ const fits = spliced ? [spliced.text, ...(contentHead ? [spliced.head + content.slice(contentHead[0].length)] : [])].find(text => read(text, true) === expected) : undefined;+ if (fits !== undefined) return fits;+ throw opError('invalid_params', 'The label edit cannot be made to the page\'s file line by line.',+ `Nothing was written for ${slug}: its file cannot take the change without being re-rendered (a label key with a block or multi-line value or a duplicate key, no frontmatter block, a body that no longer reads as the page once its facts row is changed, or a file too large to edit in memory), so the label-only write refuses. Make the change in the file by hand, commit it, and run gbrain sync for the source.`);+}/*** GST-1601: whether a local edit changes what an adoption must never take without a person: the title, the type, or a* policy, protected, access, lineage or trust-lowering frontmatter key (the keys frontmatterDriftWrite never splices).@@ -341,7 +362,9 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ/** Runs between the pieces of a segmented page's file comparison (an effect's claim renewal). */between?: () => Promise<void>;/** #7436: the preparation's clock, so its stamp says `waiting_on=git` while a Git check runs. */- clock?: ClaimPhaseClock } = {}): Promise<PreparedMutation['file']> {+ clock?: ClaimPhaseClock;+ /** GST-2468: a label-only maintenance write edits only the label lines of the file it matches (labelEditFile). */+ labelEdit?: LabelEdit } = {}): Promise<PreparedMutation['file']> {if (!row.worktree_id) return undefined;// An in-memory canonical file over the 25 MiB push-scan cap is refused (only a page over the 24 MiB single-string// ceiling renders one). That page's file is streamed instead (restore_page of a page whose body was not read back,@@ -500,6 +523,9 @@ async function compareFileTarget(engine: BrainEngine, row: Parameters<typeof pre{ argv: ['gbrain', 'sources', 'reconcile', row.source_id, row.slug, '--brain', 'host', '--preview', ...adopt] }) }),adopt.length || options.deleting === true ? {} : { localEdit: { root, path } });}+ if (matches && options.labelEdit && typeof content === 'string') {+ return { path, root, content: labelEditFile(row.slug, before, content, options.labelEdit, snapshot, options.activePack), expectedBeforeHash: beforeHash() };+ }} else if (before && !snapshot && content !== null && beforeHash() !== fileContentHash(content)&& !(options.capture && beforeHash() === options.capture.hash)) {throw await heldFileRefusal(engine, row, root, path, 'occupied', options.remote === true)@@ -1085,7 +1111,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wriasync () => noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : preparePageAdvisories(engine,row,ready.parsedPage,snapshot),async () => !noop && !targetDeleted && autoLinkedPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)? prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id,options.coordinated === true) : undefined,- () => prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile, activePack, remote: row.authority.remote, newPageIgnoredDatabaseOnly: true, clock }),+ () => prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile, activePack, remote: row.authority.remote, newPageIgnoredDatabaseOnly: true, clock, labelEdit: row.operation === 'submit_job' && p.kind === 'managed_maintenance_page' ? readLabelEdit(p.label_edit) : undefined }),// Always-loaded core tier: owner-only marking, brain-wide budget, remote-edit policy (core-guard.ts).async () => noop ? null : prepareCoreGuard(engine, { row, snapshot, incoming: targetDeleted ? null : ready.parsedPage }),]) as [Awaited<ReturnType<typeof prepareCanonicalProjections>> | undefined, Record<string, unknown>,diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex f55fd99edc..c673f91b0e 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -38,6 +38,7 @@ import { auditConflictsCommand, FILE_DRIFT_MESSAGE, liveFileDrift } from './drifimport { lowerToDerivedTier, readDerivationDeclaration, recordTaintEdges, type DerivationDeclaration } from '../trust/taint.ts';import { derivationWriteTrust, recordAgentPageLowering, storedPageTier } from '../trust/page-write.ts';import { sameInstantTies } from '../facts/claim-ties.ts';+import type { LabelEdit } from './label-edit.ts';import { factPreimages, recordConsolidationGeneration } from '../generations/adapters/fact-rows.ts';export interface MaintenanceAuthority {@@ -238,16 +239,19 @@ export function maintenanceGhostRefusal(sourceId: string, slug: string): Operati/** #5523: a Life Chronicle timeline row projected onto the depth page in the same publication. */export interface MaintenanceEventProjection { depth_slug: string; date: string; summary: string; }-/** `keepTrust`: the edit authors nothing (it only removes privacy labels), so the page keeps its stored trust tier (withTrustKeep). */+/**+ * `keepTrust`: the edit authors nothing (it only changes privacy labels), so the page keeps its stored trust tier (withTrustKeep).+ * `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 };+ eventProjection?: MaintenanceEventProjection; derivation?: DerivationDeclaration; keepTrust?: true; labelEdit?: LabelEdit };/** 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 } : {};+ const keep = { ...(options.keepTrust ? { keep_trust: true } : {}), ...(options.labelEdit ? { label_edit: options.labelEdit } : {}) };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 }) };diff --git a/src/core/repair/label-write.ts b/src/core/repair/label-write.tsnew file mode 100644index 0000000000..dd9d7f7728--- /dev/null+++ b/src/core/repair/label-write.ts@@ -0,0 +1,64 @@+/**+ * GST-2468: the one door for an operator repair's label-only page write (`gbrain repair private-labels`, `gbrain repair+ * visibility`). The write authors nothing, so the page keeps its stored trust tier and files no `lower_page` proposal,+ * and its canonical file changes only in the label lines (persistence/label-edit.ts):+ * - a managed brain publishes it through the maintenance door with keep_trust and the label edit (the Git door on a+ * repo source; a repo-less managed source writes the database only);+ * - a brain without managed persistence imports it in a maintenance transaction under the page lock and withTrustKeep,+ * database only (the default keyless install has no file to keep). A page there whose file sits in its source's+ * checkout is held by the caller (`filesInCheckout`): the next sync or re-import would undo a database-only edit.+ * An ordinary put_page, local or remote, stays an agent content write (trust/channel.ts): it is never used here.+ */+import type { BrainEngine } from '../engine.ts';+import { opError, type OperationContext } from '../ops/contract.ts';+import { importFromContent } from '../import-file.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';+import { withTrustKeep } from '../persistence/context.ts';+import type { LabelEdit } from '../persistence/label-edit.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';+import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';++const bounded = { timeoutMs: 120_000 };++/**+ * GST-2128 item 1: on a brain without managed persistence, the pages with a recorded file (`source_path`) in a source that+ * has a checkout (`local_path`, or `sync.repo_path` for the default source), by page id. A label write there writes only the+ * database, so the file would put the label back at the next sync or re-import. The core reads no filesystem+ * (GBRA-248), so a recorded file that is gone still counts, which only holds a page. Empty on a managed brain.+ */+export async function filesInCheckout(engine: BrainEngine, pageIds: number[]): Promise<Map<number, string>> {+ if (!pageIds.length || await managedPersistenceEnabled(engine)) return new Map();+ const rows = await engine.executeRaw<{ id: number; source_id: string; source_path: string; local_path: string | null }>(`SELECT p.id, p.source_id, p.source_path, s.local_path+ FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($1::integer[]) AND p.source_path IS NOT NULL`, [pageIds], bounded);+ const repoPath = rows.some(row => row.source_id === 'default' && !row.local_path) ? await engine.getConfig('sync.repo_path') : null;+ return new Map(rows.flatMap(row => (row.local_path ?? (row.source_id === 'default' ? repoPath : null)) ? [[Number(row.id), row.source_path] as const] : []));+}++/**+ * Unmanaged brains: the legacy maintenance import (an owner path: no write gate, no trust marker, gate markers kept),+ * under withTrustKeep so the page keeps its stored tier, bound to `revision` under the page lock. The revision it wrote;+ * null when the page moved. `preview` names the command whose preview lists the page again.+ */+export async function importAtRevision(engine: BrainEngine, page: { source_id: string; slug: string }, revision: string, content: string, embed: boolean,+ preview: string): Promise<string | null> {+ return maintenanceTransaction(engine, async tx => {+ await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);+ if ((await tx.readPageSnapshot(page.slug, { sourceId: page.source_id }))?.revision !== revision) return null;+ const result = await withTrustKeep(tx, ['pages'], () => importFromContent(tx, page.slug, content, { sourceId: page.source_id, noEmbed: !embed, preserveGateMarkers: true }));+ if (result.status === 'error') throw opError('invalid_params', `${page.source_id}:${page.slug} was not written: ${result.error ?? 'the import refused it'}`,+ `Preview ${preview} again; the page is listed with its current state.`);+ return (await tx.readPageSnapshot(page.slug, { sourceId: page.source_id }))?.revision ?? null;+ });+}++/**+ * One label-only page write at `revision`: the maintenance door on a managed brain (`authority`, from maintenancePreflight),+ * the import under the page lock otherwise. The revision it wrote; null when the page moved before an unmanaged import.+ */+export async function writeLabelPage(ctx: OperationContext, page: { source_id: string; slug: string }, write: { revision: string; content: string; edit: LabelEdit;+ requestId: string; embed: boolean; preview: string }, authority?: MaintenanceAuthority | null): Promise<string | null> {+ const door = authority === undefined ? await maintenancePreflight(ctx.engine, page.source_id) : authority;+ if (!door) return importAtRevision(ctx.engine, page, write.revision, write.content, write.embed, write.preview);+ await publishMaintenancePage(ctx.engine, door, page.slug, write.content, { expectedRevision: write.revision, requestId: write.requestId, keepTrust: true, labelEdit: write.edit });+ return (await ctx.engine.readPageSnapshot(page.slug, { sourceId: page.source_id }))?.revision ?? null;+}diff --git a/src/core/repair/private-labels.ts b/src/core/repair/private-labels.tsindex 15a78eae74..0edaad0cd7 100644--- a/src/core/repair/private-labels.ts+++ b/src/core/repair/private-labels.ts@@ -22,12 +22,12 @@* (class, page id) order under a hash, with every category's count over the scope before* and after the window; --apply --expect <hash> applies exactly that window, re-deciding* each page against its live revision and labels first. A bare --apply is refused. Each- * item is one revision-bound maintenance write, so it keeps the page's trust tier (no- * trust_tier marker, no lower_page proposal) and its gate markers: a managed brain- * publishes it through the maintenance door (the Git door on a repo source) with keep_trust,- * an unmanaged one imports it in a maintenance transaction under the page lock, also- * keeping the stored tier. readable_by and folder- * rules are left as they are.+ * item is one revision-bound label-only write (repair/label-write.ts), so it keeps the page's+ * trust tier (no trust_tier marker, no lower_page proposal) and its gate markers: a managed+ * brain publishes it through the maintenance door (the Git door on a repo source) with+ * keep_trust and its label edit, so the page's file changes only in the removed or re-added+ * label lines (GST-2468); an unmanaged one imports it in a maintenance transaction under the+ * page lock, also keeping the stored tier. readable_by and folder rules are left as they are.** The preview also counts, per window and by category, the pages whose only privacy is a listed* page's label and that the window would expose with it (`dependents`, never slugs): derived_from@@ -50,18 +50,16 @@import type { BrainEngine } from '../engine.ts';import { serializePageToMarkdown } from '../markdown.ts';import { opError, type OperationContext } from '../ops/contract.ts';-import { maintenanceTransaction } from '../persistence/attribution.ts';-import { withTrustKeep } from '../persistence/context.ts';-import { maintenancePreflight, publishMaintenancePage, publishMaintenancePages, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';+import { maintenancePreflight, publishMaintenancePages, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';+import { isPlainLabelValue, type LabelEdit } from '../persistence/label-edit.ts';+import { filesInCheckout, writeLabelPage } from './label-write.ts';import { getWriteRequest } from '../persistence/journal.ts';import { isTerminal } from '../persistence/model.ts';import { requestPrincipalForContext } from '../persistence/page-mutations.ts';import { digest } from '../persistence/digest.ts';import { modeRequiresSynopsis } from '../embedding-context.ts';import { chunkGenerationFilter } from '../search/safe-chunks.ts';-import { importFromContent } from '../import-file.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';-import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';import { PRIVACY_ALIASES, privacyAliasSql, privacyPartSql, privateSnapshotFilterFragment, readHonorAliases } from '../search/private-visibility.ts';import { asciiLower } from '../edge-whitespace.ts';@@ -294,36 +292,6 @@ async function windowDependents(engine: BrainEngine, window: Approved[]): Promisreturn { counts, exposes };}-/**- * GST-2128 item 1: on a brain without managed persistence, the pages with a recorded file (`source_path`) in a source that- * has a checkout (`local_path`, or `sync.repo_path` for the default source), by page id. This repair writes only the- * database there, so the file would put the label back at the next sync or re-import. The core reads no filesystem- * (GBRA-248), so a recorded file that is gone still counts, which only holds a page. Empty on a managed brain.- */-async function filesInCheckout(engine: BrainEngine, pageIds: number[]): Promise<Map<number, string>> {- if (!pageIds.length || await managedPersistenceEnabled(engine)) return new Map();- const rows = await engine.executeRaw<{ id: number; source_id: string; source_path: string; local_path: string | null }>(`SELECT p.id, p.source_id, p.source_path, s.local_path- FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($1::integer[]) AND p.source_path IS NOT NULL`, [pageIds], bounded);- const repoPath = rows.some(row => row.source_id === 'default' && !row.local_path) ? await engine.getConfig('sync.repo_path') : null;- return new Map(rows.flatMap(row => (row.local_path ?? (row.source_id === 'default' ? repoPath : null)) ? [[Number(row.id), row.source_path] as const] : []));-}--/**- * Unmanaged brains: the legacy maintenance import (an owner path: no write gate, no trust marker, gate markers kept),- * under withTrustKeep so the page keeps its stored tier, bound to the previewed revision under the page lock. The revision- * it wrote; null when the page moved.- */-async function importAtRevision(engine: BrainEngine, entry: Approved, revision: string, content: string, embed: boolean): Promise<string | null> {- return maintenanceTransaction(engine, async tx => {- await tx.lockPageKeys([{ sourceId: entry.source_id, slug: entry.slug }]);- if ((await tx.readPageSnapshot(entry.slug, { sourceId: entry.source_id }))?.revision !== revision) return null;- const result = await withTrustKeep(tx, ['pages'], () => importFromContent(tx, entry.slug, content, { sourceId: entry.source_id, noEmbed: !embed, preserveGateMarkers: true }));- if (result.status === 'error') throw opError('invalid_params', `${entry.source_id}:${entry.slug} was not written: ${result.error ?? 'the import refused it'}`,- 'Preview gbrain repair private-labels again; the page is listed with its current state.');- return (await tx.readPageSnapshot(entry.slug, { sourceId: entry.source_id }))?.revision ?? null;- });-}-/** GBRA-443: lines this run appended to its ledger, by phase (the apply result's ledger_rows_written and ledger_rows), kept on the ledger it was handed. */type CountedLedger = PrivateLabelsLedger & { rows?: { intent: number; committed: number } };function recordLine(ledger: CountedLedger, line: LedgerLine & { phase: 'intent' | 'committed' }): void {@@ -382,6 +350,9 @@ async function prepareWrite(ctx: OperationContext, item: LabelsItem): Promise<Renext = Object.fromEntries(Object.entries(frontmatter).filter(([key]) => !Object.hasOwn(labels, key)));} else {if (Object.keys(labels).some(key => Object.hasOwn(frontmatter, key))) return { outcome: CHANGED };+ if (!Object.values(labels).every(isPlainLabelValue)) {+ return { outcome: { applied: false, outcome: 'label_not_plain', reason: `${describeLabels(labels)} cannot be written back as plain label lines; add it to the page's file by hand, commit it, then run: gbrain sync --source ${entry.source_id}` } };+ }next = { ...frontmatter, ...labels };}const file = (await filesInCheckout(ctx.engine, [entry.page_id])).get(entry.page_id);@@ -423,17 +394,16 @@ function committedOutcome(item: LabelsItem, line: LedgerLine, written: string |const writtenRevision = async (engine: BrainEngine, entry: Approved) => (await engine.readPageSnapshot(entry.slug, { sourceId: entry.source_id }))?.revision ?? null;-/** One item's page write after its intent line: the maintenance door on a managed brain, the legacy import under the page lock otherwise. */+/** The label edit an item makes: a clear removes its recorded keys, a restore sets them back. */+const labelEditOf = (entry: Approved): LabelEdit => entry.mode === 'clear' ? { set: {}, remove: Object.keys(entry.labels) }+ : { set: entry.labels as Record<string, string>, remove: [] };++/** One item's page write after its intent line (repair/label-write.ts): the maintenance door on a managed brain, the legacy import under the page lock otherwise. */async function writeOne(ctx: OperationContext, item: LabelsItem, ready: Ready, line: LedgerLine, authority: MaintenanceAuthority | null, embed: boolean): Promise<RepairItemOutcome> {recordIntent(item, line);- let written: string | null;- if (authority) {- await publishMaintenancePage(ctx.engine, authority, item.entry.slug, ready.content, { expectedRevision: ready.revision, requestId: line.request_id, keepTrust: true });- written = await writtenRevision(ctx.engine, item.entry);- } else {- written = await importAtRevision(ctx.engine, item.entry, ready.revision, ready.content, embed);- if (!written) return CHANGED;- }+ const written = await writeLabelPage(ctx, item.entry, { revision: ready.revision, content: ready.content, edit: labelEditOf(item.entry), requestId: line.request_id, embed,+ preview: 'gbrain repair private-labels' }, authority);+ if (!written && !authority) return CHANGED;return committedOutcome(item, line, written);}@@ -578,7 +548,7 @@ export const privateLabelsRepair: RepairHandler = {}if (!admitted.length) continue;const published = await publishMaintenancePages(ctx.engine, authority, admitted.map(({ index, line }) => ({ slug: items[index]!.entry.slug, content: ready[index]!.content,- expectedRevision: ready[index]!.revision, requestId: line.request_id, keepTrust: true as const })), { batch: digest(['private-labels-batch-v1', opts.expect ?? opts.runId ?? '', sourceId]) });+ expectedRevision: ready[index]!.revision, requestId: line.request_id, keepTrust: true as const, labelEdit: labelEditOf(items[index]!.entry) })), { batch: digest(['private-labels-batch-v1', opts.expect ?? opts.runId ?? '', sourceId]) });wrote = true;for (const [position, { index, line }] of admitted.entries()) {const settled = published[position]!;diff --git a/src/core/repair/visibility.ts b/src/core/repair/visibility.tsindex d980c81358..0e3bdd3f81 100644--- a/src/core/repair/visibility.ts+++ b/src/core/repair/visibility.ts@@ -28,10 +28,14 @@* class past a full window is not read; apply the window and preview again for the next one. Each* plan statement runs under PLAN_STATEMENT_MS; a class that overruns it is reported and skipped.* Progress goes to stderr. A bare `--apply` (`--all`, the remediation plan) applies every class.+ *+ * `--slug <page>` (repeatable, GST-2468) replaces the classes with the named pages (class `pages`): each is made+ * private, tighten-only, preview-bound (a bare `--apply` refuses). It is the operator's single-page label change.+ * Every item writes through the label-only door (repair/label-write.ts): the page keeps its trust tier, files no+ * lower_page proposal and its file changes only on the visibility line (a fact item: its fence row).*/import type { BrainEngine } from '../engine.ts';import { serializePageToMarkdown } from '../markdown.ts';-import { submitPageMutation } from '../persistence/page-mutations.ts';import { derivationPrivateSql, effectiveVisibility, folderRestrictedSql, privacyAliasSql, privateSnapshotFilterFragment, strictestVisibility, type Visibility } from '../search/private-visibility.ts';import { strikeFenceRow } from '../facts/forget.ts';import { opError } from '../ops/contract.ts';@@ -43,7 +47,10 @@ import type { WriteRequest } from '../persistence/model.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';-import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairPlan, type RepairPlanOptions, type RepairScope, type RepairCursor } from './core.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope, type RepairCursor } from './core.ts';+import { filesInCheckout, writeLabelPage } from './label-write.ts';+import type { LabelEdit } from '../persistence/label-edit.ts';+import type { PageSnapshot } from '../page-state/types.ts';import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';import { createProgress, startHeartbeat } from '../progress.ts';import { cliOptsToProgressOptions, getCliOptions } from '../cli-options.ts';@@ -54,7 +61,7 @@ interface InputRow { concept_id: number; atom_id: number; linked: boolean }interface EventRow extends DerivedRow { origin_id: number | null; origin_type: string | null; origin_frontmatter: Record<string, unknown> | null; origin_folder_restricted: boolean }-export interface VisibilityChange { id: number; source_id: string; slug: string; phase: 0 | 1 | 2 | 3; from: string | null; to: Visibility }+export interface VisibilityChange { id: number; source_id: string; slug: string; phase: 0 | 1 | 2 | 3 | 5; from: string | null; to: Visibility }/** Tighten-only: never loosen an explicit value; stamp a missing one. */function tightened(current: string | null, target: Visibility): Visibility | null {@@ -156,6 +163,21 @@ async function planAliases(engine: BrainEngine, sourceIds: string[], only?: numbreturn { changes: rows.map(page => ({ id: Number(page.id), source_id: page.source_id, slug: page.slug, phase: 3 as const, from: null, to: 'private' as const })), rows, residuals: {} };}+/**+ * GST-2468: the pages an operator named with --slug, made private (tighten-only: an explicit private stays). The+ * operator's own single-page label change, which a put_page would rate as an agent edit (trust/channel.ts).+ */+async function planNamed(engine: BrainEngine, sourceIds: string[], slugs: string[]) {+ const rows = await engine.executeRaw<DerivedRow>(`SELECT p.id,p.source_id,p.slug,p.type,p.frontmatter->>'visibility' AS visibility,length(p.compiled_truth) AS chars+ FROM pages p WHERE p.deleted_at IS NULL AND p.source_id=ANY($1::text[]) AND p.slug=ANY($2::text[]) ORDER BY p.id`, [sourceIds, slugs], bounded);+ const changes = rows.flatMap(page => {+ const next = tightened(page.visibility, 'private');+ return next ? [{ id: Number(page.id), source_id: page.source_id, slug: page.slug, phase: 5 as const, from: page.visibility, to: next }] : [];+ });+ const found = new Set(rows.map(row => row.slug));+ return { changes, rows, residuals: { named_already_private: rows.length - changes.length, named_not_found: slugs.filter(slug => !found.has(slug)).length } };+}+/*** Every atom / synthesized concept / chronicle event / alias-only page in scope* whose stored visibility should change. `only` narrows the plan to one page@@ -234,11 +256,11 @@ export async function prepareFactVisibilityTighten(engine: BrainEngine, row: Wri/*** One fact item: a fenced row gets `private` in its page's `## Facts` fence by a- * revision-bound put_page (the projection then stores it private); a+ * revision-bound label write (labelWrite; the projection then stores it private); a* database-only row is updated in place (a database-only maintenance request* on a managed brain). A page stored in segments is left for the owner.*/-async function applyFactItem(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem, factId: number): Promise<boolean> {+async function applyFactItem(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem, factId: number): Promise<boolean | RepairItemOutcome> {const [fact] = await worldFactsFromPrivateSources(ctx.engine, [item.source_id], [factId]);if (!fact) return false;if (fact.row_num === null) {@@ -257,28 +279,45 @@ async function applyFactItem(ctx: Parameters<RepairHandler['apply']>[0], item: Rif (!snapshot || isSegmentedPage(snapshot.page)) return false;const body = strikeFenceRow(snapshot.page.compiled_truth ?? '', fact.row_num, row => ({ ...row, visibility: 'private' }));if (body === null) return false;- await submitPageMutation(ctx, { operation: 'put_page', params: { slug: snapshot.page.slug, source_id: item.source_id,- content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body }, snapshot.tags), expected_revision: snapshot.revision,- request_id: await repairRequestId(ctx, 'visibility', item, snapshot.revision) } });+ const held = await labelWrite(ctx, item, snapshot, serializePageToMarkdown({ ...snapshot.page, compiled_truth: body }, snapshot.tags), { set: {}, remove: [] });+ if (held) return held;const [stored] = await ctx.engine.executeRaw<{ visibility: string }>('SELECT visibility FROM facts WHERE id=$1', [factId]);return stored?.visibility === 'private';}-export type VisibilityClass = 'facts' | 'events' | 'aliases' | 'lineage';+/**+ * GST-2468: one item's page write is a label-only maintenance write (repair/label-write.ts): it keeps the page's trust+ * tier, files no lower_page proposal and changes only the label lines of the page's file (a fact item: its fence row).+ * Null once written; the held outcome on a brain without managed persistence whose page has a file in its source's+ * checkout (the database-only write would be undone from the file), or for a page stored in segments.+ */+async function labelWrite(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem, snapshot: PageSnapshot, content: string, edit: LabelEdit): Promise<RepairItemOutcome | null> {+ if (isSegmentedPage(snapshot.page)) return { applied: false, outcome: 'segmented_page', reason: 'The page body is stored in segments; edit it by hand on the brain host.' };+ const file = (await filesInCheckout(ctx.engine, [Number(snapshot.page.id)])).get(Number(snapshot.page.id));+ if (file) return { applied: false, outcome: 'file_backed', detail: { path: file },+ reason: `${item.source_id}:${snapshot.page.slug} has a file in its source's checkout (${file}); on a brain without managed persistence this repair writes only the database, `+ + `so the next sync or re-import would undo it from the file. Make the change in that file (${edit.set.visibility ? `add visibility: ${edit.set.visibility}` : 'its facts row visibility: private'}), commit it, then run: gbrain sync --source ${item.source_id}` };+ await writeLabelPage(ctx, item, { revision: snapshot.revision, content, edit, requestId: await repairRequestId(ctx, 'visibility', item, snapshot.revision),+ embed: true, preview: 'gbrain repair visibility' });+ return null;+}++export type VisibilityClass = 'facts' | 'events' | 'aliases' | 'lineage' | 'pages';/** Plan order: what a remote caller can read first; only `lineage` reads concept-provenance links. */export const VISIBILITY_CLASSES: readonly VisibilityClass[] = ['facts', 'events', 'aliases', 'lineage'];/** Items one preview lists and one `--apply --expect` applies (`--limit` sets it, up to VISIBILITY_WINDOW_MAX). */export const VISIBILITY_WINDOW = 1000;export const VISIBILITY_WINDOW_MAX = 10_000;-const CLASS_OF_PHASE: Record<number, VisibilityClass> = { 0: 'lineage', 1: 'lineage', 2: 'events', 3: 'aliases', 4: 'facts' };+const CLASS_OF_PHASE: Record<number, VisibilityClass> = { 0: 'lineage', 1: 'lineage', 2: 'events', 3: 'aliases', 4: 'facts', 5: 'pages' };-/** One planned change; `target` is the page (phases 0-3) or fact (phase 4) it changes. */+/** One planned change; `target` is the page (phases 0-3, 5) or fact (phase 4) it changes. */interface VisibilityItem extends RepairItem { target: RepairCursor; hash?: string; last?: boolean }interface ApprovedVisibility { target: RepairCursor; source_id: string; slug: string; chars: number; action: string; change: { from: string | null; to: string }; selection: Selection }-interface Selection { source_ids: string[]; class: VisibilityClass | null }+/** `slugs` (GST-2468): the pages an operator named with --slug, the whole selection when present. */+interface Selection { source_ids: string[]; class: VisibilityClass | null; slugs?: string[] }const visibilityPreviewCommand = (scope: RepairScope, selection: Selection, sourceFlag?: boolean) =>- `gbrain repair visibility${sourceFlag && scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}${selection.class ? ` --class ${selection.class}` : ''}`;+ `gbrain repair visibility${sourceFlag && scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}${selection.class ? ` --class ${selection.class}` : ''}${(selection.slugs ?? []).map(slug => ` --slug ${slug}`).join('')}`;function selectedClass(opts?: RepairPlanOptions): VisibilityClass | null {const value = opts?.driftClass;@@ -291,7 +330,7 @@ function selectedClass(opts?: RepairPlanOptions): VisibilityClass | null {const isStatementTimeout = (error: unknown) => (error as { code?: string } | null)?.code === '57014';/** Every planned change of one class, as items in their stable (phase, id) cursor order. */-async function planClass(engine: BrainEngine, sourceIds: string[], cls: VisibilityClass): Promise<{ items: VisibilityItem[]; residuals: Record<string, number> }> {+async function planClass(engine: BrainEngine, sourceIds: string[], cls: VisibilityClass, slugs?: string[]): Promise<{ items: VisibilityItem[]; residuals: Record<string, number> }> {const toItems = (part: { changes: VisibilityChange[]; rows: DerivedRow[] }) => {const chars = new Map(part.rows.map(row => [Number(row.id), Number(row.chars)]));return part.changes.map(change => ({ cursor: { phase: change.phase, id: change.id }, target: { phase: change.phase, id: change.id }, source_id: change.source_id,@@ -305,20 +344,26 @@ async function planClass(engine: BrainEngine, sourceIds: string[], cls: Visibiliaction: `fact ${fact.id} visibility world -> private${fact.readable ? ' (remotely readable now)' : ''}`, change: { from: 'world', to: 'private' } }));return { items, residuals: { world_facts_remotely_readable: facts.filter(fact => fact.readable).length } };}- const part = cls === 'events' ? await planEvents(engine, sourceIds) : cls === 'aliases' ? await planAliases(engine, sourceIds) : await planLineage(engine, sourceIds);+ const part = cls === 'pages' ? await planNamed(engine, sourceIds, slugs ?? []) : cls === 'events' ? await planEvents(engine, sourceIds) : cls === 'aliases' ? await planAliases(engine, sourceIds) : await planLineage(engine, sourceIds);return { items: toItems(part), residuals: part.residuals };}export const visibilityRepair: RepairHandler = {kind: 'visibility',async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null, opts?: RepairPlanOptions): Promise<RepairPlan> {- const selection: Selection = { source_ids: scope.source_ids, class: selectedClass(opts) };- const classes = selection.class ? [selection.class] : VISIBILITY_CLASSES;+ const named = [...new Set(opts?.slugs ?? [])].sort();+ if (named.length && opts?.driftClass !== undefined) throw opError('invalid_params', 'gbrain repair visibility takes --slug or --class, not both.',+ 'Name pages with --slug to make exactly them private, or preview a class with --class.');+ const selection: Selection = { source_ids: scope.source_ids, class: selectedClass(opts), ...(named.length ? { slugs: named } : {}) };+ const classes: readonly VisibilityClass[] = named.length ? ['pages'] : selection.class ? [selection.class] : VISIBILITY_CLASSES;const command = visibilityPreviewCommand(scope, selection, true);+ if (named.length && opts?.apply && !opts.expect) throw opError('invalid_params', 'gbrain repair visibility --slug applies only the set a preview printed.',+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`);if (opts?.apply && opts.expect) {const approved = await loadApprovedSet<ApprovedVisibility>(engine, { command: 'visibility', hash: opts.expect, previewCommand: command,emptyHash: async () => previewHash(hashParts(scope, selection, [])) });- if (approved.items.some(entry => (entry.selection.class ?? null) !== selection.class || JSON.stringify(entry.selection.source_ids) !== JSON.stringify(selection.source_ids))) {+ if (approved.items.some(entry => (entry.selection.class ?? null) !== selection.class || JSON.stringify(entry.selection.source_ids) !== JSON.stringify(selection.source_ids)+ || JSON.stringify(entry.selection.slugs ?? []) !== JSON.stringify(named))) {throw previewChangedError(opts.expect, command);}const items: VisibilityItem[] = approved.items.map(({ selection: _selection, ...entry }, index) => ({ ...entry, cursor: { phase: 0, id: index },@@ -327,7 +372,7 @@ export const visibilityRepair: RepairHandler = {}if (opts?.apply) {// A bare --apply (--all, the remediation plan) applies every planned change in (phase, id) order, resumable by that cursor.- const planned = await Promise.all(classes.map(cls => planClass(engine, scope.source_ids, cls)));+ const planned = await Promise.all(classes.map(cls => planClass(engine, scope.source_ids, cls, named)));return { items: planned.flatMap(part => part.items).sort((a, b) => a.cursor.phase - b.cursor.phase || a.cursor.id - b.cursor.id).filter(item => afterCursor(item.cursor, after)), residuals: Object.assign({}, ...planned.map(part => part.residuals)) };}@@ -346,7 +391,7 @@ export const visibilityRepair: RepairHandler = {progress?.heartbeat(`reading ${cls}`);const stopHeartbeat = progress ? startHeartbeat(progress, `still reading ${cls}`, 10_000) : () => {};let planned: Awaited<ReturnType<typeof planClass>>;- try { planned = await planClass(engine, scope.source_ids, cls); } catch (error) {+ try { planned = await planClass(engine, scope.source_ids, cls, named); } catch (error) {if (!isStatementTimeout(error)) throw error;timedOut.push(cls); progress?.heartbeat(`${cls}: over the ${PLAN_STATEMENT_MS} ms statement bound, skipped`); progress?.tick(1); continue;} finally { stopHeartbeat(); }@@ -383,14 +428,12 @@ export const visibilityRepair: RepairHandler = {if (target.phase === 4) return await applyFactItem(ctx, item, target.id);const snapshot = await ctx.engine.readPageSnapshot(item.slug, { sourceId: item.source_id });if (!snapshot || !item.change || Number(snapshot.page.id) !== target.id) return false;- // Re-decide against current origins and inputs; a changed decision waits for the next run.- const fresh = (await planVisibilityRepair(ctx.engine, [item.source_id], target.id)).changes.find(c => c.id === target.id);+ // Re-decide against current origins and inputs (a named page: its current visibility); a changed decision waits for the next run.+ const fresh = (target.phase === 5 ? await planNamed(ctx.engine, [item.source_id], [item.slug]) : await planVisibilityRepair(ctx.engine, [item.source_id], target.id))+ .changes.find(c => c.id === target.id);if (!fresh || fresh.from !== item.change.from || fresh.to !== item.change.to) return false;const page = { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, visibility: item.change.to } };- await submitPageMutation(ctx, { operation: 'put_page', params: { slug: item.slug, source_id: item.source_id,- content: serializePageToMarkdown(page, snapshot.tags), expected_revision: snapshot.revision,- request_id: await repairRequestId(ctx, 'visibility', item, snapshot.revision) } });- return true;+ return await labelWrite(ctx, item, snapshot, serializePageToMarkdown(page, snapshot.tags), { set: { visibility: item.change.to }, remove: [] }) ?? true;} finally {if (item.last && item.hash) await clearApprovedSet(ctx.engine, { command: 'visibility', hash: item.hash });}diff --git a/src/core/trust/label-lowerings.ts b/src/core/trust/label-lowerings.tsnew file mode 100644index 0000000000..f997dcc0f1--- /dev/null+++ b/src/core/trust/label-lowerings.ts@@ -0,0 +1,97 @@+/**+ * GST-2468: `gbrain trust backfill --label-lowerings`, a read-only listing of the `lower_page` proposals whose lowering+ * write changed only a page's privacy labels (visibility, access, confidentiality) and the server's stamps (trust_tier,+ * source_kind, ingested_via, ingested_at): an operator's label change made through put_page, which rates as an agent+ * edit (trust/channel.ts), before label-only repairs had their own door (repair/label-write.ts). For each proposal it+ * compares the version the lowering replaced (`before_state.version_id`) with the page as it is now:+ * label_only only label and stamp keys differ, and at least one label key does;+ * content the body, timeline, title, type or another frontmatter key differs;+ * unreadable the replaced version is gone or stored in segments, or the page was purged.+ * Counts are grouped by proposer (agent_page_edit:put_page, derived_page:submit_job, ...) and class. It changes+ * nothing: raising a tier back is a trust decision (gbrain trust confirm or revert), never made here.+ */+import type { BrainEngine } from '../engine.ts';+import { LABEL_KEYS } from '../persistence/label-edit.ts';+import { digest } from '../persistence/digest.ts';+import { trustProposalRef } from './proposals.ts';+import { storedTrustTier, type TrustTier } from './tier.ts';++/** Keys the server stamps on a write (page-prepare.ts putProvenance, trust/page-write.ts stampPageTrustMarker). */+const STAMP_KEYS = ['trust_tier', 'source_kind', 'ingested_via', 'ingested_at'];++export type LabelLoweringClass = 'label_only' | 'content' | 'unreadable';+export interface LabelLowering {+ ref: string; source_id: string; slug: string | null; proposer: string; status: string; class: LabelLoweringClass;+ prior_tier: TrustTier | null; tier_now: TrustTier | null; proposed_at: string;+ /** label_only: each label key's value before and now (null when absent). */+ labels?: Record<string, { before: unknown; now: unknown }>;+ /** label_only: the stamp keys the write changed. */+ stamps?: string[];+ /** The page changed after the proposal last recorded its revision (a later write that filed no proposal). */+ changed_since?: true;+}+export interface LabelLoweringsReport {+ mode: 'preview'; source_id: string | null;+ counts: { lower_page: number; label_only: number; content: number; unreadable: number; by_proposer: Record<string, Record<LabelLoweringClass, number>> };+ items: LabelLowering[];+ note: string;+}++interface Row {+ id: number; source_id: string; proposer: string; status: string; created_at: Date | string; before_state: Record<string, unknown> | null; after_state: Record<string, unknown> | null;+ slug: string | null; tier: string | null; revision: string | null; frontmatter: Record<string, unknown> | null; v_id: number | null;+ v_frontmatter: Record<string, unknown> | null; readable: boolean; same_body: boolean;+}++const same = (a: unknown, b: unknown) => digest(a ?? null) === digest(b ?? null);++function classify(row: Row): Pick<LabelLowering, 'class' | 'labels' | 'stamps'> {+ if (row.slug === null || row.v_id === null || !row.readable) return { class: 'unreadable' };+ const before = row.v_frontmatter ?? {}, now = row.frontmatter ?? {};+ const changed = [...new Set([...Object.keys(before), ...Object.keys(now)])].filter(key => !same(before[key], now[key]));+ const labels = changed.filter(key => LABEL_KEYS.includes(key));+ if (!row.same_body || !labels.length || changed.some(key => !LABEL_KEYS.includes(key) && !STAMP_KEYS.includes(key))) return { class: 'content' };+ return { class: 'label_only', labels: Object.fromEntries(labels.map(key => [key, { before: before[key] ?? null, now: now[key] ?? null }])),+ stamps: changed.filter(key => STAMP_KEYS.includes(key)) };+}++export async function listLabelLowerings(engine: BrainEngine, opts: { sourceId?: string | null } = {}): Promise<LabelLoweringsReport> {+ const rows = await engine.executeRaw<Row>(`SELECT tp.id, tp.source_id, tp.proposer, tp.status, tp.created_at, tp.before_state, tp.after_state,+ p.slug, p.trust_tier::text AS tier, p.knowledge_revision::text AS revision, p.frontmatter, v.id AS v_id, v.frontmatter AS v_frontmatter,+ (v.compiled_truth IS NOT NULL AND p.compiled_truth IS NOT NULL) AS readable,+ COALESCE(v.compiled_truth = p.compiled_truth AND (v.timeline IS NULL OR v.timeline = COALESCE(p.timeline, ''))+ AND (v.title IS NULL OR v.title = p.title) AND (v.type IS NULL OR v.type::text = p.type::text), false) AS same_body+ FROM trust_proposals tp+ LEFT JOIN pages p ON p.id = tp.target_id+ LEFT JOIN page_versions v ON v.page_id = tp.target_id+ AND v.id = CASE WHEN tp.before_state->>'version_id' ~ '^[0-9]+$' THEN (tp.before_state->>'version_id')::integer END+ WHERE tp.action = 'lower_page' AND tp.target_table = 'pages' AND ($1::text IS NULL OR tp.source_id = $1)+ ORDER BY tp.id`, [opts.sourceId ?? null]);+ const counts: LabelLoweringsReport['counts'] = { lower_page: rows.length, label_only: 0, content: 0, unreadable: 0, by_proposer: {} };+ const items = rows.map((row): LabelLowering => {+ const verdict = classify(row);+ counts[verdict.class]++;+ (counts.by_proposer[row.proposer] ??= { label_only: 0, content: 0, unreadable: 0 })[verdict.class]++;+ const prior = row.before_state?.prior_tier;+ const recorded = row.after_state?.revision;+ return { ref: trustProposalRef(Number(row.id)), source_id: row.source_id, slug: row.slug ?? (typeof row.before_state?.slug === 'string' ? row.before_state.slug : null),+ proposer: row.proposer, status: row.status, ...verdict, prior_tier: typeof prior === 'string' ? storedTrustTier(prior) : null,+ tier_now: row.tier === null ? null : storedTrustTier(row.tier), proposed_at: new Date(row.created_at).toISOString(),+ ...(row.revision !== null && typeof recorded === 'string' && recorded !== row.revision ? { changed_since: true as const } : {}) };+ });+ return { mode: 'preview', source_id: opts.sourceId ?? null, counts, items,+ note: 'Read-only: nothing here changes a tier. Raising a page back is a trust decision for the owner (gbrain trust review).' };+}++export function renderLabelLowerings(report: LabelLoweringsReport): string {+ const { counts } = report;+ const lines = [`Lowered pages by proposal (${counts.lower_page} lower_page proposal(s)${report.source_id ? ` in ${report.source_id}` : ''}): `+ + `${counts.label_only} label-only, ${counts.content} content, ${counts.unreadable} unreadable.`];+ for (const [proposer, by] of Object.entries(counts.by_proposer)) lines.push(` ${proposer}: label-only ${by.label_only}, content ${by.content}, unreadable ${by.unreadable}`);+ for (const item of report.items.filter(entry => entry.class === 'label_only')) {+ const labels = Object.entries(item.labels ?? {}).map(([key, change]) => `${key} ${String(change.before ?? '(none)')} -> ${String(change.now ?? '(none)')}`).join(', ');+ lines.push(` ${item.ref} ${item.source_id}:${item.slug} (${item.status}, ${item.proposer}): ${labels}; tier ${item.prior_tier ?? '?'} -> ${item.tier_now ?? '?'}${item.changed_since ? ' (changed since)' : ''}`);+ }+ lines.push(` ${report.note}`);+ return lines.join('\n');+}diff --git a/test/label-only-repairs.test.ts b/test/label-only-repairs.test.tsnew file mode 100644index 0000000000..ad6b169049--- /dev/null+++ b/test/label-only-repairs.test.ts@@ -0,0 +1,212 @@+/**+ * GST-2468: an operator repair that only changes privacy labels is not an agent content write.+ *+ * 1. Protects: gbrain repair visibility (its alias class and the slug-bound --slug form an operator uses for one page) and+ * gbrain repair private-labels (clear and restore) keep the page's trust tier, file no lower_page proposal and change+ * only the label lines of the page's file, on a file whose frontmatter has a slug key, a source_kind the row's+ * provenance column does not hold, and keys in a non-canonical order. A plain local put_page that adds the same label+ * still lowers the page and files its proposal, as an agent edit does (trust/channel.ts). gbrain trust backfill+ * --label-lowerings lists each lower_page proposal as label-only or content, by proposer, and changes nothing.+ * 2. Fails when: a label repair lowers the tier, files a proposal, re-renders the file (a key dropped, a value or the key+ * order changed, a provenance stamp or trust marker added), or a plain put_page stops lowering.+ * 3. Real seams: the managed-brain harness (claimed Git worktree, managed sync, the maintenance door, the Git effect),+ * remote:false, the gbrain repair command entry; a repo-less brain with no managed persistence. PGLite, and Postgres+ * with DATABASE_URL.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { withCoordinatedWrite, withTrustBackfill } from '../src/core/persistence/context.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { listLabelLowerings, renderLabelLowerings } from '../src/core/trust/label-lowerings.ts';+import { durableGitRepo, git } from './helpers/git-publication.ts';+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const NL = String.fromCharCode(10);+const putPage = operations.find(op => op.name === 'put_page')!;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+/** Keys out of canonical order, a slug key, a source_kind the provenance column does not hold. */+const file = (slug: string, labels = '') => ['---', 'title: Example Page', 'slug: ' + slug, 'source_kind: email-example', 'type: note', ...(labels ? [labels] : []),+ 'owner_note: kept', 'tags:', ' - alpha', '---', '', 'Body line one of ' + slug + '.', '', 'Second paragraph.', ''].join(NL);+const withLine = (text: string, line: string) => text.replace(NL + 'tags:', NL + 'tags:').replace(NL + '---' + NL + NL, NL + line + NL + '---' + NL + NL);++async function capture(fn: () => Promise<void>): Promise<string> {+ let printed = '';+ const original = console.log;+ console.log = (...parts: unknown[]) => { printed += parts.map(String).join(' ') + NL; };+ try { await fn(); } finally { console.log = original; }+ return printed;+}+const repair = async (engine: BrainEngine, argv: string[]) => {+ const out = await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1' }, () => capture(() => runRepairCommand(engine, [...argv, '--json'])));+ _resetCliExitVerdictForTests();+ return JSON.parse(out).results[0];+};+const previewApply = async (engine: BrainEngine, argv: string[]) => {+ const preview = await repair(engine, argv);+ expect(preview.preview_hash).toBeString();+ const applied = await repair(engine, [...argv, '--apply', '--expect', preview.preview_hash]);+ expect(applied.failed).toEqual([]);+ return { preview, applied };+};+const page = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ tier: string; frontmatter: Record<string, unknown>; revision: string; source_kind: string | null }>(+ "SELECT trust_tier::text AS tier, frontmatter, knowledge_revision::text AS revision, source_kind FROM pages WHERE source_id='default' AND slug=$1 AND deleted_at IS NULL", [slug]))[0]!;+const proposals = async (engine: BrainEngine) => engine.executeRaw<{ proposer: string; status: string }>('SELECT proposer, status FROM trust_proposals ORDER BY id');++for (const backend of testBackends()) describe('[' + backend + '] label-only operator repairs on a managed git source', () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), 'archive/' + NL); durableGitRepo(root, ['.gitignore']); };+ async function seed(engine: BrainEngine, root: string, files: Record<string, string>) {+ mkdirSync(join(root, 'notes'), { recursive: true });+ for (const [slug, text] of Object.entries(files)) writeFileSync(join(root, slug + '.md'), text);+ git(root, 'add', '-A');+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'owner notes');+ await performManagedSync(engine, OPTS);+ await settleManagedGitEffects(engine);+ for (const slug of Object.keys(files)) expect((await page(engine, slug)).tier).toBe('operator_curated');+ }+ const onDisk = (root: string, slug: string) => readFileSync(join(root, slug + '.md'), 'utf8');++ test('repair visibility --slug: tier kept, no proposal, the file gains only the visibility line', () => managedBrain(async ({ engine, root }) => {+ const slug = 'notes/one-example';+ await seed(engine, root, { [slug]: file(slug) });+ expect((await page(engine, slug)).source_kind).toBeNull();+ const before = onDisk(root, slug);+ const { preview, applied } = await previewApply(engine, ['visibility', '--slug', slug]);+ expect(preview.listing).toEqual([{ item: 'default:' + slug, class: 'pages', detail: 'visibility (none) -> private' }]);+ expect(applied.applied).toBe(1);+ await settleManagedGitEffects(engine);+ const after = await page(engine, slug);+ expect(after.tier).toBe('operator_curated');+ expect(after.frontmatter.visibility).toBe('private');+ expect(after.frontmatter.source_kind).toBe('email-example');+ expect(await proposals(engine)).toEqual([]);+ expect(onDisk(root, slug)).toBe(withLine(before, 'visibility: private'));+ expect(git(root, 'status', '--porcelain', '--', slug + '.md').trim()).toBe('');+ expect(git(root, 'show', 'HEAD:' + slug + '.md')).toBe(withLine(before, 'visibility: private'));+ // Tighten-only: the page is private now, so a second preview names nothing.+ expect((await repair(engine, ['visibility', '--slug', slug])).listing).toEqual([]);+ }, { databaseUrl, setup }), 180_000);++ test('repair visibility --slug refuses a bare --apply and --class beside it', () => managedBrain(async ({ engine }) => {+ const refused = (argv: string[]) => repair(engine, argv).then(result => JSON.stringify(result), (error: Error) => error.message);+ expect(await refused(['visibility', '--slug', 'notes/x-example', '--apply'])).toContain('applies only the set a preview printed');+ expect(await refused(['visibility', '--slug', 'notes/x-example', '--class', 'aliases'])).toContain('takes --slug or --class, not both');+ }, { databaseUrl, setup }), 120_000);++ test('repair visibility aliases: tier kept, no proposal, the file gains only the visibility line', () => managedBrain(async ({ engine, root }) => {+ const slug = 'notes/alias-example';+ await seed(engine, root, { [slug]: file(slug, 'access: private') });+ const before = onDisk(root, slug);+ const { applied } = await previewApply(engine, ['visibility', '--class', 'aliases']);+ expect(applied.applied).toBe(1);+ await settleManagedGitEffects(engine);+ expect((await page(engine, slug)).tier).toBe('operator_curated');+ expect(await proposals(engine)).toEqual([]);+ expect(onDisk(root, slug)).toBe(withLine(before, 'visibility: private'));+ }, { databaseUrl, setup }), 180_000);++ test('repair visibility facts: the page keeps its tier, files no lower_page proposal, and its file changes only in the fact row', () => managedBrain(async ({ engine, root }) => {+ const slug = 'notes/fact-example';+ const header = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |' + NL+ + '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|' + NL;+ const withFacts = (visibility: string) => file(slug, 'visibility: private').replace('Second paragraph.' + NL, 'Second paragraph.' + NL + NL + '## Facts' + NL + NL+ + '<!--- gbrain:facts:begin -->' + NL + NL + header + '| 1 | Alice Example works at acme-example. | fact | 1.0 | ' + visibility + ' | medium | 2026-10-01 | | test | |' + NL+ + '<!--- gbrain:facts:end -->' + NL);+ await seed(engine, root, { [slug]: withFacts('world') });+ await previewApply(engine, ['visibility', '--class', 'facts']);+ await settleManagedGitEffects(engine);+ expect((await page(engine, slug)).tier).toBe('operator_curated');+ expect(await engine.executeRaw("SELECT id FROM trust_proposals WHERE action='lower_page'")).toEqual([]);+ expect(onDisk(root, slug)).toBe(withFacts('private'));+ }, { databaseUrl, setup }), 180_000);++ test('repair private-labels clear and restore change only the label lines, and keep the tier', () => managedBrain(async ({ engine, root }) => {+ const slug = 'notes/labelled-example';+ await seed(engine, root, { [slug]: file(slug, 'access: private') });+ const before = onDisk(root, slug);+ const cleared = await previewApply(engine, ['private-labels']);+ expect(cleared.applied.applied).toBe(1);+ await settleManagedGitEffects(engine);+ expect(onDisk(root, slug)).toBe(before.replace('access: private' + NL, ''));+ expect((await page(engine, slug)).tier).toBe('operator_curated');+ const restored = await previewApply(engine, ['private-labels', '--class', 'restore']);+ expect(restored.applied.applied).toBe(1);+ await settleManagedGitEffects(engine);+ // The restored line is the frontmatter's last line: a label edit appends a key it adds, keeping every other byte.+ expect(onDisk(root, slug)).toBe(withLine(before.replace('access: private' + NL, ''), 'access: private'));+ expect((await page(engine, slug)).tier).toBe('operator_curated');+ expect(await proposals(engine)).toEqual([]);+ }, { databaseUrl, setup }), 180_000);++ test('a plain put_page that adds the label still lowers, files its proposal, and the listing calls it label-only', () => managedBrain(async ({ engine, ctx, root }) => {+ const labelled = 'notes/put-example', edited = 'notes/edit-example';+ await seed(engine, root, { [labelled]: file(labelled), [edited]: file(edited) });+ const first = await putPage.handler(ctx, { slug: labelled, content: withLine(file(labelled), 'visibility: private'), request_id: randomUUID(), wait_ms: 30_000,+ expected_revision: (await page(engine, labelled)).revision }) as Record<string, any>;+ expect(first.trust_lowered?.proposal_ref).toMatch(/^tp\d+$/);+ expect((await page(engine, labelled)).tier).toBe('agent_written');+ await putPage.handler(ctx, { slug: edited, content: file(edited).replace('Second paragraph.', 'An agent rewrote this paragraph.'), request_id: randomUUID(),+ wait_ms: 30_000, expected_revision: (await page(engine, edited)).revision });+ expect((await proposals(engine)).map(p => p.proposer)).toEqual(['agent_page_edit:put_page', 'agent_page_edit:put_page']);+ const tiersBefore = await engine.executeRaw('SELECT slug, trust_tier::text FROM pages ORDER BY slug');+ const report = await listLabelLowerings(engine);+ expect(report.counts).toEqual({ lower_page: 2, label_only: 1, content: 1, unreadable: 0,+ by_proposer: { 'agent_page_edit:put_page': { label_only: 1, content: 1, unreadable: 0 } } });+ const item = report.items.find(entry => entry.class === 'label_only')!;+ expect(item).toMatchObject({ source_id: 'default', slug: labelled, proposer: 'agent_page_edit:put_page', status: 'pending',+ prior_tier: 'operator_curated', tier_now: 'agent_written', labels: { visibility: { before: null, now: 'private' } } });+ expect(item.stamps).toContain('trust_tier');+ expect(report.items.find(entry => entry.class === 'content')!.slug).toBe(edited);+ expect(renderLabelLowerings(report)).toContain('visibility (none) -> private');+ expect((await listLabelLowerings(engine, { sourceId: 'other-example' })).counts.lower_page).toBe(0);+ expect(await engine.executeRaw('SELECT slug, trust_tier::text FROM pages ORDER BY slug')).toEqual(tiersBefore);+ }, { databaseUrl, setup }), 180_000);+});++/** A repo-less brain (no managed persistence, no checkout: the default keyless install) is the database record. */+for (const backend of testBackends()) describe('[' + backend + '] label-only operator repairs on a repo-less brain', () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ test('repair visibility --slug keeps the tier and files no proposal; a page whose file is in a checkout is held', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-label-repoless-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('source-b', 'source-b', $1) ON CONFLICT (id) DO NOTHING", [join(home, 'checkout')]);+ const seed = async (sourceId: string, slug: string) => {+ expect((await importFromContent(engine, slug, file(slug), { noEmbed: true, sourceId })).status).toBe('imported');+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => withTrustBackfill(tx, () =>+ tx.executeRaw("UPDATE pages SET trust_tier='operator_curated' WHERE source_id=$1 AND slug=$2", [sourceId, slug])), TEST_WRITE_ATTRIBUTION));+ };+ await seed('default', 'notes/plain-example');+ await seed('source-b', 'notes/filed-example');+ await engine.executeRaw("UPDATE pages SET source_path='notes/filed-example.md' WHERE source_id='source-b'");+ const { applied } = await previewApply(engine, ['visibility', '--source', 'default', '--slug', 'notes/plain-example']);+ expect(applied.applied).toBe(1);+ const [row] = await engine.executeRaw<{ tier: string; visibility: string }>(+ "SELECT trust_tier::text AS tier, frontmatter->>'visibility' AS visibility FROM pages WHERE source_id='default' AND slug='notes/plain-example'");+ expect(row).toEqual({ tier: 'operator_curated', visibility: 'private' });+ expect(await proposals(engine)).toEqual([]);+ const held = await previewApply(engine, ['visibility', '--source', 'source-b', '--slug', 'notes/filed-example']);+ expect(held.applied.applied).toBe(0);+ expect(held.applied.outcome_items).toEqual([expect.objectContaining({ item: 'source-b:notes/filed-example', outcome: 'file_backed' })]);+ expect((await engine.executeRaw<{ v: string | null }>("SELECT frontmatter->>'visibility' AS v FROM pages WHERE source_id='source-b'"))[0]!.v).toBeNull();+ expect((await listLabelLowerings(engine)).counts.lower_page).toBe(0);+ } finally { await disposePersistenceConsumer(engine); await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+ }, 180_000);+});