Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge origin/master (v0.60.257.0) into capy/6712-pr2-l3
garrytanf95bf1bbaa96
diff --cc CHANGELOG.mdindex 43cd153b1c,9554c2767a..610840e08e--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -10,36 -10,117 +10,147 @@@ credits are retained; no result has beeidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**Sync flags and config keys, each classified once (#6712 PR 2, L3).** Every `gbrain sync` flag is listed in one table with where it travels when a serve or PGLite owner runs the sync, so the four allowlists can no longer drift. The `sync.*` config keys are split into tunables, rollback keys and retired keys: five retired keys become `GBRAIN_SYNC_*` environment variables, and doctor names any value that stopped applying.++### What you'd see++| Situation | Before | Now |+|---|---|---|+| `gbrain config set sync.hold_cap 200` | Stored and applied | Warns that the key is retired, names `GBRAIN_SYNC_HOLD_CAP`, writes nothing (exit 0) |+| A brain with `sync.parser_regression=hold` stored | Holds the file | Stops with `sync_parser_regression` until `GBRAIN_SYNC_PARSER_REGRESSION=hold` is set; `gbrain doctor --only sync_config_keys` reports the stored value as unapplied |+| `gbrain config get sync.bulk` with nothing stored | `Config key not found` (exit 1) | `true`, with `default: sync.bulk is a rollback key ...` on stderr |+| `gbrain config set sync.foreground_priority false` | Refused as an unknown key without `--force` | Written, with a note that it is a rollback key honored until at least 2027-01-14 |+| `gbrain sync --no-lanes` while a PGLite serve holds the brain | `Unsupported owner-delegated sync option: --no-lanes` | Runs (PGLite publishes without lanes, so the flag is accepted and not sent) |+| An older sync CLI sends `explicitProcessing` to a newer serve | Silently dropped | Dropped, with one `[gbrain notice]` naming the field and its window in the serve log and the delegated run's progress lines |++### Itemized changes++- `src/core/sync-flags.ts` (new): `SYNC_FLAGS`, every sync flag with its route on the serve and owner hand-offs. `WIRE_BOOL_FLAGS`, `VALUE_FLAGS`, `IGNORED_FLAGS`, the managed pick list (`sync-delegate.ts`), `DELEGATED_SYNC_OPTION_FIELDS` (`sync-ipc.ts`), `SYNC_BOOLEAN_FLAGS` and `SYNC_VALUE_FLAGS` (`sync-wire.ts`) are views of it.+- `src/core/wire-skew.ts`: a retired wire field names the hand-offs that accept it and its shape; both validators accept, drop and report it, and the resident prints `retiredWireNotice`. `CONFIG_ROLLBACK_WINDOWS` records each rollback key's window (calendar date plus version floor).+- `src/core/sync-config-keys.ts` (new): `SYNC_TUNABLE_KEYS`, the rollback keys, `RETIRED_SYNC_KEYS` with replacements, `effectiveSyncKey` (for `config get`) and `syncKeySetNotice` (for `config set`).+- Readers: `readSyncHoldPolicy` reads the hold cap, the escalation thresholds and the parser-regression policy from `GBRAIN_SYNC_*`; `resolveBulkSettings` reads only `GBRAIN_SYNC_BULK_MAX_TXN_MS`.+- Doctor: `sync_config_keys` (meta) reports stored retired keys as unapplied and lists stored rollback keys with their windows.+- Help and printed fixes name only live keys: `--no-bulk` help, the `git_held_files` escalation line, the parser-regression hold and stop messages, the `parser_regression` registry entry.- - Docs: `docs/guides/live-sync.md#sync-config-keys`, `docs/guides/repair.md`, `docs/guides/write-refusals.md`, `docs/guides/troubleshooting.md`; migration note `skills/migrations/v0.60.256.0.md`.++- Docs: `docs/guides/live-sync.md#sync-config-keys`, `docs/guides/repair.md`, `docs/guides/write-refusals.md`, `docs/guides/troubleshooting.md`; migration note `skills/migrations/v0.60.258.0.md`.++### For contributors++- Retire a sync config key in `RETIRED_SYNC_KEYS`; `test/error-registry-retired.test.ts` then fails on any source line, help text or registered fix that still names it.+- Tests: `test/sync-flag-table-6712.test.ts`, `test/sync-config-keys-6712.test.ts`, `test/sync-managed-cron-flags-6712.test.ts`.++ ## [0.60.257.0] - 2026-10-16++ **Doctor stops reading real errors as "not migrated yet", recall and think use your query prefix everywhere, `gbrain waiting` stops listing bank alerts as people, and a surviving `gbrain serve` takes back hook IPC.** This is fix wave 18b: the older backlog nobody else had picked up, plus what wave 17 deferred. Doctor checks and four write paths used to swallow any missing column as a pre-migration brain; they now tolerate only the exact object they need and fail with the real error otherwise. `think`, `synthesize` and six more query paths embedded questions without the brain's `embedding_query_prefix`, so their retrieval drifted from hybrid search. Gmail bulk and no-reply mail opened reply-owed loops, and muting a sender left its old loops open. On Postgres, an aborted transaction left its statement running on the server.++ ### What you'd see++ | Situation | Before | Now |+ |---|---|---|+ | A doctor check hits a missing column it doesn't depend on | `ok` or `skipped` ("not migrated yet") | fails with the real database error |+ | A source's first sync is still running | `sync_freshness` reads fresh | `warn` with `sync_first_run_in_progress` |+ | A source never synced successfully | "never been synced" | fails `sync_no_successful_sync` with the last attempt and a fix for its state |+ | An adopted read-only skill pack | fails `sync_freshness` as never synced | counted under `read_only_pack_count` |+ | `gbrain sources writer activate` on a source whose Git effects stay skipped | silent | one `git_durability_not_enabled` warning per source with the enable command |+ | `think`, MCP `think`, `synthesize`, CRAG, dream auto-think, `takes search --semantic`, `search diagnose`, eval baselines, `brainstorm` on a prefix brain | query embedded without the prefix | embedded with the brain's `embedding_query_prefix`, like hybrid search |+ | A broad keyword search times out on Postgres, then runs again in the same `gbrain serve` | waits for the timeout again | answers from the vector arm with `keyword_arm_failed: skipped_after_timeout` for 10 minutes |+ | `recall --question` on a model with unmeasured fact admission floors | nothing says so | `facts_calibration: {status: "unmeasured"}` plus one info notice per session |+ | A patterns child appends a timeline entry quoting text that isn't in this run's reflections | kept as written | moved to `unverified_claims`; appended pages count in `patterns_written` |+ | Autopilot runs dream patterns again an hour later | runs | waits `dream.patterns.min_interval_hours` (default 6) and skips with `patterns_min_interval` |+ | Pages an old agent edit stamped `trust_tier: unknown` | no repair | `gbrain trust backfill --repair-unknown-markers` previews and repairs the pages you name |+ | The `embedding_model` config row has no provider prefix | managed fact extraction stops silently | doctor `embedding_identity_unqualified` names the migrate preview |+ | A bank, payment or shipping alert (`Precedence: bulk`, `List-Id`, no-reply `Reply-To`) | `gbrain waiting` lists it as a person waiting on you | no loop opens; old ones get a `gbrain loops drop sender ... --dry-run` line |+ | `gbrain loops mute sender <email>` | stops new loops only | also closes that sender's open reply-owed loops and prints the `Undo:` command |+ | The source's calendar id is one the account can't read | looks like an empty calendar | `calendar_unreadable` in the sync log, `gbrain google status` and doctor |+ | A Postgres transaction aborts while a statement waits on a lock | the statement kept running on the server | the statement is cancelled before the connection is released |+ | The first `gbrain serve` exits while a second one is running | hooks lose per-turn context until a restart | the second serve takes the IPC socket within about 30 seconds |+ | A Windows PGLite brain with a long data-dir path | IPC sockets fail to bind | sockets move under `%USERPROFILE%\.gbrain\run` |+ | `gbrain backup create` on a symlinked or over-8-GiB PGLite brain | late failure ("Out of memory") or a generic refusal | refuses up front with `unmanaged_database_path` or `backup_too_large` and a physical-copy runbook |+ | `bootstrap harness --token` on PGLite before the serve runs | exit 1, nothing wired | wires every target, exits 13 `pending_verify`; re-run once the serve is up |++ ### Things to watch++ - **Errors that used to pass now surface.** A brain with an unrelated missing column used to see doctor `ok`; it now sees the database error. Page writes, rename aliases, links preparation and Google counterparty resolution propagate any undefined table or column other than their own instead of treating it as a pre-migration brain.+ - **Prefix brains move.** On a brain with `embedding_query_prefix` set, `think`, `synthesize`, takes search and saved `gbrain eval` vector baselines return different neighbours than before.+ - **The keyword skip is per process.** `gbrain serve` and MCP benefit; one-shot CLI searches still wait for the timeout. `search.keyword_timeout_negative_cache_seconds 0` turns it off.+ - **Dropping loops by sender can't be undone.** Preview with `--dry-run` first. Muting closes loops; unmuting re-checks them on the next Gmail sync and reopens one only when nothing answered its thread since.+ - `gbrain google status` now reads each calendar once (`--no-probe` skips it) and exits 1 when one is unreadable.+ - `appended_unverified` in the dream patterns result is a deprecated alias of `quote_verify.timeline_appends` and goes away two releases from now.+ - No schema change.++ ### Itemized changes++ **Doctor and schema errors**+ - `isMissingSchemaObject` takes the exact table or column each caller needs across doctor checks (extraction sync, knowledge health, routing and federation, OAuth confidential clients, stale locks, trust scan, unclaimed sources, trust tiers) and 20+ readers. `bun run check:schema-error-predicates` blocks bare `isUndefinedTableError` / `isUndefinedColumnError` / raw `42P01` / `42703` checks outside a reasoned allowlist (#6599 follow-up).+ - `sync_freshness` separates sync outcome from freshness: `sync_first_run_in_progress`, `sync_no_successful_sync` with states `no_attempt`, `attempt_queued`, `holds_pending` and `last_attempt_unsuccessful` (#4960); read-only skill-pack catalogs are counted under `read_only_pack_count` (#6076).+ - Onboarding coverage, the MCP onboarding counts and `extract-ner` typed edges count the types the active pack declares as entities, per source; a pack that doesn't load warns `entity_types_unavailable` and `extract-ner` reports `pack_unavailable` (#4772).+ - `gbrain sources writer activate` returns `warnings[]` with `git_durability_not_enabled` per non-durable filesystem source (#5182).+ - New doctor check `embedding_identity_unqualified` (#6113).+ - New error codes: `sync_first_run_in_progress`, `sync_no_successful_sync`, `entity_types_unavailable`, `git_durability_not_enabled`, `keyword_skipped_after_timeout`, `calendar_unreadable`, `ipc_path_too_long`, `unmanaged_database_path`, `backup_too_large`.++ **Search and recall**+ - `src/core/search/query-prefix.ts`: `embedQueryWithPrefix` is used by CRAG, `synthesize`, `think` (CLI and MCP), takes search, dream auto-think, `search diagnose`, eval and `brainstorm`; `test/query-embed-call-sites.test.ts` allowlists the remaining direct `embedQuery` calls with reasons (#3783).+ - `src/core/postgres-engine/keyword-timeout-cache.ts`: a per-engine negative cache keyed on statement, parameters, source scope and timeout. Only a statement timeout (57014) records an entry, never a user cancel. New config key `search.keyword_timeout_negative_cache_seconds` (default 600, 0 off); doctor `keyword_plan` reports `details.negative_cache` (#6495).+ - `recall` reports `facts_calibration` and one `facts_calibration_unmeasured` notice per brain per session; `FACT_ADMISSION_FLOOR_EVIDENCE` moves to `search/fact-relevance.ts` (#6590).++ **Dream patterns and trust**+ - Patterns quote-verifies the timeline entries it newly published, selected by write receipt, and reports `details.timeline_appends` (#6302).+ - In-cycle cadence `dream.patterns.min_interval_hours` and a child read budget `dream.patterns.child_read_budget_kb` (default 200 KB) counted from the job's tool-execution ledger (#6297).+ - Patterns grounding and the read budget read segmented page bodies through `materializeSegmentedBody`.+ - `gbrain trust backfill --repair-unknown-markers` previews by default and applies only with `--slug` and `--expect <preview hash>`; `gbrain trust review` adds a `repair` command to the `lower_page` items the marker caused (#6550).+ - Docs: CJK fact subjects need a literal slug or a delimiter (`docs/guides/facts-relink.md`, #6620).++ **Gmail loops and calendar**+ - `Precedence`, `List-Id` and `Reply-To` are captured; positively automated mail withholds the reply-owed open with reason `automated_mail` (#5012 item 8). `gbrain loops drop sender`, mute closes and unmute re-checks, and the opt-in key `loops.updates_require_reciprocity` (default `false`).+ - `GoogleForbiddenError`, `CalendarClient.probeCalendar`, doctor `google_calendar_readable` and `gbrain sources set-calendar` (#5012 item 9).+ - `config set search.contextual_retrieval` and `sources set-cr-mode` say that existing pages keep their mode and name `gbrain repair contextual-mode` (#5012 item 6).++ **Serve, Windows, backup and harness**+ - `vendor/postgres` and `patches/[email protected]` gain `own()` cancel-and-discard; `transaction-abort.ts` cancels the running statement with a settle window, keeps the driver error as `cause` and reports a failed cancel as `cancelFailure`. Proven on direct Postgres and PgBouncer (#6598). Contributed by @Kkkkkuro (the cancel hunk of #6790).+ - Each IPC socket a serve could not bind retries every 30 seconds plus jitter through the single-owner probe (#6647).+ - Windows sockets over the 107-byte limit move to `%USERPROFILE%\.gbrain\run\<kind>-<hash12>.sock`; new doctor check `ipc_socket_path` (#6573).+ - 71 more files launch processes through `src/core/spawn.ts`, which hides the console window on Windows; 13 remain on the ratchet (#4992).+ - `gbrain backup create` checks the data-dir layout and the estimated archive size before the lock; doctor `pglite_data_dir` warns from 75% of the 8 GiB cap (#6649, which stays open for larger archives).+ - `bootstrap harness --token` on PGLite ends `pending_verify` (exit 13) when no serve answers and none holds the brain (#6661).++ **Tests**+ - Every item has a probe that fails on master and passes here. `test/e2e/persistence-chaos.test.ts` no longer races a late cancel against the commit (from GBRA-110).++ ## [0.60.256.0] - 2026-10-15++ **Session transcripts are no longer marked done with zero facts, and a write that fails after extraction stops being paid for forever.** Two corpus-sweep bugs. `gbrain bootstrap verify` ran the corpus pass in a process that could not reach the extraction model, so every pending transcript came back `chat_unavailable`, got an `.ingested` marker with zero facts, and was deleted by retention a month later (#6786). Separately, when the fact write after extraction was refused (a canonical worktree claimed but not activated), nothing recorded the window, so the `serve --http` drain paid for the same extraction every 10 minutes, for hours, and threw the error away (#6785).++ ### What you'd see++ | Situation | Before | Now |+ |---|---|---|+ | `gbrain bootstrap verify` with pending transcripts | each one marked `.ingested` with `skipped: chat_unavailable` and 0 facts | verify skips the corpus pass; the transcripts stay pending |+ | The sweep or a harvest has no usable extraction model | the file was marked done with 0 facts | the file stays pending (`corpus_chat_unavailable`) and is extracted once a model works |+ | A file an earlier build marked `skipped: chat_unavailable` | never extracted; deleted after 30 days | extracted again by the next sweeps, with its source binding and retired turns kept; kept until then (90 days by default) |+ | A source whose canonical worktree is claimed but not activated | paid for the extraction, then the write was refused, every sweep | held before any model call (`writer_coordinator_required`), naming `gbrain sources writer status <source>` |+ | A window keeps failing after its model call | paid again on every sweep, without limit | retried on the next sweep, then after 10, 20 and 40 minutes, then stopped (`corpus_window_dead_lettered`); one model or provider change retries it once |+ | Retrying stopped windows | no supported way | `gbrain sweep --retry-failed` previews, `--apply` retries (paid); `gbrain doctor` names it as the fix |+ | `serve --http` drain errors | discarded | skip reasons and failures go to serve's stderr |++ After upgrading, transcripts an earlier verify marked this way are extracted again. That is a one-time paid catch-up, bounded by the sweep's window caps (8 windows per file, 32 per sweep; `GBRAIN_CORPUS_WINDOWS_PER_SWEEP` lowers the total). `GBRAIN_SWEEP=0` or `gbrain config set facts.extraction_enabled false` pauses it. The upgrade itself rewrites nothing.++ ### Until you upgrade++ - **Stop paying for a failing extraction (#6785):** start `gbrain serve --http` with `GBRAIN_SWEEP=0` to turn its corpus drain off, or run `gbrain config set facts.extraction_enabled false` to stop all fact extraction. Turn it back on after upgrading.+ - **Keep transcripts a verify marked done (#6786):** raise `dream.synthesize.corpus_retention_days` in `~/.gbrain/config.json` (for example to 365) so retention doesn't delete them before this release extracts them. Avoid `gbrain bootstrap verify` while transcripts are pending.++ ### Itemized changes++ - `src/core/context/corpus-segments.ts`: `corpusFileCompletion` is the one completion classifier for sweep selection, the under-claim re-check, retention GC, the HTTP drain and the doctor backlog, so a rewritten file counts as pending everywhere. A sidecar whose `skipped` is `chat_unavailable` is pending, and only finished files get the plain retention; unavailable, partial and rewritten files keep the un-ingested ceiling. The failure record format (`<file>.failures.json`, `CORPUS_WINDOW_FAILURE_CAP` 5) lives here too, and the session-end hook reaps it with its `.txt`.+ - `src/core/context/corpus-windows.ts`: `runCorpusWindows` returns `unavailable` without recording the window, and rewinds a progress an earlier build finished as `chat_unavailable` to its retired turns under the same compare-and-set that takes the lease. A failure thrown after an admitted chat call counts against the window's start and the source incarnation, and so does a paid window whose progress could not be committed; an extraction refused by the spend guard before any chat call was admitted, or replayed without a model call, does not count. Neither tail growth, an edit to an earlier turn nor the error label resets the count; a commit of that window, or a rewrite that removes it, clears it. Selection serves backing-off and stopped files after every other candidate, so they never take a whole batch. One change of the extraction-config fingerprint (model, provider, key presence; no values) re-arms a stopped window once.+ - `src/core/sweep.ts`: the corpus pass runs the facts-absorb owner-readiness preflight (#5362) per source before any model call, applies the failure cap to writeback turn files as well, stops the pass on `chat_unavailable`, charges every attempted window (a thrown one included) against the per-sweep total, and logs thrown errors with their code. `corpus: false` skips the pass. `armCorpusDrain` logs the sweep's diagnostics (each distinct line once) and its skip reasons whenever they change.+ - `src/core/context/checkpoint-harvest.ts`: the compact and writeback lanes run the same preflight and the same failure cap; neither writes a receipt or sidecar for an `unavailable`, backing-off or stopped window.+ - `src/core/context-engine.ts`: the OpenClaw `compact()` inline harvest on Postgres (rung 3) runs the same preflight, records a failed paid attempt where the sweep's cap reads it and then leaves that segment to the sweep, keeps a `chat_unavailable` segment pending, and records any other skip reason in its sidecar.+ - `src/core/bootstrap/verify.ts`: the in-process sweep runs passes 1 and 2 only.+ - `gbrain sweep --retry-failed [--apply] [--json]` (`src/commands/sweep.ts`); doctor `memory_writeback` warns about stopped windows and names `gbrain sweep --retry-failed --apply` (paid) as its fix. `corpus_chat_unavailable`, `corpus_window_backoff` and `corpus_window_dead_lettered` are registered, so `gbrain errors <code>` explains them.+ - Tests: `test/sweep-corpus-chat-unavailable-6786.test.ts` (unservable model in the sweep and the compact harvest; legacy sidecars with and without `.progress`, asserting the facts exist; GC then sweep and sweep then GC with an aged file), `test/sweep-corpus-failure-cap-6785.test.ts` (a claim landing mid-call, the harvest preflight, the drain log, the retry schedule, the re-arm, doctor's fix and the operator retry, stopped files ahead of a healthy one, the window total under thrown windows, an uncommitted paid window, a refused call, a chat call followed by a refused one, an unpaid replay, the writeback harvest cap, and the drain and backlog classifier with a stale record) and two rung-3 cases in `test/e2e/context-engine-rung3-extraction.test.ts`. A new `bootstrap-verify.serial.test.ts` case runs the real verify with a keyed report and no gateway. The new behavior cases fail on the previous tree.+## [0.60.255.0] - 2026-10-16**One drainer per managed source, one cursor per source, and a resume never refuses over processing flags (#6712 PR 1).** Two processes could drain one source at once (a cron `gbrain sync` beside a serve, a `--no-delegate` run beside a job), racing each other's checkpoints, and every writer, authority and option set got its own cursor, so a resume by a different process started over or refused with `cursor_processing_options_conflict`. Now every managed pass runs under the source's drain lease, a second run follows the holder instead of competing, the cursor key is the source itself, and the cursor's opt-outs are inherited.diff --cc docs/architecture/key-files/agent-bootstrap-continued.mdindex 3f2413ce53,fd04394e40..12b7248ba8--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@@ -21,10 -21,10 +21,10 @@@- Read-time TTL validity (there is no sweeper): ACTIVE fact reads in BOTH engines (`listFactsByEntity/Since/BySession`, every `findCandidateDuplicates` arm, `countUnconsolidatedFacts`, `getFactsHealth` active buckets) carry `AND (valid_until IS NULL OR valid_until > now())` — `valid_until` is temporal validity, not retention; history paths (`listSupersessions`, `findTrajectory`, `--asof`) deliberately still see lapsed rows; a re-stated expired fact re-inserts fresh. Pinned by `test/facts/ttl-validity.test.ts` + engine-parity additions.- Diagnostics: `src/commands/doctor/checks/memory-writeback.ts` (`memory_writeback`, BRAIN category) — quiet-ok when off, but the OFF branch still probes receipt + canonical instruction paths and WARNS on a lingering block (off-but-still-instructing) with the converge command; plane-compare warns when the file mirror disagrees with the DB row (the Stop hook acting on the wrong truth) naming the re-sync; a read_error reports the state as UNKNOWN, never "off (default)"; resolved bundle + BOTH visibility postures + audience/reasons; on both branches an explicit private `facts.default_visibility` on a non-shared brain with remote readers (a harness receipt, or HTTP MCP clients active in 30d; listed in `private_default_remote_readers`) warns with the shared `PRIVATE_DEFAULT_REMOTE_CONSEQUENCE` text (`writeback-config.ts`), the same text `bootstrap harness` prints before consent; instruction blocks receipt-vs-live-probe-vs-drift compare (drift fix names the `config set` + `bootstrap harness` combo — the config set re-stamps the posture mirror so the re-render converges even after an out-of-band visibility flip) + AGENTS.override.md detection — and a receipt target in state `failed` is a STANDING warn regardless of the live probe (the one physical-survival path — a smoke-rollback strip that itself threw — leaves a current-looking block directing sessions at a rolled-back endpoint, and only the receipt state knows) naming the `bootstrap harness --yes` / `--remove` converge; validity-lapsed count; 7d counters (verbs usage sidecar's additive `remember_status` [stamped in `src/mcp/dispatch.ts`, ALL-MCP-callers semantics labeled honestly] + `writeback`/`writeback-bank` heartbeat events; `turns_banked` counts flush_skip_* — banked, enqueue declined); when at least 10 serve-side harvests finished (ok + error; a `writer_busy_requeued` retry is not finished) in those 7d and more than 20% failed, a warn names the failure count, the top error reason and the `gbrain sweep --once` recovery; `details.corpus_backlog` counts corpus files with no `.ingested` sidecar (pending, oldest age, past retention, deletion day) and, with writeback on, warns once one is past plain retention (E-N1) with the local/lossy disclosure. Null-engine runs report the file mirror honestly. `cross_lane_duplicates_7d` / `near_duplicates_shadow_7d` sum the `writeback_dedup` heartbeat events in both the on and off branches.- Tests: `test/writeback-config.test.ts`, `test/mcp-instructions-writeback.test.ts`, `test/facts/writeback-gate.test.ts`, `test/hook-writeback-stop.serial.test.ts`, writeback-lane cases in `test/checkpoint-harvest.serial.test.ts`, `test/bootstrap-instructions-block.test.ts` + harness serial additions, `test/writeback-nudge.serial.test.ts`, `test/doctor-memory-writeback.test.ts`, the hermetic 5-step `test/ambient-writeback-lifecycle.serial.test.ts`, and the NON-GATING real-codex door (`test/e2e/bootstrap-real-codex.serial.test.ts`, ambient-writeback describe).- - `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no `.ingested` sidecar; never overlaps itself; pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window's facts batch is keyed by its text (the sweep passes `reAdmitFileRefusals`), so when the canonical file check refused some of its entity requests, `resumeManagedFacts` admits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned by `test/managed-sweep-refused-window-retry.test.ts`.- - `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `retireCorpusFile` / `retireCorpusTurns` (#6091) record a file or its off-period turns as finished without extracting (`skipped_reason`; a retire overrides another extractor's lease, and a later rewrite extracts only unrecorded turns). `parseCorpusTurns` (defined in the provider-free `corpus-turns.ts`, re-exported here) splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended` with cumulative counts; an aborted window records nothing and transport errors release the lease and throw. `finishedCorpusFileState` decides `.ingested` files by stat compare (no rehash); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).+ - `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no final `.ingested` sidecar; never overlaps itself; its sweep diagnostics and thrown ticks reach stderr, each distinct line once per run, plus the skip reasons whenever their set changes (#6785); pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `bootstrap verify` runs the sweep in-process with `corpus: false` (#6786: its engine has no configured gateway, so every window answered `chat_unavailable`). Before any model call the corpus pass runs the facts-absorb owner-readiness preflight per source (`assertSourceLegacyWriter` in `persistence/filesystem-guard.ts`): a claimed, not activated canonical worktree skips the file as `writer_coordinator_required` and logs `gbrain sources writer status <id>` (#6785; the compact and writeback harvest lanes do the same). A `chat_unavailable` result is not terminal: the windowed file or `.wb-` turn keeps no sidecar, nothing is recorded, and the pass stops (`corpus_chat_unavailable`). Failures thrown after a chat call are counted per window (`<file>.failures.json`, see `corpus-windows.ts`) and skipped as `corpus_window_backoff` / `corpus_window_dead_lettered`; `gbrain sweep --retry-failed [--apply]` previews or clears them (doctor `memory_writeback` names the paid retry as its fix). Pinned by `test/sweep-corpus-chat-unavailable-6786.test.ts` and `test/sweep-corpus-failure-cap-6785.test.ts`. `gbrain sweep --once` is the trusted CLI seam for operator catch-up runs (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window's facts batch is keyed by its text (the sweep passes `reAdmitFileRefusals`), so when the canonical file check refused some of its entity requests, `resumeManagedFacts` admits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned by `test/managed-sweep-refused-window-retry.test.ts`.+ - `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `retireCorpusFile` / `retireCorpusTurns` (#6091) record a file or its off-period turns as finished without extracting (`skipped_reason`; a retire overrides another extractor's lease, and a later rewrite extracts only unrecorded turns). `parseCorpusTurns` (defined in the provider-free `corpus-turns.ts`, re-exported here) splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended`/`changed`/`source_changed`/`unavailable`/`backoff`/`dead_lettered` with cumulative counts; an aborted or `unavailable` window records nothing, and a progress a pre-#6786 build finished with `skipped_reason: chat_unavailable` is rewound under the lease CAS to its retired turns (source binding, totals and links kept). Transport and write errors release the lease and throw; one thrown after a chat call (`extractUnderFailureCount`, observed through the AI invocation preflight) counts against the window's start key (`<turn sha256>@<offset>`) and source incarnation in `<file>.failures.json`: retried on the next sweep, then after 10, 20 and 40 minutes (`CORPUS_WINDOW_RETRY_BASE_MS`), stopped at `CORPUS_WINDOW_FAILURE_CAP` (5); tail growth and error labels never reset it, a commit of that window removes it, and one change of `extractionConfigFingerprint` (model, provider, key presence) re-arms a stopped window once (#6785). `corpusFileCompletion` in `corpus-segments.ts` is the one completion classifier (selection, the under-claim re-check, retention GC; `corpusSidecarState` for the drain and the doctor backlog): a `chat_unavailable` sidecar is pending, and only `done`/`legacy` files get the plain retention (#6786); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).- `src/core/context/corpus-source.ts` — #6268, the session's source for every corpus file. Writers (`hook.ts` compact/stop/session-end, the OpenClaw `compact()`) call `openSessionCorpus`, which freezes one source per session at first use (GBRAIN_SOURCE, then the `.gbrain-source` dotfile, else unresolved) into `<sid>.source.json` in the `sourced/` spool and stamps it into the file name (`.src-<id>`, `default` included; `_unresolved` cannot collide with a real id). Pre-stamp sweepers never list the spool. `resolveCorpusFileSource` is the sweep/harvest/serve read: the stamp or frozen record, else the brain's cwd chain once (frozen, tier `engine`); legacy top-level files are held (`corpus_legacy_unstamped`) unless a legacy wb stamp, a frozen record or a single-source brain proves the source, never assigned the pass source. The first engine resolution binds the source incarnation; a recreated source holds the session (`corpus_source_incarnation_changed`). `gbrain sweep --assign-corpus <source>` is the operator mapping (preview, then `--apply`); doctor `memory_writeback` reports `details.corpus_source_holds`. Tests: `test/corpus-source-stamp.test.ts`.-- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). #6317 (D1 a′), managed Postgres brains: `maybeDelegateManagedSyncToServe(engine, args, opts)` runs post-connect from `runSingleSourceSync` right before `performSync`; it probes the host's live full `serve` consumer through `persistence_consumers` (`consumer-heartbeat.ts`, the database, never a socket), admits the catch-up's flags (`--no-bulk`, `--lanes`/`--no-lanes`, `--json`, the processing flags), sends the CLI's durable `cli` registration in `sync_start`, prints the drain's own numbered lines from `sync_status` (`managed`, `lines`, `drain`, `next`) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (`withVerifiedLocalRegistration`) and runs `performSync({ drain: true })` as that writer under `withHumanLineSink`; the shared-secret lane stays under `withLegacySyncDelegation` and is still refused on a managed brain; a denied, revoked or stdio registration answers `sync_start` with `permission_denied` and the envelope (`refusal`), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch, `stale_serve` / `unsupported_kind` from an older serve, `source_mismatch`, a serve lost mid-drain) runs without the serve with one actionable line; only the opt-out, a serve not answering its socket and a `stale_serve` serve call `forceOwnConsumer` (#6543), the rest admit writes the serve consumes under `persistence.single_consumer`. #6712 PR 1: neither builder sends `explicitProcessing` any more; the serve validates one from an older CLI by shape and drops it (`WIRE_SKEW_WINDOWS` in `src/core/wire-skew.ts`), and a resume inherits the cursor's processing opt-outs. The serve's delegated run follows the source's drain lease as holder `serve` (`followDrainLease`, `drainHolder`). Wire `embedDeferred` (sent only when true) carries the cost gate's runtime deferral, so adopting a cursor that stores `noEmbed=false` never embeds in that run. `maybeDelegateManagedSyncToServe` refuses `--skip-failed` / `--include-gitignored` on a managed source with `managed_sync_flag_refused` before any probe or socket call (`test/sync-delegated-options-6696.serial.test.ts`, `test/sync-managed-forbidden-flags-6696.test.ts`). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/serve-sync-handoff.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step) and `test/e2e/serve-delegated-managed-sync.serial.test.ts` (Postgres, spawned serve, MCP latency printed).+- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: `DELEGATED_SYNC_OPTION_FIELDS` (the fields `SYNC_FLAGS` in `src/core/sync-flags.ts` forwards through the serve, plus `sourceId`, `embedDeferred`, `timeoutSeconds` and `origin`) drives the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). #6317 (D1 a′), managed Postgres brains: `maybeDelegateManagedSyncToServe(engine, args, opts)` runs post-connect from `runSingleSourceSync` right before `performSync`; it probes the host's live full `serve` consumer through `persistence_consumers` (`consumer-heartbeat.ts`, the database, never a socket), admits the catch-up's flags (`--no-bulk`, `--lanes`/`--no-lanes`, `--json`, the processing flags), sends the CLI's durable `cli` registration in `sync_start`, prints the drain's own numbered lines from `sync_status` (`managed`, `lines`, `drain`, `next`) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (`withVerifiedLocalRegistration`) and runs `performSync({ drain: true })` as that writer under `withHumanLineSink`; the shared-secret lane stays under `withLegacySyncDelegation` and is still refused on a managed brain; a denied, revoked or stdio registration answers `sync_start` with `permission_denied` and the envelope (`refusal`), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch, `stale_serve` / `unsupported_kind` from an older serve, `source_mismatch`, a serve lost mid-drain) runs without the serve with one actionable line; only the opt-out, a serve not answering its socket and a `stale_serve` serve call `forceOwnConsumer` (#6543), the rest admit writes the serve consumes under `persistence.single_consumer`. #6712 PR 1: neither builder sends `explicitProcessing` any more; the serve validates one from an older CLI by shape and drops it (`WIRE_SKEW_WINDOWS` in `src/core/wire-skew.ts`), and a resume inherits the cursor's processing opt-outs. #6712 PR 2: `WIRE_BOOL_FLAGS` / `VALUE_FLAGS` / `IGNORED_FLAGS` and the managed pick list are views of `SYNC_FLAGS`; a retired field the validator drops comes back as `ignored`, and the serve logs `retiredWireNotice` and streams it to the older client as a progress line (`test/sync-flag-table-6712.test.ts`). The serve's delegated run follows the source's drain lease as holder `serve` (`followDrainLease`, `drainHolder`). Wire `embedDeferred` (sent only when true) carries the cost gate's runtime deferral, so adopting a cursor that stores `noEmbed=false` never embeds in that run. `maybeDelegateManagedSyncToServe` refuses `--skip-failed` / `--include-gitignored` on a managed source with `managed_sync_flag_refused` before any probe or socket call (`test/sync-delegated-options-6696.serial.test.ts`, `test/sync-managed-forbidden-flags-6696.test.ts`). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/serve-sync-handoff.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step) and `test/e2e/serve-delegated-managed-sync.serial.test.ts` (Postgres, spawned serve, MCP latency printed).- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.- `src/core/readiness.ts` — capability readiness (agent operator contract A7): `ReadinessEntry {capability, state, reason, why, fix, tier, asset?, http_visible}` for embeddings, chat_llm, writeback, tool_surface, sync, harness_wiring (config tier) and worker, backup per asset, migrations, sync (probed tier); each capability's reasons are a closed exported const (`EMBEDDINGS_REASONS`, …). `configReadiness(cfg, {transport})` is synchronous and memoized per (config object, transport); its only file read is one memoized `peekLock()` (none when this process holds the lock, via `heldLockFor`), plus one process-wide gbrain-binary PATH lookup on the CLI transport only. The HTTP view drops `http_visible:false` entries and passes the rest through `redactForTransport`. `probedReadiness(engine, {cache})` never calls `getStats`/`getHealth`; 60 s cache (`createReadinessCache()` per ServeHttpContext, process-wide otherwise), single-flight, 2 s per-probe bound, stale-while-revalidate; `readinessTail` is MCP initialize's best-effort 250 ms tail. `embeddingEnablement(cfg)` is the one "turn on embeddings" fix: resolves the datastore (PGLite path, Postgres, a mount from `--brain`/`GBRAIN_BRAIN_ID`) and the column width, picks a keyed provider that fits (or asks for a key with `inputs`), and emits in-place `init --force --embedding-model … --embedding-dimensions … [--path …]` or, for a mount, `embeddings enable --brain …`; it never rebuilds a column. `exclusiveFix` turns an exclusive fix into a two-step plan (actor `user` stops the owning serve named by `lock_owner`, `then` the command) unless the command delegates to the owner. A live status-only `serve --http` marker (`liveStatusMarkers`, config plane) makes CLI `harness_wiring` `serve_status_only` with `transport: 'http'` and the status reason's fix (`httpStatusServerEntry`, shared with doctor), never "start `gbrain serve --http`" on the port it holds. `harnessWiringEntry` builds harness-native stdio registration (absolute binary, `stdioServeArgv` with `REGISTRATION_SURFACE` = `starter`, or `input.surface` from `gbrain init --surface`; `configReadiness(cfg, {transport, surface})` skips the memo when a surface is passed), shared-HTTP `bootstrap harness`, or the MEMORY_VERBS install anchor, with effects and destinations disclosed. Consumers never coach on `disabled_by_choice`. Tests: `test/readiness.test.ts`, `test/readiness-http-cost.test.ts`, `test/readiness-advice-lint.test.ts` (no hand-written enablement advice outside this module; shrink-only baseline), `test/readiness-embedding-enablement.serial.test.ts` (the E2E matrix).- Secret and sensitivity scanning (`src/core/secret-scan.ts`, `src/core/secret-scan-allowlist.ts`, `src/core/secret-scan-work.ts`, `src/core/context/sensitivity-scan.ts`): see [secret-scan.md](secret-scan.md).diff --cc docs/guides/live-sync.mdindex 62806f93c2,5fe8392981..f15cb30f83--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@@ -115,35 -115,9 +115,35 @@@ Timing knobs the drain uses| `preparation_deadlines` write switch (`persistence.preparation_deadlines`, `GBRAIN_PREPARATION_DEADLINES`) | Kill switch for the four keys above and the attempt counter. `remember`, `put_page` and `edit_page` keep their own 30 s budget either way. | on | `gbrain config set persistence.preparation_deadlines false` (or `GBRAIN_PREPARATION_DEADLINES=0`) restores the previous behaviour exactly: no deadline on sync or maintenance writes, no counter, no `preparation_stalled` holds. A running `serve` picks the change up within 5 seconds. || Page write wait | One page's (or group's) publication before the drain re-checks. | 30 s inside a drain (5 s, checkpoint 8 s, for a single pass) | The drain re-enters; this is not a stop. || `sync` job deadline | A managed `sync` Minions job's drain: its `timeout_ms` (autopilot stamps `max(2 × --interval, 300 s)`), or the queue's wall-clock limit for a job without one, capped at an hour, less a 60 s reserve. `sync.job_drain=false` (or job data `drain: false`) keeps the single pass. | per job | Stops as `resumable` / `deadline`; on a worker-backed brain a stop that is safe to repeat queues one follow-up job (`continuation_job_id`). |- | `GBRAIN_SYNC_BULK_MAX_TXN_MS` (was `sync.bulk_max_txn_ms`, retired in 0.60.256.0) | Target time per bulk group; sizes the next group from the last one's time per page. | 15000 | A smaller next group. |-| `sync.bulk_max_txn_ms` / `GBRAIN_SYNC_BULK_MAX_TXN_MS` | Target time per bulk group; sizes the next group from the last one's time per page. | 15000 | A smaller next group. |++| `GBRAIN_SYNC_BULK_MAX_TXN_MS` (was `sync.bulk_max_txn_ms`, retired in 0.60.258.0) | Target time per bulk group; sizes the next group from the last one's time per page. | 15000 | A smaller next group. || `sync.bulk_size` / `GBRAIN_SYNC_BULK_SIZE` | Largest bulk group. | 16 | — |+### Sync config keys++`gbrain config` keeps three kinds of `sync.*` keys (`src/core/sync-config-keys.ts`):++- **Tunables** you set and keep: `sync.bulk_size`, `sync.lanes`, `sync.exclude`, `sync.include_hidden`,+ `sync.include_working_tree`, `sync.holds`, `sync.write_through`, `sync.cost_gate_min_usd`.+- **Rollback keys**, the way back a notice or migration promised: `sync.job_drain`, `sync.foreground_priority`,+ `sync.federated_v2`, `sync.waive_batch`, `sync.bulk`. Each one set to `false` restores the earlier behavior, and+ stays honored until at least 2027-01-14 (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts`). They are not+ tunables: `config set` says so, and no help text or printed fix recommends them.- - **Retired keys**, no longer read since 0.60.256.0, each with an environment variable for the process that syncs++- **Retired keys**, no longer read since 0.60.258.0, each with an environment variable for the process that syncs+ (the serve when it runs the catch-up, the cron line or the shell):++| Retired key | Replacement | Default |+|---|---|---|+| `sync.bulk_max_txn_ms` | `GBRAIN_SYNC_BULK_MAX_TXN_MS` | 15000 |+| `sync.hold_cap` | `GBRAIN_SYNC_HOLD_CAP` | 500 |+| `sync.hold_escalate_count` | `GBRAIN_SYNC_HOLD_ESCALATE_COUNT` | 50 |+| `sync.hold_escalate_pct` | `GBRAIN_SYNC_HOLD_ESCALATE_PCT` | 5 |+| `sync.parser_regression` | `GBRAIN_SYNC_PARSER_REGRESSION` | stop |+| `sync.knock_on_refreeze_limit`, `sync.knock_on_run_limit` | none (removed with the knock-on re-freeze in 0.60.255.0) | — |++`gbrain config set` of a retired key warns, names the variable and writes nothing. `gbrain config get <key>` prints+the value a sync runs with for a retired or rollback key and, on stderr, where it comes from. `gbrain doctor`+(`sync_config_keys`) reports a retired key still stored on the brain as unapplied.+### One consumer per hostEvery gbrain process that waits on a managed write starts a *persistencediff --cc docs/guides/repair.mdindex 589224659a,30a5e9f887..32dd5587e9--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@@ -1426,16 -1426,14 +1426,16 @@@ gbrain sync --source notes --no-pull --Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck);reference: [`preparation_stalled`](write-refusals.md#preparation_stalled).-Settings, all read by every sync:+Settings, all read by every sync (`sync.holds` is a brain config key; the `GBRAIN_SYNC_*` variables are read from the+environment of the process that syncs and replace the `sync.hold_*` and `sync.parser_regression` keys retired in- 0.60.256.0, see [sync config keys](live-sync.md#sync-config-keys)):++0.60.258.0, see [sync config keys](live-sync.md#sync-config-keys)):-| Key | Default | Effect |+| Setting | Default | Effect || --- | --- | --- || `sync.holds` | `hold` | `fail` makes sync fail closed: a content refusal blocks the sync. |-| `sync.hold_cap` | `500` | How many holds a sync result lists in detail; storage is never capped and valid files always import. |-| `sync.hold_escalate_count` / `sync.hold_escalate_pct` | `50` / `5` | A source holding more files, or a run holding more than that share of at least 40 screened imports, reports `holds_escalated` and doctor `git_held_files` fails. A run whose `preparation_stalled` holds would cross it stops as `preparation_systemic` instead of holding them. |-| `sync.parser_regression` | `stop` | `hold` holds a file whose exact bytes imported under an earlier gbrain (`parser_regression`) instead of stopping the run with `sync_parser_regression`. |+| `GBRAIN_SYNC_HOLD_CAP` | `500` | How many holds a sync result lists in detail; storage is never capped and valid files always import. |+| `GBRAIN_SYNC_HOLD_ESCALATE_COUNT` / `GBRAIN_SYNC_HOLD_ESCALATE_PCT` | `50` / `5` | A source holding more files, or a run holding more than that share of at least 40 screened imports, reports `holds_escalated` and doctor `git_held_files` fails. A run whose `preparation_stalled` holds would cross it stops as `preparation_systemic` instead of holding them. |+| `GBRAIN_SYNC_PARSER_REGRESSION` | `stop` | `hold` holds a file whose exact bytes imported under an earlier gbrain (`parser_regression`) instead of stopping the run with `sync_parser_regression`. |To prevent new broken files, write brain files through `put_page`/`capture`or a YAML serializer, check generated content withdiff --cc llms-full.txtindex 4d9fd3772e,f29ea69506..8afaa01c9d--- a/llms-full.txt+++ b/llms-full.txt@@@ -6675,35 -6715,9 +6715,35 @@@ Timing knobs the drain uses| `preparation_deadlines` write switch (`persistence.preparation_deadlines`, `GBRAIN_PREPARATION_DEADLINES`) | Kill switch for the four keys above and the attempt counter. `remember`, `put_page` and `edit_page` keep their own 30 s budget either way. | on | `gbrain config set persistence.preparation_deadlines false` (or `GBRAIN_PREPARATION_DEADLINES=0`) restores the previous behaviour exactly: no deadline on sync or maintenance writes, no counter, no `preparation_stalled` holds. A running `serve` picks the change up within 5 seconds. || Page write wait | One page's (or group's) publication before the drain re-checks. | 30 s inside a drain (5 s, checkpoint 8 s, for a single pass) | The drain re-enters; this is not a stop. || `sync` job deadline | A managed `sync` Minions job's drain: its `timeout_ms` (autopilot stamps `max(2 × --interval, 300 s)`), or the queue's wall-clock limit for a job without one, capped at an hour, less a 60 s reserve. `sync.job_drain=false` (or job data `drain: false`) keeps the single pass. | per job | Stops as `resumable` / `deadline`; on a worker-backed brain a stop that is safe to repeat queues one follow-up job (`continuation_job_id`). |- | `GBRAIN_SYNC_BULK_MAX_TXN_MS` (was `sync.bulk_max_txn_ms`, retired in 0.60.256.0) | Target time per bulk group; sizes the next group from the last one's time per page. | 15000 | A smaller next group. |-| `sync.bulk_max_txn_ms` / `GBRAIN_SYNC_BULK_MAX_TXN_MS` | Target time per bulk group; sizes the next group from the last one's time per page. | 15000 | A smaller next group. |++| `GBRAIN_SYNC_BULK_MAX_TXN_MS` (was `sync.bulk_max_txn_ms`, retired in 0.60.258.0) | Target time per bulk group; sizes the next group from the last one's time per page. | 15000 | A smaller next group. || `sync.bulk_size` / `GBRAIN_SYNC_BULK_SIZE` | Largest bulk group. | 16 | — |+### Sync config keys++`gbrain config` keeps three kinds of `sync.*` keys (`src/core/sync-config-keys.ts`):++- **Tunables** you set and keep: `sync.bulk_size`, `sync.lanes`, `sync.exclude`, `sync.include_hidden`,+ `sync.include_working_tree`, `sync.holds`, `sync.write_through`, `sync.cost_gate_min_usd`.+- **Rollback keys**, the way back a notice or migration promised: `sync.job_drain`, `sync.foreground_priority`,+ `sync.federated_v2`, `sync.waive_batch`, `sync.bulk`. Each one set to `false` restores the earlier behavior, and+ stays honored until at least 2027-01-14 (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts`). They are not+ tunables: `config set` says so, and no help text or printed fix recommends them.- - **Retired keys**, no longer read since 0.60.256.0, each with an environment variable for the process that syncs++- **Retired keys**, no longer read since 0.60.258.0, each with an environment variable for the process that syncs+ (the serve when it runs the catch-up, the cron line or the shell):++| Retired key | Replacement | Default |+|---|---|---|+| `sync.bulk_max_txn_ms` | `GBRAIN_SYNC_BULK_MAX_TXN_MS` | 15000 |+| `sync.hold_cap` | `GBRAIN_SYNC_HOLD_CAP` | 500 |+| `sync.hold_escalate_count` | `GBRAIN_SYNC_HOLD_ESCALATE_COUNT` | 50 |+| `sync.hold_escalate_pct` | `GBRAIN_SYNC_HOLD_ESCALATE_PCT` | 5 |+| `sync.parser_regression` | `GBRAIN_SYNC_PARSER_REGRESSION` | stop |+| `sync.knock_on_refreeze_limit`, `sync.knock_on_run_limit` | none (removed with the knock-on re-freeze in 0.60.255.0) | — |++`gbrain config set` of a retired key warns, names the variable and writes nothing. `gbrain config get <key>` prints+the value a sync runs with for a retired or rollback key and, on stderr, where it comes from. `gbrain doctor`+(`sync_config_keys`) reports a retired key still stored on the brain as unapplied.+### One consumer per hostEvery gbrain process that waits on a managed write starts a *persistencediff --cc scripts/module-size-limits.tsvindex 3016beb807,a9be5ee6df..275d278a96--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@@ -43,7 -43,7 +43,7 @@@ src/core/oauth-provider.ts 1236 ratchesrc/core/ops/pages.ts 707 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707src/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part)src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)- src/commands/doctor/checks/extraction-sync.ts 1523 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts+ src/commands/doctor/checks/extraction-sync.ts 1543 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts)src/core/search/evidence-delivery.ts 1673 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)- src/commands/config.ts 1509 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 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig)-src/commands/config.ts 1509 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)++src/commands/config.ts 1510 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)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)diff --cc skills/migrations/v0.60.258.0.mdindex 6e561fa664,0000000000..24499e4bf9mode 100644,000000..100644--- a/skills/migrations/v0.60.258.0.md+++ b/skills/migrations/v0.60.258.0.md@@@ -1,53 -1,0 +1,53 @@@- # Upgrade to v0.60.256.0: retired sync config keys move to environment variables++# Upgrade to v0.60.258.0: retired sync config keys move to environment variables++Five `sync.*` config keys are no longer read: `sync.bulk_max_txn_ms`, `sync.hold_cap`,+`sync.hold_escalate_count`, `sync.hold_escalate_pct` and `sync.parser_regression`. Each one is now an environment+variable of the process that syncs. A value stored on the brain before the upgrade stays in the config table but is+not applied, so a brain that tuned one of them runs with the default until the variable is set. No schema migration,+and the upgrade rewrites no rows.++1. **Finish the upgrade.** `gbrain upgrade` runs it. To be sure, on the brain host:+ ```bash+ gbrain apply-migrations --yes --no-autopilot-install+ ```++2. **Find values that stopped applying.**+ ```bash+ gbrain doctor --only sync_config_keys --json+ ```+ `ok` means nothing to do. `warn` lists each stored retired key with the value in effect now and the variable that+ replaces it:++ | Retired key | Environment variable | Default |+ |---|---|---|+ | `sync.bulk_max_txn_ms` | `GBRAIN_SYNC_BULK_MAX_TXN_MS` | 15000 |+ | `sync.hold_cap` | `GBRAIN_SYNC_HOLD_CAP` | 500 |+ | `sync.hold_escalate_count` | `GBRAIN_SYNC_HOLD_ESCALATE_COUNT` | 50 |+ | `sync.hold_escalate_pct` | `GBRAIN_SYNC_HOLD_ESCALATE_PCT` | 5 |+ | `sync.parser_regression` | `GBRAIN_SYNC_PARSER_REGRESSION` | stop |++ `gbrain config get <key>` prints the value in effect for one key and, on stderr, where it comes from.++3. **Ask the user before carrying a value over.** Whether to keep a tuned value is the user's call. If they want to,+ set the variable where the sync runs: the environment of `gbrain serve` when it runs the catch-up for the CLI,+ the cron line (`GBRAIN_SYNC_HOLD_CAP=200 gbrain sync --all --no-pull --hard-deadline 13m`), or the shell. Then+ remove the stored key so doctor stops reporting it:+ ```bash+ gbrain config unset sync.hold_cap+ ```+ `gbrain config set` of a retired key now warns, names the variable and writes nothing (exit 0).++4. **Rollback keys keep working.** `sync.job_drain`, `sync.foreground_priority`, `sync.federated_v2`,+ `sync.waive_batch` and `sync.bulk` are the ways back that earlier notices named. They stay readable and honored+ until at least 2027-01-14; `config set` writes them with a note saying so. They are not tunables, so do not+ suggest them for tuning. `sync.foreground_priority` is now accepted without `--force`.++5. **Older sync clients.** A serve or PGLite owner on this release accepts `explicitProcessing` from a sync CLI below+ 0.60.255.0 until 2026-11-14, ignores it and prints one `[gbrain notice]` naming it. Upgrade every machine that runs+ `gbrain sync` against this brain. The PGLite owner lane now accepts `--lanes N` and `--no-lanes` (it ignores them:+ PGLite publishes without lanes) instead of refusing them.++Verify:+```bash+gbrain doctor --only sync_config_keys --json # ok, or only the keys the user chose to keep stored+```diff --cc skills/skills.lock.jsonindex a2bc812a99,6afa1a7cb1..0762d31f52--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@@ -157,7 -157,6 +157,7 @@@"migrations/v0.60.102.0.md": "be46986da0334071931b5a285a532335af92e50dee6559899ea07bb9cd03615e","migrations/v0.60.11.0.md": "1e503113f591c5cd142b78ab4472bbdbceb890c6cbac2fbdf8aa61cd087200b8","migrations/v0.60.20.0.md": "9266863a9f76164c64a72b1be17b8ddb3bb97e1c3c5db9f666b69ebc7a228fdd",- "migrations/v0.60.256.0.md": "e9cdb3bfa8e1479caac0dfe9d57bdbeb3e24f8d1482230731194536afae0e0c9",++ "migrations/v0.60.258.0.md": "208d48665cdf9139527b72c4410112eedeb76fecedf2178c666b8bca153c76c9","migrations/v0.60.26.0.md": "30d761ef5a2361bad66053f97b7b659304a591274be33e281f4f6df0d7d5566e","migrations/v0.60.27.0.md": "1c3ac6a23ccfce8ad299457799b02958f7d21fcd967c471634f73bdb66f2b603","migrations/v0.60.28.0.md": "f7fa936066fb188f6f3f54bb6c720f57743792e4371d0b98dd3cb5a57d1bd9c9",diff --cc src/core/behavior-change-notice.tsindex a0c7b45929,d2d26a4344..de2a566c28--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -664,9 -664,28 +664,31 @@@ export const BEHAVIOR_CHANGES: Readonly{ since: '0.60.255.0', text: 'Resuming an unfinished managed sync never refuses over processing options any more (#6712): the cursor\'s `--no-embed`, `--no-extract` and `--no-schema-pack` opt-outs are inherited by every run that resumes it, a flag that would have asked for more processing is reported in `inherited_options` (and printed), and `cursor_processing_options_conflict` is no longer returned. A writer that resumes another writer\'s cursor admits the rest under its own validated grant; requests already admitted stay under their original principal, are read and cancelled under it, and are never rewritten.' },{ since: '0.60.255.0', text: 'The delegation wire\'s `explicitProcessing` field is accepted from a sync client below 0.60.255.0 and ignored until 2026-11-14 (`WIRE_SKEW_WINDOWS` in `src/core/wire-skew.ts`), then removed. `gbrain sync --retry-failed` on a managed source now counts every failure of the source, since no failure sits under another cursor key.' },{ since: '0.60.255.0', text: 'Downgrading below 0.60.255.0 must be quiescent: stop `gbrain serve`, autopilot and sync crons, let the running sync finish, then downgrade. An older binary does not take the drain lease; while a newer non-job holder drains, it writes a `gbrain-drain-lease` row that the live-sync check of 0.60.231.0 and later sees, so such an autopilot backs off instead of dispatching a second sync, but an older CLI started beside a newer drainer is not fenced. An older gbrain resumes an old-key cursor only; a cursor this release created under the new key is invisible to it and is rediscovered from the last synced commit.' },+ // #6785/#6786 corpus hotfix.+ { since: '0.60.256.0', text: 'A session transcript whose extraction answered `chat_unavailable` (no usable extraction model, as in every `gbrain bootstrap verify` before this release) is no longer marked ingested: it stays pending, and files an earlier build marked `skipped: chat_unavailable` are extracted again by the next sweeps. That is a one-time paid catch-up after upgrading, bounded by the sweep window caps (8 windows per file and 32 per sweep; `GBRAIN_CORPUS_WINDOWS_PER_SWEEP` lowers the total) and paused by `GBRAIN_SWEEP=0` or `gbrain config set facts.extraction_enabled false`. Nothing is rewritten during the upgrade, and retention keeps those files for 3x `dream.synthesize.corpus_retention_days` until they are extracted. `bootstrap verify` no longer runs the corpus pass. The sweep, both harvest lanes and the OpenClaw `compact()` inline harvest check a claimed but not activated canonical worktree before any model call and skip it as `writer_coordinator_required`, naming `gbrain sources writer status <source>`. A corpus window that fails after its model call is retried on the next sweep, then after 10, 20 and 40 minutes, then no longer paid for (`corpus_window_dead_lettered`) until `gbrain sweep --retry-failed --apply` (paid, preview without `--apply`) or one extraction model or provider change. The `serve --http` corpus drain writes its skip reasons and failures to stderr.' },+ // Fix wave 18b (old backlog). `since` is the wave's expected merge slot until the slot stamp.+ { since: '0.60.257.0', text: 'Doctor checks that used to report `ok` or `skipped` when an unrelated column or table was missing now fail with the real database error; only the exact object a check depends on reads as "not migrated yet". Page writes, rename aliases, links preparation and Google counterparty resolution likewise tolerate only their own missing table or column and propagate any other undefined-table or undefined-column error.' },+ { since: '0.60.257.0', text: '`sync_freshness`: a source whose first sync is running reads `warn` (`sync_first_run_in_progress`) instead of fresh, and "never been synced" becomes `sync_no_successful_sync` (fail) with the last attempt and a fix for its state. Adopted read-only skill-pack catalogs no longer fail it (`read_only_pack_count`).' },+ { since: '0.60.257.0', text: 'Onboarding `entity_link_coverage` and `timeline_coverage`, the MCP onboarding counts and `extract-ner` typed edges count the page types the active pack declares as entities, per source. A pack that does not load makes the checks warn `entity_types_unavailable`, leaves the MCP entity counts unknown and makes `extract-ner` report `pack_unavailable`.' },+ { since: '0.60.257.0', text: '`gbrain sources writer activate` (dry run and real) adds `warnings[]` with one `git_durability_not_enabled` entry per filesystem source whose Git effects would stay skipped, and prints them on stderr without `--json`; activation is not refused.' },+ { since: '0.60.257.0', text: '`think`, MCP `think`, `synthesize`, CRAG think escalation (`search.crag_think`), dream auto-think, `takes search --semantic`, `search diagnose`, `gbrain eval` vector baselines and `brainstorm` now embed their query with the brain\'s `embedding_query_prefix`, like hybrid search already did; on a brain with a prefix their retrieval shifts and saved eval baselines move.' },+ { since: '0.60.257.0', text: 'On Postgres, a hybrid keyword statement that hit `search.keyword_statement_timeout_ms` is skipped for `search.keyword_timeout_negative_cache_seconds` (default 600 s, 0 = off) in the same serving process when the same statement and scope run again: the search answers from the vector arm with `keyword_arm_failed: skipped_after_timeout` instead of waiting for the timeout. A narrower or differently scoped query, another brain and `use_cache: false` still run it; each timeout writes one `search.keyword_timeout_stats` row that doctor `keyword_plan` reports.' },+ { since: '0.60.257.0', text: '`recall` with `question` adds an informational `facts_calibration: {status: "unmeasured", model_key}` when semantic matching ranked facts on an embedding model without measured admission floors, and shows one `facts_calibration_unmeasured` info notice per brain per session (mute with `gbrain notices mute facts_calibration_unmeasured`); `facts_degraded` is unchanged.' },+ { since: '0.60.257.0', text: 'Dream patterns now quote-verify the timeline entries a patterns child appends with `add_timeline_entry`: an entry quoting text that is not in this run\'s reflections moves to the page\'s `unverified_claims`, and appended pages count in `patterns_written` (new `details.timeline_appends`). `appended_unverified` stays as a deprecated alias.' },+ { since: '0.60.257.0', text: 'In-cycle dream patterns runs (autopilot, bare `gbrain dream`) now wait `dream.patterns.min_interval_hours` (default 6) after the last completed run and skip with `patterns_min_interval` and `next_eligible_at`; `gbrain dream --phase patterns` and `--once` still run at once. A patterns child\'s `get_page` results past `dream.patterns.child_read_budget_kb` (default 200 KB) come back as a short summary (`truncated: true`, `read_budget_exhausted`). Set either to 0 to turn it off.' },+ { since: '0.60.257.0', text: 'New: `gbrain trust backfill --repair-unknown-markers` previews pages whose `trust_tier: unknown` marker sits below their stored tier (stamped by agent edits before v0.60.249.0) with the evidence for each, and repairs only the pages you name with `--slug` and the preview hash (`--expect`). `gbrain trust review` shows a repair command on `lower_page` items that marker caused.' },+ { since: '0.60.257.0', text: '`gbrain doctor` has a new `embedding_identity_unqualified` check: a brain whose `embedding_model` row has no provider prefix now warns and names the `gbrain migrate embeddings --to <provider:model> --dry-run` preview (applying it re-embeds facts and is paid).' },+ { since: '0.60.257.0', text: 'Gmail mail sent with `Precedence: bulk`, `list` or `junk`, a `List-Id` header, or a no-reply `Reply-To` no longer opens a reply-owed loop in `gbrain waiting`. Loops opened before this release stay open: `gbrain waiting` counts those from such senders and prints `gbrain loops drop sender <email> --source <id> --dry-run` for each (preview, then run without `--dry-run`; a drop cannot be undone).' },+ { since: '0.60.257.0', text: '`gbrain loops mute sender|thread` (`loops_mute`) now also closes the muted sender\'s or thread\'s open reply-owed loops (status `dropped`, `closed_by: muted`) and returns their ids in `closed`; before, existing loops stayed open. `gbrain loops unmute` (`loops_unmute`) queues those loops for a re-check on the next Gmail sync, which reopens one only when nothing answered its thread since, and returns `requeued`. Both take `--dry-run` (`dry_run`) and return an `undo_command`. Commitment and decision loops and manually closed loops are not touched.' },+ { since: '0.60.257.0', text: '`gbrain google status` now reads each linked Google source\'s calendar once (`--no-probe` skips it) and, when the account cannot read it (HTTP 403 or 404), names it with `code: calendar_unreadable` and the fix, and reports `ok: false` with exit code 1. The sync records the same result instead of looking like an empty calendar, and doctor warns `google_calendar_readable`.' },+ { since: '0.60.257.0', text: 'On Postgres, an aborted transaction (a request deadline, a cancelled job or a closed client) now cancels the statement it is running before it releases the connection, instead of leaving that statement running on the server until it finished on its own. A statement waiting on a lock is cancelled within the settle window; the abort error keeps the driver error as `cause` and reports a failed cancel as `cancelFailure`.' },+ { since: '0.60.257.0', text: 'A second `gbrain serve` that could not bind the resolve IPC socket (another serve owned it) now retries every 30 seconds (plus up to 5 s jitter) and takes the socket over once the owner is gone, so hooks keep per-turn context without restarting the surviving serve. The single-owner rule is unchanged: a live owner is never displaced.' },+ { since: '0.60.257.0', text: 'On Windows, a PGLite brain whose data directory makes the IPC socket path longer than 107 bytes now places its sockets at `%USERPROFILE%\\.gbrain\\run\\<kind>-<hash>.sock` (the Postgres scheme, same `.gbrain-ipc-secret` guard) instead of failing to bind them, so hooks and local commands reach `gbrain serve` again. A path still too long is logged as `ipc_path_too_long` and reported by the new doctor check `ipc_socket_path`.' },+ { since: '0.60.257.0', text: '`gbrain backup create` on PGLite now refuses before it takes the lock or writes anything when the brain is outside what its archive holds: a data directory that is not `<root>/.gbrain/brain.pglite` or is reached through a symlink is `unmanaged_database_path` (a `.gbrain` alias used to get `symlink_path`), and an estimated archive over 8 GiB is `backup_too_large` (it used to run the dump and fail late). Under `--json` both are their own envelope with an ask-the-user physical-copy fix instead of `storage_error`; the legacy `reason` is unchanged. Doctor `pglite_data_dir` now warns on a healthy PGLite brain whose estimated archive passes 6 GiB.' },+ { since: '0.60.257.0', text: '`gbrain bootstrap harness --token` on a PGLite brain now wires the harness when no serve answers at the serve URL and none holds the brain, and exits 13 with JSON `status: "pending_verify"` instead of exit 1 before writing anything. Re-run the same command with the same `--token` once `gbrain serve --http` runs to verify it; `gbrain bootstrap harness --status` reports `status: "partial"` and exits 1 until that run passes. A serve holding the brain at another URL, any HTTP answer, no `--token` and Postgres brains still fail as before. The harness `--json` result gains `status` (`ok`, `failed` or `pending_verify`).' },+ // #6712 PR 2 lane L3 (flags and config keys): `since` is a placeholder until the merge-slot stamp.- { since: '0.60.256.0', text: 'Five `sync.*` config keys are no longer read (#6712): `sync.bulk_max_txn_ms`, `sync.hold_cap`, `sync.hold_escalate_count`, `sync.hold_escalate_pct` and `sync.parser_regression`. Set `GBRAIN_SYNC_BULK_MAX_TXN_MS`, `GBRAIN_SYNC_HOLD_CAP`, `GBRAIN_SYNC_HOLD_ESCALATE_COUNT`, `GBRAIN_SYNC_HOLD_ESCALATE_PCT` or `GBRAIN_SYNC_PARSER_REGRESSION` in the environment of the process that syncs instead; a value stored on the brain is kept but not applied, so a tuned brain runs with the defaults (15000, 500, 50, 5, stop) until the variable is set. `gbrain doctor --only sync_config_keys` lists stored values that stopped applying, `gbrain config get <key>` prints the value in effect and where it comes from, and `gbrain config set` of a retired key warns, names the variable and writes nothing (exit 0).' },- { since: '0.60.256.0', text: '`sync.job_drain`, `sync.foreground_priority`, `sync.federated_v2`, `sync.waive_batch` and `sync.bulk` are rollback keys (#6712): `false` still restores the earlier behavior a notice named, and they stay honored until at least 2027-01-14 (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts`), but `config set` now writes them with a note that they are not tunables and help text no longer recommends them. `sync.foreground_priority` is accepted without `--force` (it was refused as an unknown key). A serve or PGLite owner that receives a retired field from an older sync client (`explicitProcessing` today) prints one `[gbrain notice]` naming it and its window, and the PGLite owner lane accepts `--lanes N` and `--no-lanes` (ignored there) instead of refusing them.' },++ { since: '0.60.258.0', text: 'Five `sync.*` config keys are no longer read (#6712): `sync.bulk_max_txn_ms`, `sync.hold_cap`, `sync.hold_escalate_count`, `sync.hold_escalate_pct` and `sync.parser_regression`. Set `GBRAIN_SYNC_BULK_MAX_TXN_MS`, `GBRAIN_SYNC_HOLD_CAP`, `GBRAIN_SYNC_HOLD_ESCALATE_COUNT`, `GBRAIN_SYNC_HOLD_ESCALATE_PCT` or `GBRAIN_SYNC_PARSER_REGRESSION` in the environment of the process that syncs instead; a value stored on the brain is kept but not applied, so a tuned brain runs with the defaults (15000, 500, 50, 5, stop) until the variable is set. `gbrain doctor --only sync_config_keys` lists stored values that stopped applying, `gbrain config get <key>` prints the value in effect and where it comes from, and `gbrain config set` of a retired key warns, names the variable and writes nothing (exit 0).' },++ { since: '0.60.258.0', text: '`sync.job_drain`, `sync.foreground_priority`, `sync.federated_v2`, `sync.waive_batch` and `sync.bulk` are rollback keys (#6712): `false` still restores the earlier behavior a notice named, and they stay honored until at least 2027-01-14 (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts`), but `config set` now writes them with a note that they are not tunables and help text no longer recommends them. `sync.foreground_priority` is accepted without `--force` (it was refused as an unknown key). A serve or PGLite owner that receives a retired field from an older sync client (`explicitProcessing` today) prints one `[gbrain notice]` naming it and its window, and the PGLite owner lane accepts `--lanes N` and `--no-lanes` (ignored there) instead of refusing them.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --cc src/core/cli-flag-registry.generated.tsindex 9d8da28af8,f2b5612fe4..7e895e66a9--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@@ -73,7 -73,7 +73,7 @@@ export const CLI_FLAG_REGISTRY: Record<'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--detach', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-frontmatter', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--detach', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-frontmatter', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],++ 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--detach', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-frontmatter', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--prefer', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],diff --cc src/core/sync-config-keys.tsindex 211fd5c8cb,0000000000..90d1efb16dmode 100644,000000..100644--- a/src/core/sync-config-keys.ts+++ b/src/core/sync-config-keys.ts@@@ -1,135 -1,0 +1,135 @@@+/**+ * #6712 PR 2 (L3): the `sync.*` config keys in three kinds.+ *+ * - Tunables: user intent a brain keeps (`config set` writes them, every sync reads them).+ * - Rollback keys: a published notice or migration names them as the way back from a default+ * (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts` holds each one's window). They stay readable and honored,+ * but they are not tunables: `config set` says so, and help text and printed fixes never recommend them.+ * - Retired keys: no longer read. Each names its replacement (a `GBRAIN_SYNC_*` environment variable read by the+ * process that syncs, or nothing when the behavior itself was removed). `config set` warns and writes nothing,+ * `config get` prints the value in effect and where it comes from, and doctor (`sync_config_keys`) reports a value+ * stored before the upgrade as unapplied.+ */+import { CONFIG_ROLLBACK_WINDOWS, type ConfigRollbackWindow } from './wire-skew.ts';++export const SYNC_TUNABLE_KEYS = ['sync.bulk_size', 'sync.lanes', 'sync.exclude', 'sync.include_hidden', 'sync.include_working_tree', 'sync.holds',+ 'sync.write_through', 'sync.cost_gate_min_usd'] as const;++export interface RetiredSyncKey {+ key: string;+ retired_in: string;+ /** What the key tuned, in the words `config get` and doctor print. */+ tuned: string;+ /** The environment variable that replaces it and the value in effect without one; null when the behavior was removed. */+ replacement: { env: string; default: string } | null;+}++export const RETIRED_SYNC_KEYS = {- 'sync.bulk_max_txn_ms': { key: 'sync.bulk_max_txn_ms', retired_in: '0.60.256.0', tuned: 'the target time of one bulk group without lanes, in ms',++ 'sync.bulk_max_txn_ms': { key: 'sync.bulk_max_txn_ms', retired_in: '0.60.258.0', tuned: 'the target time of one bulk group without lanes, in ms',+ replacement: { env: 'GBRAIN_SYNC_BULK_MAX_TXN_MS', default: '15000' } },- 'sync.hold_cap': { key: 'sync.hold_cap', retired_in: '0.60.256.0', tuned: 'how many held files a sync result lists in detail',++ 'sync.hold_cap': { key: 'sync.hold_cap', retired_in: '0.60.258.0', tuned: 'how many held files a sync result lists in detail',+ replacement: { env: 'GBRAIN_SYNC_HOLD_CAP', default: '500' } },- 'sync.hold_escalate_count': { key: 'sync.hold_escalate_count', retired_in: '0.60.256.0', tuned: 'the held-file count above which a source escalates',++ 'sync.hold_escalate_count': { key: 'sync.hold_escalate_count', retired_in: '0.60.258.0', tuned: 'the held-file count above which a source escalates',+ replacement: { env: 'GBRAIN_SYNC_HOLD_ESCALATE_COUNT', default: '50' } },- 'sync.hold_escalate_pct': { key: 'sync.hold_escalate_pct', retired_in: '0.60.256.0', tuned: 'the share of a run\'s screened imports above which it escalates, in percent',++ 'sync.hold_escalate_pct': { key: 'sync.hold_escalate_pct', retired_in: '0.60.258.0', tuned: 'the share of a run\'s screened imports above which it escalates, in percent',+ replacement: { env: 'GBRAIN_SYNC_HOLD_ESCALATE_PCT', default: '5' } },- 'sync.parser_regression': { key: 'sync.parser_regression', retired_in: '0.60.256.0', tuned: 'whether sync stops (stop) or holds the file (hold) when bytes that imported before are refused',++ 'sync.parser_regression': { key: 'sync.parser_regression', retired_in: '0.60.258.0', tuned: 'whether sync stops (stop) or holds the file (hold) when bytes that imported before are refused',+ replacement: { env: 'GBRAIN_SYNC_PARSER_REGRESSION', default: 'stop' } },+ 'sync.knock_on_refreeze_limit': { key: 'sync.knock_on_refreeze_limit', retired_in: '0.60.255.0', tuned: 'the knock-on re-freeze budget', replacement: null },+ 'sync.knock_on_run_limit': { key: 'sync.knock_on_run_limit', retired_in: '0.60.255.0', tuned: 'the knock-on re-freeze budget per run', replacement: null },+} as const satisfies Record<string, RetiredSyncKey>;++export type RetiredSyncKeyName = keyof typeof RETIRED_SYNC_KEYS;+export const SYNC_ROLLBACK_KEYS = Object.keys(CONFIG_ROLLBACK_WINDOWS) as Array<keyof typeof CONFIG_ROLLBACK_WINDOWS>;++export function retiredSyncKey(key: string): RetiredSyncKey | null {+ return (RETIRED_SYNC_KEYS as Record<string, RetiredSyncKey>)[key] ?? null;+}+export function rollbackSyncKey(key: string): ConfigRollbackWindow | null {+ return (CONFIG_ROLLBACK_WINDOWS as Record<string, ConfigRollbackWindow>)[key] ?? null;+}++/** The value a retired key's replacement puts in effect: its environment variable, else the built-in default. */+export function retiredSyncSetting(key: RetiredSyncKeyName, env: NodeJS.ProcessEnv = process.env): string {+ const replacement = (RETIRED_SYNC_KEYS[key] as RetiredSyncKey).replacement!;+ const value = env[replacement.env]?.trim();+ return value ? value : replacement.default;+}++const isOff = (value: string | null | undefined) => typeof value === 'string' && /^(0|false)$/i.test(value.trim());+const isOn = (value: string | null | undefined) => typeof value === 'string' && /^(1|true)$/i.test(value.trim());+const exactOff = (value: string) => value === '0' || value === 'false';++/** How each rollback key resolves at runtime (the readers' own rules), so `config get` reports what a sync does. */+const ROLLBACK_RESOLVERS: Record<keyof typeof CONFIG_ROLLBACK_WINDOWS, { env?: string; resolve: (stored: string | null, envValue: string | undefined) => { on: boolean; from: 'env' | 'config' | 'default' } }> = {+ // sync-group.ts resolveGrouping: a non-empty env wins; `0`/`false` exactly turn it off.+ 'sync.bulk': { env: 'GBRAIN_SYNC_BULK', resolve: (stored, envValue) => envValue ? { on: !exactOff(envValue), from: 'env' } : stored !== null ? { on: !exactOff(stored), from: 'config' } : { on: true, from: 'default' } },+ // sync-waivers.ts waiverBatchEnabled: env ?? config; `0`/`false` exactly turn it off.+ 'sync.waive_batch': { env: 'GBRAIN_SYNC_WAIVE_BATCH', resolve: (stored, envValue) => envValue !== undefined ? { on: !exactOff(envValue), from: 'env' } : stored !== null ? { on: !exactOff(stored), from: 'config' } : { on: true, from: 'default' } },+ // persistence/switches.ts: env `0|false|1|true` (any case) wins, else config, else on.+ 'sync.foreground_priority': { env: 'GBRAIN_SYNC_FOREGROUND_PRIORITY', resolve: (stored, envValue) => isOff(envValue) || isOn(envValue) ? { on: isOn(envValue), from: 'env' }+ : stored !== null ? { on: !isOff(stored), from: 'config' } : { on: true, from: 'default' } },+ // feature-flags.ts and handlers/sync-job-drain.ts: exactly `false` turns it off.+ 'sync.federated_v2': { resolve: stored => stored !== null ? { on: stored !== 'false', from: 'config' } : { on: true, from: 'default' } },+ 'sync.job_drain': { resolve: stored => stored !== null ? { on: stored !== 'false', from: 'config' } : { on: true, from: 'default' } },+};++export interface EffectiveSyncKey {+ /** The value a sync runs with (stdout of `config get`). */+ value: string;+ /** Where it comes from, one line (stderr of `config get`). */+ origin: string;+}++/** The value in effect for a retired or rollback key and where it comes from; null for any other key. */+export function effectiveSyncKey(key: string, stored: string | null, env: NodeJS.ProcessEnv = process.env): EffectiveSyncKey | null {+ const retired = retiredSyncKey(key);+ if (retired) {+ const unapplied = stored !== null ? ` The stored ${key}=${stored} is not applied.` : '';+ if (!retired.replacement) return { value: 'removed', origin: `${key} was retired in ${retired.retired_in} with ${retired.tuned}; nothing replaces it.${unapplied}` };+ const fromEnv = env[retired.replacement.env]?.trim();+ return { value: fromEnv || retired.replacement.default,+ origin: `${fromEnv ? `environment ${retired.replacement.env}` : `built-in default (${retired.replacement.env} unset)`}: ${key} was retired in ${retired.retired_in}; `+ + `set ${retired.replacement.env} for the process that syncs to change ${retired.tuned}.${unapplied}` };+ }+ const window = rollbackSyncKey(key);+ if (!window) return null;+ const resolver = ROLLBACK_RESOLVERS[key as keyof typeof CONFIG_ROLLBACK_WINDOWS];+ const { on, from } = resolver.resolve(stored, resolver.env ? env[resolver.env] : undefined);+ const where = from === 'env' ? `environment ${resolver.env}` : from === 'config' ? 'brain config' : 'default';+ return { value: String(on), origin: `${where}: ${key} is a rollback key, not a tunable; false restores ${window.restores}. Honored until at least ${window.honored_until} (named in ${window.named_in}).` };+}++/** The `config set` warning for a retired or rollback key (null for any other key); `writes` says whether the value is stored. */+export function syncKeySetNotice(key: string): { writes: boolean; lines: string[] } | null {+ const retired = retiredSyncKey(key);+ if (retired) return { writes: false, lines: [+ `[config] WARN: ${key} was retired in ${retired.retired_in} and is no longer read; nothing was written.`,+ retired.replacement+ ? `[config] To change ${retired.tuned}, set ${retired.replacement.env}=<value> in the environment of the process that syncs (the serve, the cron line or the shell); default ${retired.replacement.default}.`+ : `[config] ${retired.tuned} was removed with the behavior it tuned; nothing replaces it.`,+ ] };+ const window = rollbackSyncKey(key);+ if (window) return { writes: true, lines: [+ `[config] note: ${key} is a rollback key, not a tunable: false restores ${window.restores}. It is honored until at least ${window.honored_until} (named in ${window.named_in}); after that a release may stop reading it.`,+ ] };+ return null;+}++/**+ * `gbrain config get|set` of a retired or rollback key. `get` prints the value in effect (stdout) and its origin+ * (stderr); `set` prints the key's notice. True when the command is done: every `get`, and the `set` of a retired key,+ * which writes nothing. A rollback key's `set` returns false so the write goes ahead; any other key returns false.+ */+export async function handleSyncKeyConfig(engine: { getConfig(key: string): Promise<string | null> }, action: 'get' | 'set', key: string): Promise<boolean> {+ if (!retiredSyncKey(key) && !rollbackSyncKey(key)) return false;+ if (action === 'set') {+ const notice = syncKeySetNotice(key)!;+ for (const line of notice.lines) console.error(line);+ return !notice.writes;+ }+ const effective = effectiveSyncKey(key, await engine.getConfig(key))!;+ console.log(effective.value);+ console.error(`[config] source: ${effective.origin}`);+ return true;+}diff --cc src/core/wire-skew.tsindex a6bc7032d0,ef1795aa02..e1896bbeee--- a/src/core/wire-skew.ts+++ b/src/core/wire-skew.ts@@@ -27,34 -9,6 +27,34 @@@ const PROCESSING_KEYS: readonly unknownexport const WIRE_SKEW_WINDOWS = {/** #6712 PR 1: the managed cursor's processing options are inherited, so the explicit-flag list no longer decides anything. */- explicitProcessing: { field: 'explicitProcessing', floor: '0.60.255.0', accept_until: '2026-11-14',+ explicitProcessing: { field: 'explicitProcessing', floor: '0.60.255.0', accept_until: '2026-11-14', wires: ['serve', 'owner'],+ accepts: value => Array.isArray(value) && new Set(value).size === value.length && value.every(item => PROCESSING_KEYS.includes(item)),why: 'Sync clients below the floor send the processing flags their user typed (#6317, #6696); a resume now inherits the cursor\'s opt-outs instead.' },} as const satisfies Record<string, WireSkewWindow>;++/** The retired fields one hand-off still accepts, by field name. */+export function retiredWireFields(wire: SyncWire): ReadonlyMap<string, WireSkewWindow> {+ return new Map((Object.values(WIRE_SKEW_WINDOWS) as WireSkewWindow[]).filter(window => window.wires.includes(wire)).map(window => [window.field, window]));+}++/** The one notice a resident prints when it ignores retired fields an older client sent. */+export function retiredWireNotice(fields: readonly string[]): string {+ const windows = fields.map(field => (Object.values(WIRE_SKEW_WINDOWS) as WireSkewWindow[]).find(window => window.field === field)!);+ return `[gbrain notice] this gbrain ignores ${windows.map(window => `\`${window.field}\` (sent by gbrain below ${window.floor}; accepted until ${window.accept_until})`).join(', ')} `+ + 'from an older sync client and runs without it. Upgrade the gbrain that runs `gbrain sync` to match this one.';+}++export interface ConfigRollbackWindow { key: string; floor: string; honored_until: string; named_in: string; restores: string }++export const CONFIG_ROLLBACK_WINDOWS = {- 'sync.job_drain': { key: 'sync.job_drain', floor: '0.60.256.0', honored_until: '2027-01-14', named_in: '0.60.233.0 behavior notice (#6706)',++ 'sync.job_drain': { key: 'sync.job_drain', floor: '0.60.258.0', honored_until: '2027-01-14', named_in: '0.60.233.0 behavior notice (#6706)',+ restores: 'single-pass managed `sync` jobs instead of draining to the job deadline' },- 'sync.foreground_priority': { key: 'sync.foreground_priority', floor: '0.60.256.0', honored_until: '2027-01-14', named_in: 'docs/guides/live-sync.md (#5984)',++ 'sync.foreground_priority': { key: 'sync.foreground_priority', floor: '0.60.258.0', honored_until: '2027-01-14', named_in: 'docs/guides/live-sync.md (#5984)',+ restores: 'first-in-first-out bulk groups instead of letting foreground writes go first' },- 'sync.federated_v2': { key: 'sync.federated_v2', floor: '0.60.256.0', honored_until: '2027-01-14', named_in: 'skills/migrations/v0.40.5.md',++ 'sync.federated_v2': { key: 'sync.federated_v2', floor: '0.60.258.0', honored_until: '2027-01-14', named_in: 'skills/migrations/v0.40.5.md',+ restores: 'the v0.39 sequential sync --all instead of the federated v2 path' },- 'sync.waive_batch': { key: 'sync.waive_batch', floor: '0.60.256.0', honored_until: '2027-01-14', named_in: '#5984 behavior notice',++ 'sync.waive_batch': { key: 'sync.waive_batch', floor: '0.60.258.0', honored_until: '2027-01-14', named_in: '#5984 behavior notice',+ restores: 'one waived entry per transaction instead of batched waivers' },- 'sync.bulk': { key: 'sync.bulk', floor: '0.60.256.0', honored_until: '2027-01-14', named_in: '#5984 behavior notice and docs/guides/live-sync.md',++ 'sync.bulk': { key: 'sync.bulk', floor: '0.60.258.0', honored_until: '2027-01-14', named_in: '#5984 behavior notice and docs/guides/live-sync.md',+ restores: 'one page per transaction on managed Postgres sync instead of bulk groups' },+} as const satisfies Record<string, ConfigRollbackWindow>;diff --cc test/sync-config-keys-6712.test.tsindex e40c314d77,0000000000..9d38805d73mode 100644,000000..100644--- a/test/sync-config-keys-6712.test.ts+++ b/test/sync-config-keys-6712.test.ts@@@ -1,155 -1,0 +1,155 @@@+/**+ * #6712 PR 2 (L3): the `sync.*` keys in three kinds (src/core/sync-config-keys.ts).+ *+ * Protects:+ * - `config set` of a retired key warns, names its GBRAIN_SYNC_* replacement and writes nothing (exit 0, not a refusal);+ * - `config get` of a retired key prints the value a sync runs with (env, else the built-in default) and says a+ * stored value is not applied; the readers really ignore the stored key;+ * - a rollback key is written with a note naming its window, and `config get` prints the value in effect and+ * where it comes from; `sync.foreground_priority` (named as the way back since 0.60.111.0) is accepted without+ * --force, where it used to be refused as an unknown key;+ * - `config get`'s resolution of each rollback key agrees with the reader the sync uses;+ * - doctor `sync_config_keys` reports a stored retired key as unapplied, with the value in effect and its env.+ */+import { afterAll, beforeAll, beforeEach, expect, spyOn, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runConfig } from '../src/commands/config.ts';+import { RETIRED_SYNC_KEYS, SYNC_ROLLBACK_KEYS, SYNC_TUNABLE_KEYS, effectiveSyncKey } from '../src/core/sync-config-keys.ts';+import { CONFIG_ROLLBACK_WINDOWS } from '../src/core/wire-skew.ts';+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';+import { GIT_HOLD_CAP, GIT_HOLD_ESCALATE_COUNT, GIT_HOLD_ESCALATE_PCT, readSyncHoldPolicy } from '../src/core/persistence/sync-holds.ts';+import { resolveBulkSettings } from '../src/core/persistence/sync-group.ts';+import { waiverBatchEnabled } from '../src/core/persistence/sync-waivers.ts';+import { isFederatedV2Enabled } from '../src/core/feature-flags.ts';+import { readWriteSwitches, resetWriteSwitches } from '../src/core/persistence/switches.ts';+import { syncConfigKeysEntry } from '../src/commands/doctor/checks/sync-config-keys.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+const KEYS = [...Object.keys(RETIRED_SYNC_KEYS), ...SYNC_ROLLBACK_KEYS];+const CLEAR = { GBRAIN_SYNC_HOLD_CAP: undefined, GBRAIN_SYNC_HOLD_ESCALATE_COUNT: undefined, GBRAIN_SYNC_HOLD_ESCALATE_PCT: undefined, GBRAIN_SYNC_PARSER_REGRESSION: undefined,+ GBRAIN_SYNC_BULK_MAX_TXN_MS: undefined, GBRAIN_SYNC_BULK: undefined, GBRAIN_SYNC_WAIVE_BATCH: undefined, GBRAIN_SYNC_FOREGROUND_PRIORITY: undefined };+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { for (const key of KEYS) await engine.unsetConfig(key); });++async function config(args: string[]) {+ const logs: string[] = [], errs: string[] = [];+ let exit: number | null = null;+ const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => { exit = code ?? 0; throw new Error(`EXIT:${code}`); }) as never);+ try { await runConfig(engine, args); }+ catch (e) { if (!(e as Error).message.startsWith('EXIT:')) throw e; }+ finally { logSpy.mockRestore(); errSpy.mockRestore(); exitSpy.mockRestore(); }+ return { out: logs.join('\n'), err: errs.join('\n'), exit: exit as number | null };+}++test('the three kinds are disjoint; tunables and rollback keys are registered, retired keys are not; defaults match the readers', () => {+ const retired = Object.keys(RETIRED_SYNC_KEYS);+ for (const key of SYNC_TUNABLE_KEYS) { expect(KNOWN_CONFIG_KEYS).toContain(key); expect(retired).not.toContain(key); expect(SYNC_ROLLBACK_KEYS as string[]).not.toContain(key); }+ for (const key of SYNC_ROLLBACK_KEYS) { expect(KNOWN_CONFIG_KEYS).toContain(key); expect(retired).not.toContain(key); }+ for (const key of retired) expect(KNOWN_CONFIG_KEYS).not.toContain(key);+ expect(String(RETIRED_SYNC_KEYS['sync.hold_cap'].replacement.default)).toBe(String(GIT_HOLD_CAP));+ expect(String(RETIRED_SYNC_KEYS['sync.hold_escalate_count'].replacement.default)).toBe(String(GIT_HOLD_ESCALATE_COUNT));+ expect(String(RETIRED_SYNC_KEYS['sync.hold_escalate_pct'].replacement.default)).toBe(String(GIT_HOLD_ESCALATE_PCT));+ for (const window of Object.values(CONFIG_ROLLBACK_WINDOWS)) {+ expect(window.honored_until).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ expect(window.floor).toMatch(/^\d+\.\d+\.\d+\.\d+$/);+ }+});++test('config set of a retired key warns, names its replacement and writes nothing', async () => withEnv(CLEAR, async () => {+ const set = await config(['set', 'sync.hold_cap', '200']);+ expect(set.exit).toBeNull();- expect(set.err).toContain('sync.hold_cap was retired in 0.60.256.0');++ expect(set.err).toContain('sync.hold_cap was retired in 0.60.258.0');+ expect(set.err).toContain('GBRAIN_SYNC_HOLD_CAP=<value>');+ expect(set.err).toContain('nothing was written');+ expect(await engine.getConfig('sync.hold_cap')).toBeNull();+ const removed = await config(['set', 'sync.knock_on_run_limit', '5']);+ expect(removed.exit).toBeNull();+ expect(removed.err).toContain('nothing replaces it');+ expect(await engine.getConfig('sync.knock_on_run_limit')).toBeNull();+}));++test('config get of a retired key prints the value in effect, and a stored value is reported and not applied', async () => withEnv(CLEAR, async () => {+ await engine.setConfig('sync.hold_cap', '200');+ await engine.setConfig('sync.parser_regression', 'hold');+ const got = await config(['get', 'sync.hold_cap']);+ expect(got.out).toBe('500');+ expect(got.err).toContain('built-in default (GBRAIN_SYNC_HOLD_CAP unset)');+ expect(got.err).toContain('The stored sync.hold_cap=200 is not applied.');+ expect(await readSyncHoldPolicy(engine)).toMatchObject({ cap: 500, parserRegression: 'stop' });+ await withEnv({ GBRAIN_SYNC_HOLD_CAP: '7' }, async () => {+ const env = await config(['get', 'sync.hold_cap']);+ expect(env.out).toBe('7');+ expect(env.err).toContain('environment GBRAIN_SYNC_HOLD_CAP');+ expect((await readSyncHoldPolicy(engine)).cap).toBe(7);+ });+ await engine.setConfig('sync.bulk_max_txn_ms', '100');+ const settings = await resolveBulkSettings(engine, false);+ expect({ maxTxnMs: settings.maxTxnMs, explicit: settings.maxTxnExplicit }).toEqual({ maxTxnMs: 15_000, explicit: false });+}));++test('a rollback key is written with its window; get prints the value in effect and where it comes from', async () => withEnv(CLEAR, async () => {+ const set = await config(['set', 'sync.bulk', 'false']);+ expect(set.exit).toBeNull();+ expect(set.err).toContain('sync.bulk is a rollback key, not a tunable');+ expect(set.err).toContain(CONFIG_ROLLBACK_WINDOWS['sync.bulk'].honored_until);+ expect(await engine.getConfig('sync.bulk')).toBe('false');+ const got = await config(['get', 'sync.bulk']);+ expect(got.out).toBe('false');+ expect(got.err).toContain('brain config: sync.bulk is a rollback key');+ await withEnv({ GBRAIN_SYNC_BULK: '1' }, async () => {+ const env = await config(['get', 'sync.bulk']);+ expect(env.out).toBe('true');+ expect(env.err).toContain('environment GBRAIN_SYNC_BULK');+ });+ const unset = await config(['get', 'sync.job_drain']);+ expect(unset).toMatchObject({ out: 'true', exit: null });+ expect(unset.err).toContain('default: sync.job_drain is a rollback key');+}));++test('sync.foreground_priority is accepted without --force (it used to be refused as an unknown key)', async () => withEnv(CLEAR, async () => {+ const set = await config(['set', 'sync.foreground_priority', 'false']);+ expect(set.exit).toBeNull();+ expect(await engine.getConfig('sync.foreground_priority')).toBe('false');+ resetWriteSwitches();+ expect((await readWriteSwitches(engine)).foreground_priority).toBe(false);+}));++test('config get resolves every rollback key the way its reader does', async () => {+ const cases: Array<[string | null, string | undefined]> = [[null, undefined], ['false', undefined], ['0', undefined], ['true', undefined], ['FALSE', undefined],+ [null, '0'], [null, 'false'], [null, '1'], ['false', '1'], ['true', '0'], [null, '']];+ for (const [stored, envValue] of cases) {+ for (const key of SYNC_ROLLBACK_KEYS) { if (stored === null) await engine.unsetConfig(key); else await engine.setConfig(key, stored); }+ await withEnv({ ...CLEAR, GBRAIN_SYNC_BULK: envValue, GBRAIN_SYNC_WAIVE_BATCH: envValue, GBRAIN_SYNC_FOREGROUND_PRIORITY: envValue }, async () => {+ const said = (key: string) => effectiveSyncKey(key, stored)!.value === 'true';+ const bulk = await resolveBulkSettings(engine, false);+ // PGLite turns bulk off for its own reason; only an explicit off is the key's.+ expect(said('sync.bulk')).toBe(!(bulk.reason && /GBRAIN_SYNC_BULK|sync\.bulk/.test(bulk.reason)));+ expect(said('sync.waive_batch')).toBe(await waiverBatchEnabled(engine));+ expect(said('sync.federated_v2')).toBe(await isFederatedV2Enabled(engine));+ resetWriteSwitches();+ expect(said('sync.foreground_priority')).toBe((await readWriteSwitches(engine)).foreground_priority);+ expect(said('sync.job_drain')).toBe(stored !== 'false');+ });+ }+});++test('doctor sync_config_keys reports a stored retired key as unapplied, and is ok without one', async () => withEnv(CLEAR, async () => {+ const ctx = { engine, progress: { heartbeat: () => {} } } as never;+ const clean = await syncConfigKeysEntry.run(ctx);+ expect(clean).toMatchObject([{ name: 'sync_config_keys', status: 'ok' }]);+ await engine.setConfig('sync.hold_escalate_count', '10');+ await engine.setConfig('sync.waive_batch', 'false');+ const checks = await syncConfigKeysEntry.run(ctx);+ if (!Array.isArray(checks)) throw new Error('sync_config_keys returned no checks');+ const [check] = checks;+ expect(check).toMatchObject({ name: 'sync_config_keys', status: 'warn', fix: { argv: ['gbrain', 'config', 'get', 'sync.hold_escalate_count'], actor: 'agent' } });+ expect(check!.message).toContain('sync.hold_escalate_count=10 (in effect: 50; set GBRAIN_SYNC_HOLD_ESCALATE_COUNT');+ expect(check!.message).toContain('sync.waive_batch=false (until at least');+ // The documented way to clear it: config unset of the retired key.+ expect((await config(['unset', 'sync.hold_escalate_count'])).exit).toBeNull();+ expect(await syncConfigKeysEntry.run(ctx)).toMatchObject([{ name: 'sync_config_keys', status: 'ok' }]);+}));