Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs: private-hold sweep in write refusals, repair guide, error registry, key files, behavior changes and CHANGELOG (#7897)

garrytan29fe92547f15
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 26bb8f6ee9..b6480782ff 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,21 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**Three more writers refuse a `visibility: private` request page privacy does not read instead of storing a world-readable page (#7897).**
+
+`gbrain repair url-clone-fences` restored a clone file by importing HEAD's bytes as its page without checking how a private request was spelled, and ignored the import's result. On a brain without managed persistence, a HEAD whose frontmatter said `Visibility: private` (or another spelling sync holds as `visibility_noncanonical`) was stored world-readable and reported `restored`. The preview now lists such a file under the hold's code and leaves it alone, rows and page included, and an approval saved before this release applies as `held`. `gbrain brainstorm` / `gbrain lsd` `--save` on an unmanaged brain had the same gap for content passed to the exported save function; the CLI's own frontmatter never carries a private request, and it now refuses one with put_page's `visibility_not_applied` and exits 1. `gbrain sources reconcile` protected only the lowercase `visibility` key from the file side, so a file adding `Visibility: private` merged in (as an additive field under `--auto-additive`) and published world-readable; it now refuses `visibility_not_applied` at preview and apply. `visibility: private` on its own lowercase line keeps working everywhere, and pages stored before this release are not changed.
+
+### Itemized changes
+
+- `src/core/repair/url-clone-fences.ts`: the preview and the apply screen HEAD's bytes with `holdNoncanonicalPrivate` before any backup or row move; the import opts in too, and a refused import reports `held` with its code instead of `restored`.
+- `src/commands/brainstorm.ts`: the unmanaged save opts in, turns the hold into `visibility_not_applied` (`privateRequestRefusal`) and treats any refused import as not saved.
+- `src/core/persistence/reconcile-prepare.ts`: the merged result imports with `holdNoncanonicalPrivate` and refuses `visibility_not_applied`.
+- `test/import-private-hold-callers-7897.test.ts`: lists every `importFromContent` / `screenImportContent` call that does not opt in, with why it is held another way or derived from a stored page, and fails on a new unlisted call.
+- `src/core/error-registry.ts`, `src/core/behavior-change-notice.ts`, `docs/guides/write-refusals.md`, `docs/guides/repair.md`: name the new refusals.
+- Tests, on PGLite and Postgres: `test/url-clone-fences-private-hold-7897.test.ts`, `test/brainstorm-private-hold-7897.test.ts` (a Git checkout and a source with none), `test/reconcile-private-hold-7897.test.ts` (a Git checkout and a plain directory).
+
## [0.60.485.0] - 2026-10-29
**A capture that asks for `visibility: private` in a spelling page privacy does not read is refused on every brain, never stored world-readable (#7880).**
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index ec54e77a8d..050c94e765 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -4,7 +4,7 @@ See [generations](generations.md).
- `src/commands/sync-diagnostics.ts` + `src/core/persistence/{sync-run,verb-errors}.ts` — bounded source/slug/path/reason diagnostics derive from immutable managed-sync receipts, including when the local failure ledger is unavailable. Direct and resident-owner JSON carry the same receipt; human memory errors lead with the specific write reason without widening frozen v1 error codes. Pending requests retain their original UUID, terminal corrections require a new UUID, and neither retry nor line-ending diagnostics bypasses raw-byte or skip guards.
-- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts` `hardenedPathDirty`: filter-free plumbing, never `git status`, so the checkout's clean/process filters never run; `null` when only repository config could decide) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`. #6222/#6254: `assertSoleFileClaim` (reconcile-state.ts) refuses on any claimant `findLiveFileClaimants` (file-claims.ts) returns, naming the soft-delete exit (#6517). Its predicates (`fileClaimCandidatesQuery`) match the v219 expression indexes `pages_source_path_name_idx` and `pages_file_uri_name_idx` (built online, one statement per call). `sources reconcile` help says writes to one source publish one at a time. Tests: `test/persistence-reconcile.test.ts`, `test/e2e/pages-reconcile-name-indexes-postgres.test.ts`. #6394: `readReconcileState(..., { adoptSlugPath })` lets a live page with no recorded origin and no database-only marker reconcile against the file at its slug path (`slugDerivedOrigin`, mode-aware), never for a declared db_only slug, a never-filed derive-phase page, a page with a `source_uri` or a mirror-only page; the CLI flag is `gbrain sources reconcile … --preview --adopt-slug-path`, and apply and the consumer's prepare adopt only when the preview's stored page recorded no origin (`reconcilePreviewAdopts`), with the pinned relative path and binding digest unchanged. The drift refusal names the flag for such a page. #6712 wave: a missing canonical file refuses `source_changed` / detail `canonical_file_missing` with the route `canonicalDeletionState` picks from bounded filter-free Git plumbing (`missingFileRoute`: still committed at HEAD → commit the deletion or `gbrain repair ghost-pages`; gone from HEAD, or no Git or no commit → `gbrain repair file-drift --prefer database|file`). `readReconcileState(..., { fileGone })` instead returns an absent state for a recorded origin: empty preimage bytes, `raw_file_hash` pinned to `ABSENT_FILE_HASH` (all zeros, which no file hashes to, so a file that reappears is stale), the file side read as the page itself, and `assertSoleFileClaim` run with `absent: true` (`file-claims.ts` `absentCanonicalPath`, so a candidate recording the same missing path still claims it). `reconcileReadOptions` derives `adoptSlugPath` and `fileGone` from a stored preview for apply and the consumer's prepare, whose file target then expects no bytes (`expectedBeforeHash: null`). Test: `test/repair-file-drift-deleted-6712.test.ts`. `readDeletedDriftTarget` reads the deleted side of a held file that is present: a deleted page at the origin is `tombstone_edited` (id and revision), otherwise a `deleted` `sync-origin-deleted` marker is `purged_differs` (its value digested); a live claimant, a missing file, no deletion or bytes the marker held return `changed`.
+- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #7897: the merged result imports with `holdNoncanonicalPrivate`, so a merge asking for private in a spelling page privacy does not read (a file's `Visibility: private`, which the protected lowercase `visibility` key does not cover) refuses `visibility_not_applied` at preview and apply (`test/reconcile-private-hold-7897.test.ts`). #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts` `hardenedPathDirty`: filter-free plumbing, never `git status`, so the checkout's clean/process filters never run; `null` when only repository config could decide) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`. #6222/#6254: `assertSoleFileClaim` (reconcile-state.ts) refuses on any claimant `findLiveFileClaimants` (file-claims.ts) returns, naming the soft-delete exit (#6517). Its predicates (`fileClaimCandidatesQuery`) match the v219 expression indexes `pages_source_path_name_idx` and `pages_file_uri_name_idx` (built online, one statement per call). `sources reconcile` help says writes to one source publish one at a time. Tests: `test/persistence-reconcile.test.ts`, `test/e2e/pages-reconcile-name-indexes-postgres.test.ts`. #6394: `readReconcileState(..., { adoptSlugPath })` lets a live page with no recorded origin and no database-only marker reconcile against the file at its slug path (`slugDerivedOrigin`, mode-aware), never for a declared db_only slug, a never-filed derive-phase page, a page with a `source_uri` or a mirror-only page; the CLI flag is `gbrain sources reconcile … --preview --adopt-slug-path`, and apply and the consumer's prepare adopt only when the preview's stored page recorded no origin (`reconcilePreviewAdopts`), with the pinned relative path and binding digest unchanged. The drift refusal names the flag for such a page. #6712 wave: a missing canonical file refuses `source_changed` / detail `canonical_file_missing` with the route `canonicalDeletionState` picks from bounded filter-free Git plumbing (`missingFileRoute`: still committed at HEAD → commit the deletion or `gbrain repair ghost-pages`; gone from HEAD, or no Git or no commit → `gbrain repair file-drift --prefer database|file`). `readReconcileState(..., { fileGone })` instead returns an absent state for a recorded origin: empty preimage bytes, `raw_file_hash` pinned to `ABSENT_FILE_HASH` (all zeros, which no file hashes to, so a file that reappears is stale), the file side read as the page itself, and `assertSoleFileClaim` run with `absent: true` (`file-claims.ts` `absentCanonicalPath`, so a candidate recording the same missing path still claims it). `reconcileReadOptions` derives `adoptSlugPath` and `fileGone` from a stored preview for apply and the consumer's prepare, whose file target then expects no bytes (`expectedBeforeHash: null`). Test: `test/repair-file-drift-deleted-6712.test.ts`. `readDeletedDriftTarget` reads the deleted side of a held file that is present: a deleted page at the origin is `tombstone_edited` (id and revision), otherwise a `deleted` `sync-origin-deleted` marker is `purged_differs` (its value digested); a live claimant, a missing file, no deletion or bytes the marker held return `changed`.
- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list, an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values; #5966 (W14 P1.7) adds the `slug_rule_mismatch` verdict (a legacy unstamped file of a slug the path cannot derive, fix: `gbrain repair frontmatter`) read from `readReconcileState`'s refusal (`detail: slug_rule_mismatch` once the wave-13 `reconcile-state.ts` hunk lands; until then an `invalid_params` refusal on a non-fixed-point slug).
diff --git a/docs/architecture/key-files/core-persistence-graduation.md b/docs/architecture/key-files/core-persistence-graduation.md
index 1b1e9fa280..f8399d2897 100644
--- a/docs/architecture/key-files/core-persistence-graduation.md
+++ b/docs/architecture/key-files/core-persistence-graduation.md
@@ -17,6 +17,6 @@ Verified engine graduation, PGLite to Postgres ([operator guide](../../guides/mo
- `src/commands/migrate-graduation.ts` — the `gbrain migrate` graduation CLI, routed before connect from `routeEngineFreeSubcommands` in `src/cli.ts` when `routesToGraduation` holds (run-scoped verbs and `--plan` always; a bare `--to postgres|supabase` on a durable PGLite config unless `migrate.graduation` is false or the host is Windows). Without `--yes --expect` it plans and returns the `confirmation_required` payload (effects egress and destructive, what moves and what stays, `plan_hash`, the `--plan` preview; no stdin prompt); `--plan`/`--dry-run` prints the plan; the run reports the receipt, retained copy, target doctor, `gbrain mcp expose` and the MCP restart note. Exit codes 0/1/2/3, 11 for a progressing drain stop (1 when a blocker needs a person), 75 for `graduation_in_progress`, 130 after SIGINT (stops at the next batch boundary). `--json` prints one document; progress goes to stderr per table and batch. Test: `test/migrate-graduation-cli.serial.test.ts`.
- `src/commands/doctor/checks/engine-graduation.ts` — `graduationStateCheck`, emitted from the filesystem lane of `local-audits.ts`: `graduation_interrupted` fails when a manifest or marker is non-terminal with no live owner (fix `gbrain migrate --resume`, rollback named) or a stray brain sits at the old path, is `ok` while a live run owns it, exempts the run named by `GBRAIN_GRADUATION_RUN`, and emits nothing on a brain that never graduated. The retained `.graduated-*` copy is reported by `pglite_leftovers` (`src/core/pglite-leftovers-check.ts`), silent while a manifest is non-terminal.
- `src/core/repair/missing-tables.ts` — `gbrain repair missing-tables` (#6911), explicit-only and preview-bound (`--apply --expect <hash>`), brain-wide, DDL only. The preview lists the missing rebuildable caches `readMissingTables` reports (`recreate`), plus `user_data_tables` and `other_tables` residuals it never recreates; the hash covers the brain id, `LATEST_VERSION` and the tables. Apply refuses when the brain schema is newer than the client, leaves a table that already exists alone (`already_present`, no DDL), runs `recreateStep` in one transaction per table under the migration statement and lock timeouts (`schemaLockBlockedError` on a lock timeout), maps 42501 to `schema_owner_required` (approval kept) and 23505/42P07 races to `already_present`, and retires the approved set with the last item. Tests: `test/purge-missing-cache-6911.test.ts`, `test/schema-missing-tables.test.ts`.
-- `src/core/repair/url-clone-fences.ts` — `gbrain repair url-clone-fences` (#6946, GBRA-130 C-2): explicit-only, preview-bound, destructive consent; unmanaged brains only (a managed brain gets a warning naming `sources mirror-readonly`). The survey lists every tracked file of each owned clone in scope that differs from HEAD (`trackedChanges`) and proves per file (`proveFenceRowsOnly`) that HEAD's fence rows are an unchanged prefix of the working copy's and that re-rendering HEAD with the working fence matches byte for byte (`fence_rows_only`); anything else is listed as `non_fence_edit` / `unparsed_fence` / `staged_change` / `deleted` / `not_in_head` / `unreadable_checkout` and never touched. The preview hash binds the approved set (preview-approval, keyed by the command string). The apply, per file under the source filesystem lock and page lock, rechecks both sides (`changed_since_preview`), backs the file up under `~/.gbrain/backups/url-clone-fences/`, clears `row_num`/`source_markdown_slug` on the appended rows in one `maintenanceTransaction` (inserting database-only any row the database lost), imports HEAD's bytes as the page through `importFromContent`, and only then restores the file from HEAD; each step is idempotent. Test: `test/pathological/c2-url-clone-fences.test.ts`.
+- `src/core/repair/url-clone-fences.ts` — `gbrain repair url-clone-fences` (#6946, GBRA-130 C-2): explicit-only, preview-bound, destructive consent; unmanaged brains only (a managed brain gets a warning naming `sources mirror-readonly`). The survey lists every tracked file of each owned clone in scope that differs from HEAD (`trackedChanges`) and proves per file (`proveFenceRowsOnly`) that HEAD's fence rows are an unchanged prefix of the working copy's and that re-rendering HEAD with the working fence matches byte for byte (`fence_rows_only`); anything else is listed as `non_fence_edit` / `unparsed_fence` / `staged_change` / `deleted` / `not_in_head` / `unreadable_checkout` and never touched, and so is a file whose HEAD would not import (`headHold`, the import screen with `holdNoncanonicalPrivate`), listed under the hold's code; at apply that check runs before the backup and the row move, the import opts in too, and a held file reports `held` with the code instead of `restored` (#7897). The preview hash binds the approved set (preview-approval, keyed by the command string). The apply, per file under the source filesystem lock and page lock, rechecks both sides (`changed_since_preview`), backs the file up under `~/.gbrain/backups/url-clone-fences/`, clears `row_num`/`source_markdown_slug` on the appended rows in one `maintenanceTransaction` (inserting database-only any row the database lost), imports HEAD's bytes as the page through `importFromContent`, and only then restores the file from HEAD; each step is idempotent. Tests: `test/pathological/c2-url-clone-fences.test.ts`, `test/url-clone-fences-private-hold-7897.test.ts`.
- `src/core/schema-missing-tables.ts` — #6911 expected-table check. `readMissingTables`: at head every graduation-inventory table for the engine, below head only the recreatable caches whose creating migration (`CREATED_BY`) already ran, `skipped` (`client_behind`) when the brain is newer; each missing table carries its inventory class and `loss_kind`. `recreateStep` (own-key lookup, rebuild class only) rebuilds `query_cache` (v055 DDL sized from the live `facts.embedding` shape, then the v056/v090/v091 statements) and `code_traversal_cache` (v059), then on Postgres enables RLS on the recreated table through v275's `protectTables` (a role that does not bypass RLS or own the table leaves it RLS-off and names it on stderr). `test/schema-missing-tables.test.ts` pins each recreated table's columns and indexes to the migrated brain's on both engines and checks that every inventory rebuild table is either in `RECREATABLE_TABLES` or defined by the base schema (so `init --migrate-only` recreates it). Doctor `schema_missing_tables` (`src/commands/doctor/checks/schema-health.ts`) renders it: warn for caches (repair preview fix) and tables without user data, fail for `user_data` tables.
- `src/core/persistence/rebuildable-cache.ts` — #6911 purge-side skip: `isRebuildableCache` (inventory class `rebuild`), `relationExists` (`to_regclass` on the connection's search path), and `clearRebuildableCache(tx, table)`, which returns the rows deleted or null when the cache table is absent; the existence check runs first because a 42P01 aborts a Postgres transaction. Callers: page purge (`purge.missing_caches`) and fact purge.
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index 16a8a8d959..600da3e14e 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/brainstorm/checkpoint.ts` — crash-resilient checkpoint for `gbrain brainstorm` and `gbrain lsd`. Persists FULL idea bodies (~50KB/run) so resume MERGES pre-crash ideas with post-resume ideas before the judge runs (a resume that produces only second-run output is silent partial output). `run_id = sha256(question + profile + sort(close_slugs) + sort(far_slugs)).slice(0,16)` — NO embedding bits, stable across embedding-model swaps. Atomic write via `.tmp + rename`. ONE resume flag (`--resume <run_id>` covers failed crosses, never-attempted crosses, AND a failed judge phase — the orchestrator keeps the checkpoint with `judge_done=false` whenever the judge throws, so `--resume` short-circuits every completed cross from disk and re-runs only the judge; there is no separate retry-judge flag); only a fully clean run (all crosses + judge) clears the file. The checkpoint also banks the CLI's saved-page slug (`idea_slug`, from `RunBrainstormOpts.ideaSlug`) and the orchestrator echoes it back as `BrainstormResult.idea_slug` on resume, so the re-scored page overwrites the one the failed run saved instead of forking a second page under a fresh nonce. `--list-runs` prints run_ids mtime-newest-first; `--force-resume` bypasses the 7-day staleness gate. Cycle purge phase (`gbrain dream --phase purge`) GCs checkpoints older than 7 days via `gcStaleCheckpoints(7)`. Pinned by `test/e2e/brainstorm-resume.test.ts` (20 unit + 5 E2E cases incl. the merge contract and judge-failed retention/re-score).
-- `src/core/brainstorm/{domain-bank,orchestrator,judges}.ts` + `src/commands/{brainstorm,lsd,eval-brainstorm}.ts` + `src/core/last-retrieved.ts` — bisociation-grounded idea generation pair: `gbrain brainstorm <question>` (defensible, cite-heavy, 4 close × 6 far, judge threshold 4.0/5, save by default) and `gbrain lsd <question>` (Lateral Synaptic Drift — inverted judge rejecting ideas with resistance >4.5 "too obvious", stale-page bias via `pages.last_retrieved_at`, 2 close × 12 far, axiomatic inversions required, ephemeral by default). The "domain bank" is prefix-stratified sampling from the user's own brain (`SELECT DISTINCT substring(slug from '^[^/]+/[^/]+')` cached 1h-TTL in `config` per source) tiebroken by `JOIN page_links` connection_count, with corpus-sampling fallback when fewer prefixes than M exist. Distance normalized to [0,1] via `1 - clamp(cosine_distance, 0, 2) / 2`. `judges.ts` exports `runJudge(config, ideas)` + two configs (`BRAINSTORM_JUDGE_CONFIG` weighted originality/resistance/thesis_density/concrete_grounding/cognitive_load 0.25/0.20/0.20/0.20/0.15 vs `LSD_JUDGE_CONFIG` cognitive_load 0.50 + inversion rule). Calibration cold-start fallback: when `calibration_profiles.active_bias_tags` is empty, judge runs without anti-bias context AND stderr-warns. Op-layer write-back in `src/core/operations.ts` `search`/`query`/`get_page` handlers fires `bumpLastRetrievedAt(engine, pageIds)` (fire-and-forget, 5-min throttled via SQL clause, default-on with `search.track_retrieval` config escape hatch); internal callers (sync, migrations, dream cycle) bypass the op layer so the LSD stale signal stays clean. The fire-and-forget IIFE is tracked in a module-scoped `Set<Promise<unknown>>`; `awaitPendingLastRetrievedWrites(timeoutMs?: number): Promise<{outcome, pending}>` resolves once all tracked promises settle, bounded by a 5s `Promise.race` timeout that stderr-warns the pending count. `src/cli.ts` awaits the drain unconditionally for every op in the op-dispatch finally block BEFORE `engine.disconnect()`, then a fallback `process.exit(0)` fires ONLY when `outcome === 'timeout'` AND `shouldForceExitAfterMain(argv)` (excludes `serve` so daemons stay alive) — so the IIFE cannot race disconnect and leave PGLite's WASM keeping Bun's event loop alive. The timestamp lives in `page_retrievals(page_id, last_retrieved_at)` (v224): the bump is an `INSERT ... ON CONFLICT DO UPDATE` throttled to 5 minutes, a HOT update with no triggers that never advances `page_generation_clock_seq` (the old `UPDATE pages` advanced it on every read, expiring the query-cache bookmark and the get_health and projection-readiness memos). No foreign key; the `pages_forget_retrievals` statement trigger removes rows of hard-deleted pages. Readers (domain-bank samplers, volunteer stats, entity card) take `GREATEST(pages.last_retrieved_at, page_retrievals.last_retrieved_at)`; the legacy column stays (unindexed since v224) for older binaries; full forward-reference bootstrap probe on both engines. Frontmatter `mode: lsd` makes the dream-cycle synthesize phase skip LSD output via `isLsdOutput()` in `src/core/cycle/transcript-discovery.ts` short-circuiting `isDreamOutput()`. `gbrain eval brainstorm <fixture.jsonl>` is a three-axis conjunctive gate (distance + usefulness + grounding — distance alone is gameable). `gbrain doctor` has a `brainstorm_health` check (migration applied, `search.track_retrieval` setting, an unpriced cross or judge chat model, calibration cold-start status). Cost policy lives in `src/core/brainstorm/cost-gate.ts`: no cap flag is the $5 `default` tracker cap (an unpriced model warns and runs, priced calls stay metered; the estimate, mid-run guard and pre-judge check count it at Sonnet rates), `--max-usd N` (legacy `--max-cost`) is a `user` cap that refuses a run touching an unpriced chat, judge or embedding model before any work with the `no-pricing.ts` refusal, `--max-usd off` drops the USD ceiling; every price reads `pricing.overrides`; results carry `cost.cap_usd`/`cost.cap_source`. `judges.ts` computes the judge token budget via `computeJudgeMaxTokens(ideaCount, modelId)` (named constants `TOKEN_BUDGET_PER_IDEA`, `TOKEN_BUDGET_ENVELOPE`, `LEGACY_MIN_MAX_TOKENS`, `MAX_OUTPUT_TOKENS_CEIL`; `ANTHROPIC_OUTPUT_CAPS` map: Opus 4.7 32K, Sonnet 4.6 / Haiku 4.5 64K, legacy Claude 3.5 8K) so a large multi-call judge doesn't truncate mid-JSON; with no `modelOverride` the cap routes through the gateway's actual configured chat model via `getChatModel()`. `--save` for both commands persists through the canonical ingestion path: `persistSavedIdea(engine, {slug, content, provenanceVia})` calls `importFromContent({noEmbed:true, sourcePath})` (chunked + tagged + content_hash so search finds it, no embedding cost at save) THEN renders the saved row to disk via the shared `writePageThrough` helper (file rendered FROM the row so the two sinks can't diverge and `gbrain sync` doesn't churn it). `formatSaveOutcome(outcome, ctx)` returns an honest per-branch message (both-sinks, DB-only when no `sync.repo_path`/repo-not-a-dir, DB-saved-but-file-errored, total-failure → loud `save FAILED … NOT persisted` on stderr + nonzero exit) — `--save` never prints "Saved" when the DB write failed. `buildIdeaSlug(question, label, nonce?)` adds a random nonce suffix (injectable for tests) so two same-day runs sharing the first 60 slug chars don't clobber. `--json` callers stay DB-only. `buildBrainstormFrontmatterObject(result)` in orchestrator.ts returns the object form for `serializeMarkdown`. Pinned by `test/last-retrieved.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts` (IRON-RULE: real `bun src/cli.ts` subprocess against a hermetic PGLite tempdir asserts search/get/query exit 0 in <15s + daemon-survival), `test/fix-wave-structural.test.ts` (asserts the drain `await` is textually BEFORE `engine.disconnect`), `test/brainstorm/{distance,lsd-mode-skip,eval-brainstorm,judges-maxtokens,save}.test.ts`. Open Collider source: `github.com/CL-ML/open-collider`.
+- `src/core/brainstorm/{domain-bank,orchestrator,judges}.ts` + `src/commands/{brainstorm,lsd,eval-brainstorm}.ts` + `src/core/last-retrieved.ts` — bisociation-grounded idea generation pair: `gbrain brainstorm <question>` (defensible, cite-heavy, 4 close × 6 far, judge threshold 4.0/5, save by default) and `gbrain lsd <question>` (Lateral Synaptic Drift — inverted judge rejecting ideas with resistance >4.5 "too obvious", stale-page bias via `pages.last_retrieved_at`, 2 close × 12 far, axiomatic inversions required, ephemeral by default). The "domain bank" is prefix-stratified sampling from the user's own brain (`SELECT DISTINCT substring(slug from '^[^/]+/[^/]+')` cached 1h-TTL in `config` per source) tiebroken by `JOIN page_links` connection_count, with corpus-sampling fallback when fewer prefixes than M exist. Distance normalized to [0,1] via `1 - clamp(cosine_distance, 0, 2) / 2`. `judges.ts` exports `runJudge(config, ideas)` + two configs (`BRAINSTORM_JUDGE_CONFIG` weighted originality/resistance/thesis_density/concrete_grounding/cognitive_load 0.25/0.20/0.20/0.20/0.15 vs `LSD_JUDGE_CONFIG` cognitive_load 0.50 + inversion rule). Calibration cold-start fallback: when `calibration_profiles.active_bias_tags` is empty, judge runs without anti-bias context AND stderr-warns. Op-layer write-back in `src/core/operations.ts` `search`/`query`/`get_page` handlers fires `bumpLastRetrievedAt(engine, pageIds)` (fire-and-forget, 5-min throttled via SQL clause, default-on with `search.track_retrieval` config escape hatch); internal callers (sync, migrations, dream cycle) bypass the op layer so the LSD stale signal stays clean. The fire-and-forget IIFE is tracked in a module-scoped `Set<Promise<unknown>>`; `awaitPendingLastRetrievedWrites(timeoutMs?: number): Promise<{outcome, pending}>` resolves once all tracked promises settle, bounded by a 5s `Promise.race` timeout that stderr-warns the pending count. `src/cli.ts` awaits the drain unconditionally for every op in the op-dispatch finally block BEFORE `engine.disconnect()`, then a fallback `process.exit(0)` fires ONLY when `outcome === 'timeout'` AND `shouldForceExitAfterMain(argv)` (excludes `serve` so daemons stay alive) — so the IIFE cannot race disconnect and leave PGLite's WASM keeping Bun's event loop alive. The timestamp lives in `page_retrievals(page_id, last_retrieved_at)` (v224): the bump is an `INSERT ... ON CONFLICT DO UPDATE` throttled to 5 minutes, a HOT update with no triggers that never advances `page_generation_clock_seq` (the old `UPDATE pages` advanced it on every read, expiring the query-cache bookmark and the get_health and projection-readiness memos). No foreign key; the `pages_forget_retrievals` statement trigger removes rows of hard-deleted pages. Readers (domain-bank samplers, volunteer stats, entity card) take `GREATEST(pages.last_retrieved_at, page_retrievals.last_retrieved_at)`; the legacy column stays (unindexed since v224) for older binaries; full forward-reference bootstrap probe on both engines. Frontmatter `mode: lsd` makes the dream-cycle synthesize phase skip LSD output via `isLsdOutput()` in `src/core/cycle/transcript-discovery.ts` short-circuiting `isDreamOutput()`. `gbrain eval brainstorm <fixture.jsonl>` is a three-axis conjunctive gate (distance + usefulness + grounding — distance alone is gameable). `gbrain doctor` has a `brainstorm_health` check (migration applied, `search.track_retrieval` setting, an unpriced cross or judge chat model, calibration cold-start status). Cost policy lives in `src/core/brainstorm/cost-gate.ts`: no cap flag is the $5 `default` tracker cap (an unpriced model warns and runs, priced calls stay metered; the estimate, mid-run guard and pre-judge check count it at Sonnet rates), `--max-usd N` (legacy `--max-cost`) is a `user` cap that refuses a run touching an unpriced chat, judge or embedding model before any work with the `no-pricing.ts` refusal, `--max-usd off` drops the USD ceiling; every price reads `pricing.overrides`; results carry `cost.cap_usd`/`cost.cap_source`. `judges.ts` computes the judge token budget via `computeJudgeMaxTokens(ideaCount, modelId)` (named constants `TOKEN_BUDGET_PER_IDEA`, `TOKEN_BUDGET_ENVELOPE`, `LEGACY_MIN_MAX_TOKENS`, `MAX_OUTPUT_TOKENS_CEIL`; `ANTHROPIC_OUTPUT_CAPS` map: Opus 4.7 32K, Sonnet 4.6 / Haiku 4.5 64K, legacy Claude 3.5 8K) so a large multi-call judge doesn't truncate mid-JSON; with no `modelOverride` the cap routes through the gateway's actual configured chat model via `getChatModel()`. `--save` for both commands persists through the canonical ingestion path: `persistSavedIdea(engine, {slug, content, provenanceVia})` calls `importFromContent({noEmbed:true, sourcePath, holdNoncanonicalPrivate:true})` (a held private request refuses put_page's `visibility_not_applied` and any other refusal is a failed save, #7897; chunked + tagged + content_hash so search finds it, no embedding cost at save) THEN renders the saved row to disk via the shared `writePageThrough` helper (file rendered FROM the row so the two sinks can't diverge and `gbrain sync` doesn't churn it). `formatSaveOutcome(outcome, ctx)` returns an honest per-branch message (both-sinks, DB-only when no `sync.repo_path`/repo-not-a-dir, DB-saved-but-file-errored, total-failure → loud `save FAILED … NOT persisted` on stderr + nonzero exit) — `--save` never prints "Saved" when the DB write failed. `buildIdeaSlug(question, label, nonce?)` adds a random nonce suffix (injectable for tests) so two same-day runs sharing the first 60 slug chars don't clobber. `--json` callers stay DB-only. `buildBrainstormFrontmatterObject(result)` in orchestrator.ts returns the object form for `serializeMarkdown`. Pinned by `test/last-retrieved.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts` (IRON-RULE: real `bun src/cli.ts` subprocess against a hermetic PGLite tempdir asserts search/get/query exit 0 in <15s + daemon-survival), `test/fix-wave-structural.test.ts` (asserts the drain `await` is textually BEFORE `engine.disconnect`), `test/brainstorm/{distance,lsd-mode-skip,eval-brainstorm,judges-maxtokens,save}.test.ts`. Open Collider source: `github.com/CL-ML/open-collider`.
- `src/core/budget/budget-tracker.ts` — the keystone budget primitive. One typed error (`BudgetExhausted` with `reason: 'cost' | 'runtime' | 'no_pricing'`), one schema-stable audit JSONL at `~/.gbrain/audit/budget-YYYY-Www.jsonl`. Contracts: `record()` throws when cumulative spend exceeds cap (the cap is a real ceiling, not a suggestion); `reserve()` admission checks cumulative + OUTSTANDING spend and returns an opaque `BudgetReservation` id for each held projection; `record({ reservation })` settles that id and `release(id)` frees an attempt that never billed (no-op when already settled), so N concurrent callers can't all pass against the same cumulative and a small same-model call finishing first can't free a large in-flight call's hold (settlement is by id, never by model; an id-less record settles nothing; a priced reservation recorded under an unpriced served id charges its held ceiling). `gateway.chat` reserves, then runs the attempt in one try/finally that releases the id (provider-resolution failure, invocation-policy refusal); embed reserves after its preflights; rerank, decide, the TypeSafe rerank adapter and embed-facts pass their ids. Record audit rows carry `requested_model` and `reservation`; `reserve()` hard-fails with `reason: 'no_pricing'` when `maxCostUsd` is set AND the model is missing from pricing maps, its message and `BudgetExhausted.pricing` built by `no-pricing.ts` (warn-once preserved when cap is unset, naming the registration command); `lookupPricing` normalizes recipe aliases through `resolveRecipe` before consulting the pricing tables, so `claude-cli:haiku` prices exactly like `claude-cli:claude-haiku-4-5-20251001` at `reserve()`, `record()` and `isModelPriceable()` alike (the gateway reserves with the pre-resolution string the user configured); `extractUsageFromError(err, fallback)` returns `err.usage` when the SDK provides it, else the pessimistic fallback (caller passes `maxOutputTokens`, not the optimistic pre-call estimate). `onExhausted(cb)` fires once synchronously BEFORE the throw propagates so callers can persist checkpoints. Pricing math lives in the pure `src/core/budget/reservation-cost.ts`: `priceFor(model, kind, overrides) → { pricing, source: 'override' | 'provider_wildcard' | 'table' } | null` is the one resolver (exact override, then a `<provider>:*` wildcard admitted only for recipes with `billing: 'subscription'` by `isAllowedPricingOverrideKey`, then aliases, the claude-cli → Anthropic sibling, canonical rows and free local providers); `isModelPriceable`, `usageCostUsd`/`reservationCostUsd`, skillopt preflight and synthesize_concepts all use it. `parsePricingOverrides` drops disallowed keys and adds each alias key's canonical twin. Every `record()` also feeds an in-memory model ledger keyed by (requested model, served model, touchpoint, purpose) — updated BEFORE the cap throw and before the unpriced early return — exposed as `snapshot().models`; `BudgetActualUsage` carries `requestedModelId`, `purpose`, `failed`, `countsAsCall` (default true) and `estimated`, and rows track `calls` (gateway operations), `attempts` (every record), `failed_calls`, tokens, `cost_usd` (`null` when unpriced) and `cost_basis` (`estimated` if any contributing record was). `src/core/budget/models-used.ts` maps labels to touchpoints (`gateway.chat`→chat, `gateway.expand*`→expansion, `gateway.embed*`→embedding, `gateway.rerank*`→rerank, `gateway.ocr*`→ocr, else other), builds receipt rows (`buildModelsUsed`), merges resumed segments and renders the "Models called" table. No DB change. Shared by brainstorm, cycle/budget-meter, and eval-contradictions; `BudgetMeter` keeps its public shape over it (`schema_version: 1` stamped on every dream-budget audit line). Pinned by 18 unit cases. A4 cap sources: `capSource: 'derived' | 'default' | 'user'` (getter `capSource`; an explicit `maxCostUsd` with no declared source is `user`, the pre-A4 behaviour). Only a `user` cap hard-fails an unpriced model, and that `BudgetExhausted` carries `fix` (`noPricingFix`, actor `agent` on the CLI, `host_admin` when `transport` is remote); `derived`/`default` caps warn once and run the model unmetered. Cost exhaustion carries `capSource`, and a `derived` one appends `derived_cap_exhausted` to the agent-contract log (callers report it with `consent.ts`'s `derivedCapExhaustedError`). Pinned by `test/budget-tracker-cap-source.test.ts`.
- `src/core/budget/daily-ledger.ts` — #6188 the durable per-UTC-day USD ledger over `budget_ledger`/`budget_reservations` (migration v012; no new schema), one ledger per (scope, resolver), e.g. `FENCE_REPAIR_LEDGER` (`llm_repair`/`fences`). `reserve(estimate, { capUsd })` is one conditional upsert (`reserved + committed + estimate <= cap`) plus a reservation row with `expires_at`; `dispatch` marks it sent; `settle(id, actual)` is idempotent, bound to the reservation's own day, and records an overrun; `release` returns an undispatched hold; expired holds are reclaimed before each reserve (a dispatched one is charged its estimate). Any ledger error means no call (`ledger_unavailable`); `meteredCall` runs the whole protocol. Amounts are NUMERIC(12,4), spend rounded up and caps down. `estimateChatCallUsd` prices a chat call through `pricing.overrides` and the canonical table; an unpriced model is metered at the highest canonical rate (`estimated: true`) under a default cap and refused with `noPricingGuidance` under a user cap. Never opens a BudgetTracker, so a caller's ambient tracker keeps metering. Read by doctor `fence_integrity` (today's spend). Tests: `test/daily-ledger.test.ts` (+ `test/e2e/daily-ledger-postgres.test.ts`, concurrent sessions).
diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.md
index 303b513aba..c24690e405 100644
--- a/docs/architecture/key-files/files-and-sync-2.md
+++ b/docs/architecture/key-files/files-and-sync-2.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/persistence/visibility-request.ts` — the private-request guard. `readPrivateRequest(content, parse)` reads whether content asks for `visibility: private`: a frontmatter line in any case, or the parse reading a visibility key of any case as private (block scalars, lists, flow mappings and merge keys count). Page writes (`put_page`, `edit_page`, `capture`; `privateRequestGuarded`) refuse a request the stored frontmatter would not keep as exactly `visibility: private` (`assertPrivateRequestKept`, `visibility_not_applied`); an unmanaged `ingest_capture` job takes the same refusal (`privateRequestRefusal`) after `importFromContent`'s screen holds the content (`holdNoncanonicalPrivate`), and dead-letters without a retry (#7880). File ingestion holds the same case as `visibility_noncanonical` (`noncanonicalPrivateHold`): classic sync and legacy `gbrain import` through `importFromFile` and `screenLegacyFile`, managed sync and import through `screenImportContent`'s `holdNoncanonicalPrivate`, and through `importFromContent`'s opt-in of the same name: `ingest_capture`, company-brain imports (`importCompanyBrainFile`) and the GitHub and Google connectors' database-only imports (#7880), streamed large files unless they are a page write, with or without a Git checkout. Doctor `git_held_files` counts those holds and the live stored pages `noncanonicalPrivateRequest('', frontmatter)` reads as asking for private (`details.visibility_noncanonical`); nothing rewrites them. Derived writers never refuse. Tests: `test/put-visibility-private-7841.test.ts`, `test/visibility-noncanonical-hold-7848.test.ts`, `test/ingest-capture-private-hold-7880.test.ts`, `test/company-brain-private-hold-7880.test.ts` (Postgres: the matching `test/e2e/*-postgres.test.ts` wrappers).
+- `src/core/persistence/visibility-request.ts` — the private-request guard. `readPrivateRequest(content, parse)` reads whether content asks for `visibility: private`: a frontmatter line in any case, or the parse reading a visibility key of any case as private (block scalars, lists, flow mappings and merge keys count). Page writes (`put_page`, `edit_page`, `capture`; `privateRequestGuarded`) refuse a request the stored frontmatter would not keep as exactly `visibility: private` (`assertPrivateRequestKept`, `visibility_not_applied`); an unmanaged `ingest_capture` job takes the same refusal (`privateRequestRefusal`) after `importFromContent`'s screen holds the content (`holdNoncanonicalPrivate`), and dead-letters without a retry (#7880). File ingestion holds the same case as `visibility_noncanonical` (`noncanonicalPrivateHold`): classic sync and legacy `gbrain import` through `importFromFile` and `screenLegacyFile`, managed sync and import through `screenImportContent`'s `holdNoncanonicalPrivate`, and through `importFromContent`'s opt-in of the same name: `ingest_capture`, company-brain imports (`importCompanyBrainFile`) and the GitHub and Google connectors' database-only imports (#7880), `gbrain repair url-clone-fences` (a held HEAD previews under its code and applies as `held`), and the unmanaged `brainstorm --save` and `sources reconcile`, which turn the hold into `visibility_not_applied` (#7897), streamed large files unless they are a page write, with or without a Git checkout. Doctor `git_held_files` counts those holds and the live stored pages `noncanonicalPrivateRequest('', frontmatter)` reads as asking for private (`details.visibility_noncanonical`); nothing rewrites them. Derived writers never refuse. Tests: `test/put-visibility-private-7841.test.ts`, `test/visibility-noncanonical-hold-7848.test.ts`, `test/ingest-capture-private-hold-7880.test.ts`, `test/company-brain-private-hold-7880.test.ts`, `test/{url-clone-fences,brainstorm,reconcile}-private-hold-7897.test.ts` (Postgres: the matching `test/e2e/*-postgres.test.ts` wrappers). `test/import-private-hold-callers-7897.test.ts` lists every `importFromContent` / `screenImportContent` call that does not opt in, with why it is held or derived, and fails on a new one.
- `src/core/sync-embed-backfill.ts` — Sync command’s engine-aware embedding-delivery seam. It derives separate worker-backed deferral and multi-source fan-out eligibility, keeps automatic-submission policy distinct from capability, invokes the shared cost gate for `--all` and single-source runs, propagates intrinsic large-sync deferral into final delivery outcomes, resolves backfill results through the centralized submitter, formats one truthful human status, and builds the single-source JSON envelope. `syncProducedEmbeddableContent` is the one content gate every automatic submit site (`sync --all`, single-source autodefer, the jobs `sync` handler) applies on top of status: a sweep-only or delete-only run reports `synced` but wrote no chunks, and minting a backfill for it would only arm the per-source cooldown against the next real import (the handler reports `embed_skip_reason: 'no_new_content'`). Keeping these pieces together prevents cost-gate, queue, human, and machine surfaces from drifting while the size-ratcheted `src/commands/sync.ts` façade stays at its committed ceiling.
- `src/core/sync-failure-ledger.ts` — the bounded auto-skip sync failure ledger. A LEAF module (imports only fs/path/crypto/config) so `sync.ts` can re-export it without a circular dependency. State lives in `~/.gbrain/sync-failures.jsonl`, one JSON object per line, keyed by `(source_id, path)` with a per-key `attempts` count and a 3-state machine: `open` (fresh/blocking) → `auto_skipped` (chronic, still doctor-visible) or `acknowledged` (human resolved via `gbrain sync --skip-failed` from either unresolved state). `classifyErrorCode(errorMsg)` regex classifier with 23 named codes (`RENAME_RECONCILE`, `SLUG_MISMATCH`, `DB_DUPLICATE_KEY`, `STATEMENT_TIMEOUT`, `YAML_PARSE`, `YAML_DUPLICATE_KEY`, `MISSING_OPEN`, `MISSING_CLOSE`, `EMPTY_FRONTMATTER`, `NULL_BYTES`, `NESTED_QUOTES`, `INVALID_UTF8`, `FILE_TOO_LARGE`, `SYMLINK_NOT_ALLOWED`, `TAKES_TABLE_MALFORMED`, `TAKES_HOLDER_INVALID`, `EMBEDDING_NO_CREDS`, `EMBEDDING_NO_TOUCHPOINT`, `EMBEDDING_TIMEOUT`, `EMBEDDING_RATE_LIMIT`, `EMBEDDING_QUOTA`, `EMBEDDING_OVERSIZE`, `PAGE_JUNK_PATTERN`) plus `UNKNOWN` (the default fallthrough); `summarizeFailuresByCode(failures)` returns sorted `[{code, count}]`; `MISSING_OPEN`/`EMPTY_FRONTMATTER` regexes match the `markdown.ts` validator strings; `MISSING_CLOSE`'s regex is stale against current `markdown.ts` output — it matches the no-heading-hint case (`No closing --- delimiter found`) but not the heading-hint case (`No closing --- before heading at line N`), which falls through to `UNKNOWN`. `FILE_TOO_LARGE` covers `import-file.ts:395, 1236, 1436` (markdown/text, plain-file, and code-file import paths), `SYMLINK_NOT_ALLOWED` covers `:1231, 2038` (file and image import paths). `EMBEDDING_INFRA_CODES` is the subset (`EMBEDDING_TIMEOUT`/`EMBEDDING_RATE_LIMIT`/`EMBEDDING_QUOTA`) that means the embedding PROVIDER is unhealthy rather than the file being poison — `isEmbeddingInfraCode(code)` is consulted inside `decideGateAction`'s chronic-eligibility loop so these three are never counted toward auto-skip (treated as fresh, forcing `block` instead of `advance_then_autoskip`); an explicit `--skip-failed` still advances past them like any other failure, since that check runs before the loop. All mutations run under `withLedgerLock` (cross-process file lock) with an atomic rename write. The auto-skip threshold resolves via `resolveAutoSkipThreshold()` from `GBRAIN_SYNC_AUTOSKIP_AFTER` (default `DEFAULT_AUTOSKIP_AFTER = 3`; `0` disables the valve = pure fail-closed). Two pure decision functions are the unit-test surface: `decideGateAction({fileFailures, sentinels, attemptsByPath, threshold, skipFailed})` returns `hard_block | block | advance | advance_then_autoskip` (sentinels like `<head>` ALWAYS hard-block, even with `--skip-failed`, so a history rewrite can't auto-skip; any FRESH failure with `attempts < threshold` blocks fail-closed; only when ALL failures are chronic does it `advance_then_autoskip`), and `decideSyncFailureSeverity({entries, nowMs, failHours})` returns the `sync_failures` doctor status (`ok` when zero unresolved; `fail` when ≥10 OPEN-blocking or the oldest OPEN failure's `ts` (last attempt, NOT `first_seen`) is older than `failHours` — a failure retried inside that window keeps refreshing `ts` and never trips this leg even if `first_seen` is much older; otherwise `warn` — `auto_skipped`-only rows stay WARN-visible regardless of count because the bookmark already advanced). `applySyncFailureGate(input)` is the one orchestrator BOTH sync paths (incremental + full/`runImport`) call: it records/clears ledger rows, runs `decideGateAction`, then executes effects in the crash-safe order (advance the bookmark FIRST via the injected `advance()` callback, THEN auto-skip the chronic set) so a crash can never mark a file skipped while leaving sync wedged. `isSkippablePath` rejects `<…>` sentinels. Pinned by `test/sync-failure-ledger.serial.test.ts` + `test/sync-failures.test.ts`. GBRA-130 A-18: the module imports `BILLING_MESSAGE_RE`/`RATE_MESSAGE_RE` from the import-free `ai/errors.ts` (still a leaf). `classifyErrorCode(msg, path?)` never reads path text as a provider error: errno-led messages map to `PERMISSION_DENIED` (EACCES/EPERM) or `FILE_UNREADABLE` (ENOENT and other file errnos), and the infra regexes run on the message with the embed envelope, the path and its tokens stripped, so `billing/q3.md` or `http-429.md` no longer read as `EMBEDDING_QUOTA`/`EMBEDDING_RATE_LIMIT`. `syncFailureCode(error, path)` takes the structured errno first (the import paths pass `SyncFailedFile.code`). `SyncGateInput` gains `code`, `imported` and `systemic`: a run where files imported records `infra_isolated_runs` on an open infra row, and `decideGateAction` treats an infra row with `infra_isolated_runs >= threshold` as chronic, auto-skipped with code `EMBEDDING_INFRA_ISOLATED`; a run where nothing imported never counts toward it. A systemic run (the `sync.import_files` ItemRun breaker, most files failing) adds no attempt to open rows, starts new rows at 1, blocks, and `finalize.ts` prints a blocked message naming `--skip-failed`. Pinned by `test/pathological/a18-ledger-path-text.test.ts` (both engines).
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index ba0b140410..41ea951500 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -4653,7 +4653,7 @@ More: [docs/ENGINES.md#vector-index-prewarm](../../docs/ENGINES.md#vector-index-
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| A file asks for visibility: private in a spelling page privacy does not read, so sync or import held it instead of storing it world-readable. | Page privacy reads only the exact lowercase key and value visibility: private. A file that spells it another way (Visibility: private, visibility: Private, a block scalar, a list, a flow mapping or a merge key) would be stored as a world page while its author believes it is private (#7848); put_page, edit_page, capture and ingest_capture refuse the same request as visibility_not_applied. | Write visibility: private on its own frontmatter line (lowercase key and value), then commit and sync, or import the file again. | agent | `repeat the read that failed` | 1 | no |
+| A file asks for visibility: private in a spelling page privacy does not read, so sync or import held it instead of storing it world-readable. | Page privacy reads only the exact lowercase key and value visibility: private. A file that spells it another way (Visibility: private, visibility: Private, a block scalar, a list, a flow mapping or a merge key) would be stored as a world page while its author believes it is private (#7848); put_page, edit_page, capture, ingest_capture, brainstorm --save and sources reconcile refuse the same request as visibility_not_applied. | Write visibility: private on its own frontmatter line (lowercase key and value), then commit and sync, or import the file again. | agent | `repeat the read that failed` | 1 | no |
More: [docs/guides/write-refusals.md#visibility_noncanonical](../../docs/guides/write-refusals.md#visibility_noncanonical)
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 291aac9748..fb44f90930 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -169,7 +169,7 @@ work behind exits 0, so scripts should also check `results[].complete`.
| `rename-identity` | `rename_identity_downgrades` | Explicit-only, preview-bound, destructive consent. For an inexact Git rename that sync split into a delete plus an add (#6729): carries the old page's identity (id, version history, timeline, links, facts, aliases) onto the new slug, imports the new file onto it as an edit and retires the provisional page; or, with `--close`, settles the pair and moves nothing. `--slug <new-slug>` (and `--from <old-slug>`) names one pair; `--apply --expect <hash> --yes`. See [rename identity](#rename-identity). | `fact_rows_collide` (a fence row of the old page the new file does not keep with the same claim); `managed_remedy_unavailable` (a carry on a managed source; `--close` is the remedy there); pages changed after the preview (`changed_since_preview`). |
| `overwritten-edits` | `sync_overwritten_db_edits` | Explicit-only, preview-bound. Restores database edits that an incremental managed sync replaced with a committed file edit and no `file_drift` hold (#6712, fixed by #6887). It restores only what the records prove: a database-only revision (its receipt published no file) archived by a managed-sync import that wrote different content, with no later revision holding the edit again. The preview diffs the live page against the edit; `--apply --expect <hash>` reverts each page to that version through a revision-bound, database-only `revert_version` and holds the committed file `file_drift` when it differs. See [overwritten edits](#overwritten-edits). | `unknown_*` findings (no persistence outcome on the writer's receipt, the import's content no longer readable, a segmented version), listed but not restored; pages that moved after the preview (`changed_since_preview`). |
| `missing-tables` | `schema_missing_tables` | Explicit-only, preview-bound. Recreates, empty, a rebuildable cache table (`query_cache`, `code_traversal_cache`) that the applied migrations created but the brain no longer has, on a brain whose schema version already covers its creating migration, so `apply-migrations` never recreates it (#6911). DDL only (`IF NOT EXISTS`), no journal admission, brain-wide. See [missing tables](#missing-tables). | `user_data_tables`: a missing table that holds user data; this repair never recreates it, so restore its rows from a backup first. `other_tables`: a missing table that holds no user data; `gbrain init --migrate-only` recreates it if the base schema defines it. |
-| `url-clone-fences` | none (`gbrain sync --source <id>` stops at the pull with `pull_blocked_local_changes`) | Explicit-only, preview-bound, destructive consent. Clears the `## Facts` fence rows an older gbrain appended to files of a clone it owns (`gbrain sources add --url`), which block every `git pull --ff-only` that touches those files (#6946). The preview proves each changed file differs from HEAD only by appended fence rows; `--apply --expect <hash> --yes` backs each file up, keeps its rows database-only and restores the file from HEAD. Unmanaged brains only. See [URL clone fences](#url-clone-fences). | `non_fence_edit`, `unparsed_fence`, `staged_change`, `deleted`, `not_in_head`, `unreadable_checkout`: a file with any other difference from HEAD, named with why; files that changed after the preview (`changed_since_preview`). |
+| `url-clone-fences` | none (`gbrain sync --source <id>` stops at the pull with `pull_blocked_local_changes`) | Explicit-only, preview-bound, destructive consent. Clears the `## Facts` fence rows an older gbrain appended to files of a clone it owns (`gbrain sources add --url`), which block every `git pull --ff-only` that touches those files (#6946). The preview proves each changed file differs from HEAD only by appended fence rows; `--apply --expect <hash> --yes` backs each file up, keeps its rows database-only and restores the file from HEAD. Unmanaged brains only. See [URL clone fences](#url-clone-fences). | `non_fence_edit`, `unparsed_fence`, `staged_change`, `deleted`, `not_in_head`, `unreadable_checkout`: a file with any other difference from HEAD, named with why; a file whose HEAD would not import as its page (`visibility_noncanonical` and the other import holds; an approval saved earlier applies as `held`); files that changed after the preview (`changed_since_preview`). |
| `segmented-mirror` | none (doctor does not read segmented files; run the preview once if the brain ran a version before v0.60.299.0) | Explicit-only, preview-bound, destructive consent. Rewrites the canonical file of a page stored in segments that an older binary's withdrawal mirror passed by (`page_body_segmented`), so the file still holds a row `forget`, `forget_fact` or `purge_fact` removed from the database. The file becomes the page's canonical render (`gbrain export`'s bytes), written by the withdrawal mirror and committed by its Git effect. See [segmented mirror](#segmented-mirror). | `file_database_drift`: the file also differs from the database for another reason; it is listed held and never rewritten. `not_owner_host`: the preview ran off the source's owner host and read none of its files. |
Timeline rows that an earlier version of a page produced and its current text
@@ -2304,7 +2304,10 @@ working fence reproduces the file byte for byte. Any other difference is
named with its class (`non_fence_edit`, `unparsed_fence`, `staged_change`,
`deleted`, `not_in_head`, `unreadable_checkout`) and the file is left alone; resolve it in the clone (keep
the edit upstream, or discard it with `git checkout -- <path>`), then preview
-again. Each restored file is first backed up under
+again. A file whose HEAD bytes would not import as its page is listed under the
+hold's code (`visibility_noncanonical` for a `Visibility: private` that page privacy
+does not read) and left alone too, rows and page included; an approval saved
+before that applies as `held` with the code (#7897). Each restored file is first backed up under
`~/.gbrain/backups/url-clone-fences/`. Its rows stay active and recallable as
database-only facts, HEAD's bytes are imported as the page (as sync would
import them), and only then is the file restored; each step is idempotent, so
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 34ca15cc5c..3ebb536ca2 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -132,7 +132,7 @@ a receipt can report has a row here.
| Reason | Error code | What it means | Recovery |
| --- | --- | --- | --- |
| `writer_pool_capacity` | `writer_pool_capacity` | The canonical owner has no free publication slot right now; the write stays queued. | Wait and poll the receipt (`gbrain write-request <id>`). If it persists, check `gbrain sources writer status <source>`. |
-| <a id="visibility_not_applied"></a>`noncanonical_value`, `not_kept` | `visibility_not_applied` | A `put_page`, `edit_page` or `capture` write's frontmatter asked for `visibility: private`, but the page would have stayed world-readable, so nothing was written and no no-op was reported (#7841). An `ingest_capture` job (webhook `POST /ingest`, the ingestion daemon) refuses this request on every brain and dead-letters without a retry, its job result carrying the refusal (#7880); the webhook answers 202 before the job runs, so a sender reads the refusal from the job. `noncanonical_value`: the key or value is in another case (`Visibility: private`, `visibility: Private`) or another shape (a value on the next line, a block scalar, a list, a flow mapping, an explicit or merged key), which page privacy does not read as private. `not_kept`: the request did not survive into the page that would be stored. The check only refuses; it never widens a page or changes what a remote caller may read or write. When the content's frontmatter is unreadable or ambiguous (the importer would hold it), a private request gets the importer's `invalid_frontmatter` refusal with its reason instead; nothing is written either way. | Read the page and its revision (`gbrain get --source <id> -- <slug>`), write `visibility: private` on its own frontmatter line, lowercase, and submit `put_page` again with a new `request_id`. That is the supported way to make an existing page private, on a git-canonical source too (the page publishes database-only, see [`git_private_commit_refused`](#git_private_commit_refused)). |
+| <a id="visibility_not_applied"></a>`noncanonical_value`, `not_kept` | `visibility_not_applied` | A `put_page`, `edit_page` or `capture` write's frontmatter asked for `visibility: private`, but the page would have stayed world-readable, so nothing was written and no no-op was reported (#7841). An `ingest_capture` job (webhook `POST /ingest`, the ingestion daemon) refuses this request on every brain and dead-letters without a retry, its job result carrying the refusal (#7880); the webhook answers 202 before the job runs, so a sender reads the refusal from the job. `gbrain brainstorm` / `gbrain lsd` with `--save` and `gbrain sources reconcile` (a merge that takes a file's `Visibility: private`) refuse it on every brain too and store nothing (#7897). `noncanonical_value`: the key or value is in another case (`Visibility: private`, `visibility: Private`) or another shape (a value on the next line, a block scalar, a list, a flow mapping, an explicit or merged key), which page privacy does not read as private. `not_kept`: the request did not survive into the page that would be stored. The check only refuses; it never widens a page or changes what a remote caller may read or write. When the content's frontmatter is unreadable or ambiguous (the importer would hold it), a private request gets the importer's `invalid_frontmatter` refusal with its reason instead; nothing is written either way. | Read the page and its revision (`gbrain get --source <id> -- <slug>`), write `visibility: private` on its own frontmatter line, lowercase, and submit `put_page` again with a new `request_id`. That is the supported way to make an existing page private, on a git-canonical source too (the page publishes database-only, see [`git_private_commit_refused`](#git_private_commit_refused)). |
| `revision_required` | `revision_required` | The operation must be bound to a revision you reviewed (for example `--if-version` or `expected_revision`), and none was given: a `put_page` of a page that already exists without `expected_revision` reports this since #5385 (earlier releases said `revision_conflict`). | Preview first, then repeat with the revision the preview printed. |
| `revision_conflict` | `revision_conflict` | The page changed after the revision this write was bound to. Nothing was overwritten. | Re-read the page, merge your change, and save with the new revision. |
| `revision_changed` | `revision_changed` | An `append_page` with `expected_revision`, or a `commit_page_upload` whose session was bound to a revision, found the page at a newer revision. Nothing was appended or written, and the upload session is aborted with its staged bytes released. | Read the page again (`get_page` with `body: 'none'`), check whether the text is still missing, then append against the new revision with a new `request_id` (for an upload, begin a new session). |
@@ -230,7 +230,7 @@ with each file and fix the ones that need no guessing."*
| <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. |
| <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing, a sync request wrote its current revision, or its writer's write-through wrote that revision to the file. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one; a hold the live pass writes also names its Decision, `side` (`both`, `unknown`, `deleted`) and, for a deleted side, `state` (`tombstone_edited`, `purged_differs`, `file_gone`). Pages under `storage.keep_db` prefixes whose file is clean in committed mode are not held: the pass writes the database copy back to the file (at most 200 per pass, the rest the next pass); an uncommitted edit there is held. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. Held pages of one Decision resolve together with [`--held --side <side> [--state <state>]`](repair.md#file-drift-held). A changed file or page revision re-screens the hold by itself. |
| <a id="frontmatter_alias_limit"></a>`frontmatter_alias_limit` | A file whose exact bytes an older gbrain imported and validated nests YAML aliases in its frontmatter that expand past the size limit (#7018). This release refuses them on purpose, so only that file is held (its page keeps the last imported version) and the rest of the source syncs; it is never a parser regression. | Reduce the alias nesting in the frontmatter (or write the values out), or remove the file, then commit and `gbrain sync --source <source> --no-pull`. The hold re-screens when the file changes. Before 4b such a file stopped the source as `sync_parser_regression`; the workaround there was `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs. |
-| <a id="visibility_noncanonical"></a>`visibility_noncanonical` | The file's frontmatter asks for `visibility: private` in a spelling page privacy does not read: another case (`Visibility: private`, `visibility: Private`), a block scalar, a list, a flow mapping or a merge key. Page privacy reads only the exact lowercase key and value, so importing it would store a world-readable page its author believes is private. Git sync (classic and managed) holds the file and the rest of the source syncs; `gbrain import` (with or without a Git checkout) refuses it and imports the rest. An existing page keeps its last imported version. Company-brain connects and syncs, and the GitHub and Google connectors on a database-only source, hold it the same way (#7880). `put_page`, `edit_page`, `capture` and `ingest_capture` refuse the same request as [`visibility_not_applied`](#visibility_not_applied). Doctor `git_held_files` counts the held files and the stored pages that ask for private this way (`details.visibility_noncanonical`). | Write `visibility: private` on its own frontmatter line (lowercase key and value), commit, and run `gbrain sync --source <source> --no-pull` (or import the file again). The hold re-screens when the file changes; no frontmatter repair rewrites a privacy request. For a stored page doctor names, rewrite its frontmatter the same way with `put_page` or by editing its file. |
+| <a id="visibility_noncanonical"></a>`visibility_noncanonical` | The file's frontmatter asks for `visibility: private` in a spelling page privacy does not read: another case (`Visibility: private`, `visibility: Private`), a block scalar, a list, a flow mapping or a merge key. Page privacy reads only the exact lowercase key and value, so importing it would store a world-readable page its author believes is private. Git sync (classic and managed) holds the file and the rest of the source syncs; `gbrain import` (with or without a Git checkout) refuses it and imports the rest. An existing page keeps its last imported version. Company-brain connects and syncs, and the GitHub and Google connectors on a database-only source, hold it the same way (#7880); `gbrain repair url-clone-fences` lists a clone file whose HEAD asks for it this way under this code and leaves the file, its fence rows and the page as they are (#7897). `put_page`, `edit_page`, `capture`, `ingest_capture`, `brainstorm --save` and `sources reconcile` refuse the same request as [`visibility_not_applied`](#visibility_not_applied). Doctor `git_held_files` counts the held files and the stored pages that ask for private this way (`details.visibility_noncanonical`). | Write `visibility: private` on its own frontmatter line (lowercase key and value), commit, and run `gbrain sync --source <source> --no-pull` (or import the file again). The hold re-screens when the file changes; no frontmatter repair rewrites a privacy request. For a stored page doctor names, rewrite its frontmatter the same way with `put_page` or by editing its file. |
| <a id="parser_regression"></a>`parser_regression` | A file whose exact bytes imported under an earlier gbrain is now refused. It is held and the rest of the source syncs (the default; `GBRAIN_SYNC_PARSER_REGRESSION=stop` stops the run instead). This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. |
| <a id="settle_mismatch"></a>`settle_mismatch` | A live managed sync pass settled this file at the same level in three consecutive passes, but the next round never classified it settled (#6712). Instead of re-importing it every pass, sync held it at that level and stamped the rest of the source. The hold records the level and `meta.mismatch_streak`. The file is usually fine: a path that keeps coming back unsettled points to a broken writer, a stuck effect or a damaged record. | Run `gbrain doctor --json` and `gbrain sources writer status --source <source> --json` (both read-only), fix or report what they name with the gbrain version, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull`. A mismatch that comes back is held again after three passes. |
| <a id="write_interrupted-hold"></a>`write_interrupted` | The database ended this file's statements (a statement timeout or cancel) at every attempt, so the sync held the file and kept going. The file is fine: no repair applies, and it is not imported until it is retried. Full reference: [`write_interrupted`](#write_interrupted). | `gbrain sources writer status --source <source> --json` (read-only) names the load on the write owner; reduce it, then `gbrain sources retry-held <source>` and the same sync with its options. |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 5f57c32597..1549e98fa7 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/core/search/evidence-delivery.ts 1733 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)
src/commands/config.ts 1524 ratchet 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)
src/commands/mcp-expose.ts 1512 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)
-src/core/behavior-change-notice.ts 1535 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +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
+src/core/behavior-change-notice.ts 1537 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +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
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index aaf7bc8b2d..16e2a13474 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1337,6 +1337,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.483.0', id: 'visibility_noncanonical_hold_7848', text: 'Git sync (classic and managed) and `gbrain import` (with or without a Git checkout) hold a file whose frontmatter asks for `visibility: private` in a spelling page privacy does not read (`Visibility: private`, `visibility: Private`, a block scalar, a list, a flow mapping or a merge key) as `visibility_noncanonical` instead of storing a world-readable page; the rest of the source syncs and an existing page keeps its last imported version. Write `visibility: private` on its own frontmatter line (lowercase) and commit, or import the file again. Doctor `git_held_files` counts the held files and the stored pages that already ask for private this way (`details.visibility_noncanonical`); nothing rewrites them. On a brain without managed persistence, `gbrain put --file` and `gbrain capture --file` of a page over the single-string ceiling refuse such a request with `visibility_not_applied`, as a smaller write does.' },
// #7880 ingest_capture and company-brain imports on a brain without managed persistence. `since` is stamped at the merge slot.
{ since: '0.60.485.0', id: 'ingest_capture_private_hold_7880', text: 'On a brain without managed persistence, an `ingest_capture` job (the webhook `POST /ingest` route and the ingestion daemon) whose content asks for `visibility: private` in a spelling page privacy does not read (`Visibility: private`, `visibility: Private`, a block scalar, a list, a flow mapping or a merge key) is refused `visibility_not_applied` and dead-letters on its first attempt instead of storing a world-readable page, as a managed brain already refused it. A legacy company-brain connect or sync holds such a file as `visibility_noncanonical` instead of importing it world-readable, and the GitHub and Google connectors hold it on a database-only source as they do with a checkout. Write `visibility: private` on its own frontmatter line (lowercase) and send it again. Nothing rewrites pages already stored (#7880).' },
+ // #7897 the remaining content imports without the private-request hold. `since` is stamped at the merge slot.
+ { since: 'TBD', id: 'private_hold_sweep_7897', text: 'Three more writers refuse content that asks for `visibility: private` in a spelling page privacy does not read (`Visibility: private`, `visibility: Private`, a block scalar, a list, a flow mapping or a merge key) instead of storing a world-readable page. `gbrain repair url-clone-fences` lists such a clone file under `visibility_noncanonical` and leaves the file, its fence rows and the page alone; an approval previewed before this release applies as `held`, not `restored`. On a brain without managed persistence, `gbrain brainstorm` / `gbrain lsd` `--save` refuses it `visibility_not_applied` and exits 1, as a managed brain already did, and a save whose import is refused for another reason is reported not saved. `gbrain sources reconcile` refuses a merge that takes a file\'s `Visibility: private` with `visibility_not_applied`. Write `visibility: private` on its own frontmatter line (lowercase) and try again. Nothing rewrites pages already stored (#7897).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 624e962c17..acd7852f97 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -779,7 +779,7 @@ export const CODES = {
vector_prewarm_unsupported_engine: { class: 'caller', summary: "`gbrain embeddings prewarm` was refused because the brain is PGLite; nothing was read.", why: "Prewarm fills a Postgres server's shared_buffers so later processes find index pages cached; PGLite runs inside each gbrain process, with no server cache that outlives it.", docs: 'docs/ENGINES.md#vector-index-prewarm', suggestion: 'Nothing to do on PGLite.' },
vector_prewarm_wont_fit: { class: 'host_only', actor: 'host_admin', summary: "`gbrain embeddings prewarm` was refused before reading anything because the brain's HNSW indexes are larger than half of shared_buffers.", why: "Prewarm loads the indexes into shared_buffers, the cache Postgres sizes and keeps; past half of it the prewarm would evict heap and keyword-index pages other reads need, so the next searches would pay first-touch reads on those instead. effective_cache_size does not decide: it is a planner hint, not memory the server holds.", docs: 'docs/ENGINES.md#vector-index-prewarm', suggestion: 'Raise shared_buffers on the database host to at least twice the index size the message names and restart Postgres, or leave the indexes cold; read the fit with gbrain embeddings prewarm --dry-run --json.', fix: { argv: ['gbrain', 'embeddings', 'prewarm', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Read-only: prints the index sizes, shared_buffers, effective_cache_size and the fit, and reads no relation page.', requires_exclusive: false } },
verification_failed: { class: 'server', summary: "Source content or relationships changed during verification." },
- visibility_noncanonical: { class: 'caller', summary: "A file asks for visibility: private in a spelling page privacy does not read, so sync or import held it instead of storing it world-readable.", why: "Page privacy reads only the exact lowercase key and value visibility: private. A file that spells it another way (Visibility: private, visibility: Private, a block scalar, a list, a flow mapping or a merge key) would be stored as a world page while its author believes it is private (#7848); put_page, edit_page, capture and ingest_capture refuse the same request as visibility_not_applied.", docs: 'docs/guides/write-refusals.md#visibility_noncanonical', suggestion: 'Write visibility: private on its own frontmatter line (lowercase key and value), then commit and sync, or import the file again.' },
+ visibility_noncanonical: { class: 'caller', summary: "A file asks for visibility: private in a spelling page privacy does not read, so sync or import held it instead of storing it world-readable.", why: "Page privacy reads only the exact lowercase key and value visibility: private. A file that spells it another way (Visibility: private, visibility: Private, a block scalar, a list, a flow mapping or a merge key) would be stored as a world page while its author believes it is private (#7848); put_page, edit_page, capture, ingest_capture, brainstorm --save and sources reconcile refuse the same request as visibility_not_applied.", docs: 'docs/guides/write-refusals.md#visibility_noncanonical', suggestion: 'Write visibility: private on its own frontmatter line (lowercase key and value), then commit and sync, or import the file again.' },
visibility_not_applied: { class: 'caller', reasons: ['noncanonical_value', 'not_kept'], summary: "A page write asked for visibility: private, but the page would have stayed world-readable, so nothing was written.", why: "A write that reports success while the page stays world-readable leaves the caller believing it is hidden. Page privacy reads only the exact lowercase key and value visibility: private (#7841). When the frontmatter is unreadable or ambiguous, the write is refused invalid_frontmatter instead.", docs: 'docs/guides/write-refusals.md#visibility_not_applied', suggestion: 'Read the page and its revision, write visibility: private on its own frontmatter line (lowercase key and value), then submit again with a new request_id.', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], consent: [], actor: 'agent', why: 'Read-only: shows the page as it is now, with its revision.', requires_exclusive: false } },
withdrawal_capacity: { class: 'caller', summary: "Withdrawal capacity." },
withdrawal_mirror_failed: { class: 'unavailable', summary: "A page's Git or embedding work is withheld because its withdrawal mirror failed before rewriting the page's file; the file may still hold the withdrawn text.", why: "A withdrawal's Git and embedding effects touch only the pages whose file its mirror recorded rewriting (GBRA-130 A-12); Git never commits a page the mirror passed without rewriting its file. Retrying the request's effects reruns the mirror for this page; once the mirror commits, the withheld work is re-armed automatically.", suggestion: 'Read the parked effects with gbrain doctor --only parked_effects, fix the cause the mirror recorded, then preview gbrain sources writer retry-effects <source> --request-id <id> --dry-run and run it without --dry-run.' },