Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge origin/master (v0.60.52.0: engine graduation #6022, auto_chronicle date quality #6010, contributor fixes) into capy/foundations-2

garrytane623fd8babf4
diff --cc CHANGELOG.md
index c6abebfebc,453fa8ccdc..2a4c3a1c89
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -10,117 -10,148 +10,259 @@@ credits are retained; no result has bee
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.53.0] - 2026-10-04
+
+**gbrain now crash-tests its own write path on every pull request, notes on a PGLite brain turn into facts without anyone running a command, and new dashboard API keys stop handing out admin access by default.**
+
+Three things got measurably better in this release. First, the gate that guards your data now kills gbrain in the middle of real writes, over and over, and checks that nothing was lost, duplicated or leaked into another source afterwards. A full 10-minute run kills it 69 to 75 times on PGLite and 18 times on Postgres behind a connection pooler, at 11 different points in the write path, and finds zero problems. Second, on a PGLite brain served by `gbrain serve`, ten new meeting notes became 49 facts within about 20 minutes with no further command; before, they waited forever. Third, an API key created in the admin dashboard used to get full admin access unless you knew better. Now 0 of 20 do.
+
+### The numbers that matter
+
+| What we measured | Before | Now |
+| --- | --- | --- |
+| Crash runs in one full persistence gate run (600 s budget) | 0 | 69 to 75 on PGLite, 18 on Postgres through PgBouncer, 11 crash points, 0 violations |
+| Past persistence fixes the gate catches when the fix is reverted (12 tried) | 0 | 1 on each engine |
+| Facts from 10 meeting notes on a served PGLite brain, no command run | 0 after 22 min (10 jobs waiting) | 49 facts from all 10 pages at about 20 min, $0.084 |
+| Dashboard-minted API keys with full admin access | 20 of 20 | 0 of 20 |
+| Legacy tokens authorized from the old JSON grant after upgrade | 50 of 50 | 0 of 50 (all 50 still work) |
+| Unattributed writer references in the code | 90 in 40 files | 7 in 3 files |
+| Scale tier enforced gates at 10,000 pages | n/a | 25 of 25 PGLite, 24 of 24 Postgres |
+| Scale tier at 20,000 pages | nightly timed out at 50 min | green on both engines, about 8 min per job |
+| `gbrain extract timeline --source db` at 20,000 PGLite pages | 12.6 min | about 2 min |
+
+Search latency did not regress with the facts drain running beside it (12 pages, real model): `get_page` p95 3.2 to 3.3 ms, `list_pages` 9.1 to 8.8 ms, search 439 to 389 ms.
+
+### How to use it
+
+```bash
+gbrain doctor --only legacy_token_null_scope,facts_drain --json # full-access keys and the drain's state
+gbrain auth rescope --id <token-id> --scopes read,write # narrow an old full-access key
+gbrain auth rescope --client <id> --sources none # an OAuth client that reads no source
+gbrain auth rescope --client <id> --takes-holders world,brain # per-client takes holders
+gbrain repair take-supersession # preview; add --apply after review
+gbrain config set facts.extraction_enabled false # turn automatic fact extraction off
+```
+
+### Things to watch
+
+- The facts drain is on by default on PGLite and spends real money: one chat call per page, capped at $1 per run and $5 per rolling day (`facts.drain_budget_usd`, `facts.drain_daily_budget_usd`). A brain without a chat key queues the pages and `gbrain doctor` says so.
+- Large-brain ceilings (MCP search latency at 10k and 20k pages, calibrated budgets) are still report-only. The scale tier measures them every night; enforcement stays off until five nightly runs are stable.
+- MCP search on Postgres slows from 78.6 ms at 10k pages to 615 ms at 20k (1,169 ms source-scoped). This is filed, not fixed.
+- Older binaries keep reading tokens through the `permissions` mirror, which is written until 2026-11-04.
+
+## To take advantage of v0.60.53.0
+
+`gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:
+
+1. **Run the orchestrator manually:**
+ ```bash
+ gbrain apply-migrations --yes
+ ```
- 2. **Your agent reads `skills/migrations/v0.60.53.0.md` the next time you interact with it.** Migration v201 converts every legacy token grant to the grant columns without changing what any token can do, and v202 adds the per-client source and takes-holder columns. Restart every `gbrain serve`, autopilot and worker so the facts drain and the new token reads take effect.
++2. **Your agent reads `skills/migrations/v0.60.53.0.md` the next time you interact with it.** Migration v202 converts every legacy token grant to the grant columns without changing what any token can do, and v203 adds the per-client source and takes-holder columns. Restart every `gbrain serve`, autopilot and worker so the facts drain and the new token reads take effect.
+3. **Verify the outcome:**
+ ```bash
+ gbrain doctor --only legacy_token_null_scope,legacy_token_grant_shape,facts_drain,revision_backfill --json
+ gbrain stats
+ ```
+4. **If any step fails or the numbers look wrong,** please file an issue:
+ https://github.com/garrytan/gbrain/issues with:
+ - output of `gbrain doctor`
+ - contents of `~/.gbrain/upgrade-errors.jsonl` if it exists
+ - which step broke
+
+ This feedback loop is how the gbrain maintainers find fragile upgrade paths. Thank you.
+
+### Itemized changes
+
+#### Crash robot in the persistence gate
+
+- The persistence gate runs a crash robot (`scripts/persistence/crash-robot.ts`, `generator.ts`, `model.ts`, `ops.ts`): seeded sequences of real operations across two sources and a connector source (local CLI, an OAuth client and a legacy token as remote agents; page writes, edits, deletes and restores, `remember`/`forget`, takes add and supersede, timeline entries, `sync_brain`, a GitHub connector publish, credential revocation). It SIGKILLs the owner at every crash seam the sequences reach (`src/core/persistence/fault-points.ts`), and runs process faults: a stale `index.lock`, a hung `git commit`, Postgres session drops every 400 ms, and the owner killed right after a `facts-absorb` job commits. A reference model checks for lost or duplicated writes, untrue receipts, withdrawn facts coming back, cross-source writes, request-id replay across principals, takes and facts rows against their page fences, write attribution, orphan rows, wedged queues and lock order.
+- `.github/workflows/persistence-validation.yml` adds a `crash-robot` job per engine with PgBouncer for Postgres: 150 s on pull requests, 600 s on pushes, schedules and manual runs. Failing runs replay with `--replay` and shrink with `--shrink`; accepted shrunk sequences live in `test/fixtures/crash-robot/`.
+- A restarted PGLite owner (for example `gbrain serve` after a crash) resumes the effects and writes its predecessor left claimed instead of waiting out a 2-minute lease that also held back writes to a withdrawn page.
+- `buildHistoryFixture(engine, { pages, seed, sources, worktrees })` (`scripts/persistence/history-fixture.ts`) builds a managed brain with real persistence history at up to 10,000 pages.
+
+#### Facts and chronicle
+
+- Automatic facts drain on PGLite (`src/core/facts/drain.ts`, `drain-scheduler.ts`): `gbrain serve` (stdio and `--http`) and the new `facts_drain` cycle phase run queued `facts-absorb` jobs under per-run and daily spend caps. Jobs without a key are deferred without spending an attempt (minion job deferral); doctor `facts_drain` reports the state. Guide: `docs/guides/facts-drain.md`.
+- The `extract_facts` cycle phase fences facts without a fence row itself (#5299).
+- `gbrain repair take-supersession` rebuilds supersession chains broken on managed brains (#5886).
+- Doctor `revision_backfill` reports pages waiting on the page revision backfill with a resume command that works, and the backfill runs on managed brains (#5216).
+- Life chronicle: two same-day events of one page that share who and what both survive (`src/core/chronicle/event-identity.ts`), and an ended calendar invite becomes a `Scheduled:` meeting event without a model call (`invite-projection.ts`).
+
+#### Keys and grants
+
+- Dashboard API keys mint through `mintLegacyToken` with read and write by default; admin only when the box is checked. The dashboard revokes a key by id, so two keys with the same name no longer revoke each other.
+- Doctor `legacy_token_null_scope` names every existing full-access key with the command that narrows it.
- - Migration v201 (`legacy_token_grant_conversion`) converts every legacy token grant to the unified grant columns; HTTP auth on both transports reads those columns, and a row created later converts on its first read. A malformed `permissions` value now denies every axis on every path.
- - Migration v202 (`oauth_client_grant_axes`) adds `oauth_clients.source_grant` and `oauth_clients.takes_holders`: `gbrain auth rescope --client <id> --sources none` and `--takes-holders a,b|none`.
++- Migration v202 (`legacy_token_grant_conversion`) converts every legacy token grant to the unified grant columns; HTTP auth on both transports reads those columns, and a row created later converts on its first read. A malformed `permissions` value now denies every axis on every path.
++- Migration v203 (`oauth_client_grant_axes`) adds `oauth_clients.source_grant` and `oauth_clients.takes_holders`: `gbrain auth rescope --client <id> --sources none` and `--takes-holders a,b|none`.
+
+#### Write attribution
+
+- Imports, legacy sync renames and deletes, timeline extraction, legacy facts and takes helpers, cycle phases, schema-pack conversions and repairs record the local maintenance principal (`maintenanceTransaction`). Changed rows keep their creator and move their last writer. `gbrain extract`, meeting-timeline extraction and enrichment remain unattributed (`docs/architecture/system-of-record.md`).
+- Batch maintenance writers commit one bounded transaction per batch: 10,000 pages of timeline extraction run as 100 transactions of at most 100 rows.
+- `gbrain repair attribution-backfill` on a 10,000-page managed history with 75% of rows reset refilled 6,868 of 7,509 pages, 5,502 of 5,609 versions and 1,501 of 1,501 facts exactly and changed no content; the rest were last changed by `forget`.
+- `gbrain calibration undo-wave` works on Postgres.
+
+#### Scale and operations
+
+- The scale tier asserts the large-brain ceilings through the real CLI at every size: progress-aware sync deadline, loud `embed --stale` budget stop, serve boot window, and a 20,000-file `sources add` at 20k pages and up. Ceiling enforcement stays report-only.
+- The Postgres `find_orphans` known answer reads totals and one maximal page (it read 1 page of 100 against 104 orphans and failed the 20k nightly).
+- PGLite writes made outside a transaction take the WAL checkpoint guard, so large raw writes no longer hang at a 529 MB WAL.
+- `gbrain extract timeline --source db` refreshes PGLite planner statistics on batch boundaries during the walk.
+- `gbrain migrate --to` refusals carry why and a filled fix naming the refusing side; an unknown engine is `invalid_params`; `postgres` is the canonical engine name (`supabase` stays an alias).
+- `gbrain sources refresh` runs inside a resident PGLite owner (`writer_refresh` administration operation); delegated syncs keep the progress-aware deadline; the consumer's idle probe honors the refresh fence.
+- `gbrain sources add` no longer fails with `internal_error` (ENOENT under `.git/objects`) when a background `git gc` prunes the checkout while it is being registered.
+- Search reuses its projection-readiness answer until the brain changes (`GBRAIN_PROJECTION_READINESS_CACHE=0` turns it off).
+- The OpenClaw context-engine heartbeat reports seat write failures with their hints; a pattern page drops a seat its reflections no longer share (#4618).
+
+### For contributors
+
+- Generated files were regenerated, not merged: migration registry, flag registry, schema blobs, llms bundles, goldens.
+- New write-attribution suites `test/write-attribution-<family>.test.ts`; helpers `test/helpers/unmanaged-attribution.ts` and `attribution-history-fixture.ts` (`GBRAIN_TEST_BACKFILL_FIXTURE_PAGES`). A test that overrides an engine method with a copy bound to the base engine deadlocks on PGLite once the writer runs in a transaction; override through the transaction engine instead.
+- `scripts/persistence/would-have-caught.ts` reverts past fixes one at a time and reports which the gate catches.
+
+ ## [0.60.52.0] - 2026-10-04
+
+ **A PGLite brain that has saved memory can now move to Postgres with nothing lost: one command shows the plan, one confirmation moves it, and the move proves the copy matches before it switches.**
+
+ PGLite is the zero-setup local database a new brain starts on. When a brain outgrows it (thousands of pages, several machines, a hosted server), the next step is Postgres. Until now `gbrain migrate --to postgres` refused almost every real brain: anything an agent had saved through the write coordinator carried history the old copier could not move, such as which saves already happened, which facts you told it to forget, who wrote what, and which keys can get in. Now the move carries all of it, row for row, with the same IDs.
+
+ The move locks the old brain so nothing can write to it, finishes saves that are still in flight, copies every table, and then checks the copy: row counts and a fingerprint of every table, a replay of a saved request to show it is not done twice, and a health check on the new brain. Only after that passes does gbrain point at Postgres. The old folder becomes a small "this brain moved" file that tells any gbrain (old or new, including a restarted `gbrain serve`) where the brain went, and the old data is kept beside it. At every moment at most one of the two databases accepts writes, including after a crash; `--resume` picks up from the last finished step.
+
+ ### How to use it
+
+ ```bash
+ export GBRAIN_TARGET_URL='postgresql://...' # the empty Postgres database
+ gbrain migrate --to postgres --url-env GBRAIN_TARGET_URL --json # shows the plan, exits 3, changes nothing
+ gbrain migrate --to postgres --url-env GBRAIN_TARGET_URL --yes --expect <plan_hash> --json
+ gbrain doctor --no-migrate --json
+ ```
+
+ `--status` and `--plan` are read-only. `--resume` continues an interrupted move, and `--rollback-to-source` goes back to PGLite (it refuses once you have withdrawn facts or revoked a key on Postgres, because going back would undo that). Existing access tokens, OAuth clients and local writer credentials keep working on Postgres. Full guide: [Move a PGLite brain to Postgres](docs/guides/move-to-postgres.md). To keep the old copier, run `gbrain config set migrate.graduation false`.
+
+ ### The numbers that matter
+
+ Measured with the history fixture (real write history: requests, withdrawals, versions, takes, tokens, embedded chunks), a resident `gbrain serve` holding the brain, and a local Postgres 16:
+
+ | Brain | Commands | Wall time, plan to green doctor | Copy | Verify | Target doctor |
+ | --- | --- | --- | --- | --- | --- |
+ | 1,000 pages (1,737 requests, 4,702 effects, 1,168 embedded chunks) | 2 plus 1 doctor | 16.4 s | 2.9 s | 4.3 s | no failing check |
+ | 10,000 pages (17,344 requests, 46,986 effects, 11,668 embedded chunks) | 2 plus 1 doctor | 47.4 s | 15.9 s | 13.3 s | no failing check |
+
+ Search latency, PGLite then Postgres: at 1,000 pages p50 5.3 ms / 8.4 ms and p95 9.0 ms / 9.9 ms; at 10,000 pages p50 37.4 ms / 30.5 ms and p95 41.8 ms / 58.9 ms.
+
+ ### Things to watch
+
+ - A move to a hosted Postgres where the role is not a superuser needs the `vector` extension installed, `BYPASSRLS`, and the row-level-security event trigger owned by the role. The plan names the exact SQL your database admin runs. Supabase's `postgres` role already qualifies.
+ - On Windows a brain with write history still cannot move; brains without history keep the old copier.
+ - The kept PGLite copy (`<path>.graduated-<run_id>`) still holds private memory and token hashes. `gbrain doctor` reports it; deleting it is your call.
+
+ ### Behavior changes for scripts and agents
+
+ | Area | Before | Now | What to change |
+ | --- | --- | --- | --- |
+ | `gbrain migrate --to postgres` (or `--to supabase`) on a PGLite brain | copied at once, or exit 1 `writer_coordinator_required` for a brain with write history | exit 3 `confirmation_required` with the plan and `plan_hash`; the move runs with `--yes --expect <plan_hash>` | relay the plan to the user, then run `fix.argv` after they agree; `gbrain config set migrate.graduation false` keeps the old copier |
+ | `gbrain serve` started while a move runs | waited on the lock or started status-only | exit 75 `graduation_in_progress` | let the supervisor retry after the move |
+ | A CLI or MCP config that still points at a moved PGLite path | opened or recreated the PGLite folder | `engine_graduated` with the one-step fix | run `fix.argv`, restart the MCP client |
+ | `doctor` `pglite_scale` fix | `gbrain migrate --to supabase` | `gbrain migrate --to postgres --plan --json` | none |
+
+ ## To take advantage of v0.60.52.0
+
+ `gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:
+
+ 1. **Run the orchestrator manually:**
+ ```bash
+ gbrain apply-migrations --yes --no-autopilot-install
+ ```
+ Migration v201 adds the `persistence_graduation` table; no existing rows change.
+ 2. **Your agent reads `skills/migrations/v0.60.52.0.md` the next time you interact with it.** Nothing moves until you ask for a move and confirm the plan.
+ 3. **Verify:**
+ ```bash
+ gbrain doctor --json
+ gbrain migrate --status --json
+ ```
+ 4. **If any step fails or the numbers look wrong,** please file an issue: https://github.com/garrytan/gbrain/issues with:
+ - output of `gbrain doctor`
+ - contents of `~/.gbrain/upgrade-errors.jsonl` if it exists
+ - which step broke
+
+ ### Itemized changes
+
+ #### Engine graduation (`gbrain migrate --to postgres`)
+
+ - Every table is classified in one versioned inventory: 94 copied verbatim with IDs, 2 re-checked for this machine (brain identity, worktree host bindings), 2 caches rebuilt, 6 transient or unused tables (PGLite planner statistics, cycle locks, an unused reservation table, rate leases, one-time OAuth codes) dropped. A schema with an unclassified table refuses the move, and a test fails when a migration adds one without a classification.
+ - The copy runs with database triggers bypassed for the copy transaction only, so stored attribution, revisions and generations land unchanged; leases on queued jobs and effects are reset so the new database's workers pick them up, and delayed effects keep their schedule.
+ - Verify compares row counts (twice: by a plain count and by the batched fingerprint read), a canonical per-table fingerprint computed the same way on both engines, sequence positions, every foreign key, trigger state and the relation set, replays a drained request through admission inside a rolled-back transaction, and runs the target doctor.
+ - Custody: the PGLite kernel lock is held from the start of the move until routing flips; an intent marker beside the brain and a database fence on Postgres refuse every other writer; the old folder is renamed and replaced by an exclusive-create tombstone before Postgres takes authority. A stray brain created at the old path by an older gbrain is detected and refused (`graduation_split_brain`).
+ - New error codes, each with a reason, an exact fix and a read-only verify command: `graduation_source_writer_held`, `graduation_unclassified_table`, `graduation_embedding_dimension_mismatch`, `graduation_drain_timeout`, `graduation_target_not_empty`, `graduation_foreign_host_binding`, `graduation_verify_failed`, `graduation_interrupted`, `graduation_in_progress`, `graduation_split_brain`, `graduation_rollback_writes_lost`, `graduation_target_auth_failed`, `graduation_target_ddl_unreachable`, `graduation_target_unsupported`, `graduation_unsupported_platform`, `engine_graduated`.
+ - `gbrain engine status --json` shows the graduation state; `pglite_leftovers` reports the kept PGLite copy; a dead interrupted move is a doctor failure with the resume command.
+
+ #### Tests
+
+ - A hand-built legacy brain with independently written expected outcomes, plus 1,000- and 10,000-page history brains, graduate end to end on Postgres 16 and through a transaction-mode PgBouncer.
+ - Crash tests kill the move at every step of the move and of rollback, including around the routing flip and the first write on Postgres; a restarted `gbrain serve`, older released binaries against the tombstone, stale CLI and MCP configs, a full target disk and a rotated target password are each tested.
+
+ ## [0.60.49.0] - 2026-10-04
+
+ **Automatic event extraction now records only what happened. On the independent lift eval that failed it, wrong or premature events drop from 1.11 per judged page to 0.07 and 0.11 (gate: 0.20), and recall rises from 35/38 to 38/38.**
+
+ `auto_chronicle` wrote plans as if they happened: "board meeting in Austin on May 15" in an April 18 meeting note became a May 15 event, and "back in 2024" became January 1, 2024. Now the extractor is told to return only what happened by the end of the page's day, and two rules hold after it answers, before anything is written: no event after the page's own day (`future_dated`), and no event without a real day (`date_imprecise`). A plan never reaches `gbrain day`, and a vague year is never pinned to January 1.
+
+ ### The numbers that matter
+
+ gbrain-evals `chronicle-lift.ts` (amara-life-v1, 48 judged pages, 38 labeled events on 28 pages, judge `anthropic:claude-sonnet-4-6`), one ON arm per run, scored with the published review rubric:
+
+ | | master `5bd9e849` | this release, run 1 | this release, run 2 |
+ |---|---|---|---|
+ | Recall of labeled events | 35/38 (92.1%) | 38/38 (100%) | 38/38 (100%) |
+ | Premature (dated after the page) | 26 | 0 | 0 |
+ | False (misdated or unsupported) | 5 | 2 | 3 |
+ | **False + premature per judged labeled page** (gate ≤ 0.20) | **1.11** | **0.07** | **0.11** |
+ | Slack events dated after their page | 32 | 0 | 0 |
+ | Proposals dropped as `date_imprecise` | — | 9 | 6 |
+ | Events written | 386 | 303 | 315 |
+ | Cost per judged page | $0.0119 | $0.0105 | $0.0106 |
+
+ The remaining false events are quarter results ("Q1 revenue came in at $2.1M") dated on the meeting that discussed them; counted strictly, as the published review does. No control page was judged in any run. Method and receipts: `docs/fix-wave-notes/capy-chronicle-date-quality.md`.
+
+ ### What changed
+
+ - **No event after the page's own day.** The page's own day is the latest of its own date (frontmatter `date` or `start`, or an authored effective date), a calendar invite's `end` and a conversation's last message, read in `chronicle.tz`; anything on that day counts, and nothing after today does. Ended calendar invites still produce their meeting event.
+ - **No invented days.** The extractor writes a vague past date at its real precision ("2024", "2026-03"); the timeline stores days, so those proposals are dropped instead of pinned to the first of the year or month.
+ - **Drops are reported.** The `chronicle` phase result carries `events_dropped` by reason; a page whose every proposal was dropped records `future_dated` or `date_imprecise` on its ledger row instead of `no_events`. Both codes are in the reason table (`docs/guides/life-chronicle.md`) and the `chronicle_skipped` error-code registry.
+ - **Re-extraction still cleans up.** A changed page whose new proposals are all dropped retires its previous automatic events like any empty generation.
+
+ ## To take advantage of v0.60.49.0
+
+ `gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:
+
+ 1. **Run the orchestrator manually:**
+ ```bash
+ gbrain apply-migrations --yes
+ ```
+ 2. **Nothing else to migrate.** There is no schema change; the rules apply to every extraction from now on. Events already written stay until their page is extracted again.
+ 3. **Verify the outcome:**
+ ```bash
+ gbrain dream --phase chronicle --json # events_dropped lists refused proposals by reason
+ ```
+ 4. **If any step fails or the numbers look wrong,** please file an issue:
+ https://github.com/garrytan/gbrain/issues with:
+ - output of `gbrain doctor`
+ - contents of `~/.gbrain/upgrade-errors.jsonl` if it exists
+ - which step broke
+
+ This feedback loop is how the gbrain maintainers find fragile upgrade paths. Thank you.
+
+ ### Itemized changes
+
+ - `src/core/chronicle/extract-events.ts`: `chronicleJudgeContext` collects the page's dating instants (`pageDates`); `chronicleEventCutoff` and `screenChronicleProposals` drop `future_dated` and `date_imprecise` proposals; `buildChronicleEvents` returns `{ events, dropped }`; the judge prompt extracts only what happened and never invents a day; `runChronicleExtract` reports `events_dropped`.
+ - `src/core/chronicle/execute.ts`, `src/core/cycle/chronicle.ts`, `src/core/chronicle/job.ts`, `src/core/chronicle/contract.ts`: drop counts on the row outcome and in `ChronicleRunDetails.events_dropped`; an extracted row with a reason counts as `no_events`.
+ - `src/core/chronicle/reasons.ts`, `src/core/error-registry.ts`: `future_dated` and `date_imprecise`.
+
+ ### For contributors
+
+ - `test/chronicle-date-quality.test.ts` (+ `test/e2e/chronicle-date-quality-postgres.test.ts`): a past meeting mentioning a future offsite, "back in 2024", same-day events, ended invites, multi-day conversations, re-extraction cleanup and the cutoff arithmetic across time zones.
+
## [0.60.48.0] - 2026-10-04
**A managed Postgres brain now catches up a big sync backlog in one `gbrain sync` run, about 4.6 times faster, and the run tells your agent exactly what happened and what to do next (#5984).**
diff --cc TODOS.md
index 32138131b2,acf4bcdb8d..2dd4f59107
--- a/TODOS.md
+++ b/TODOS.md
@@@ -1,24 -1,16 +1,35 @@@
# TODOS
+## Foundations 2 crash robot follow-ups (filed 2026-10-04, follow-up from v0.60.53.0)
+
+Context: `scripts/persistence/README.md` ("Crash robot"), `scripts/persistence/{generator,model,crash-robot}.ts`.
+
+- [ ] **P2 — A restarted Postgres owner waits out its dead predecessor's claims.**
+ **What:** after a Postgres owner process dies, its running effects resume only when their 2-minute lease expires (requests: 30 s), and a withdrawal mirror it held blocks writes to that page until then. PGLite releases them at once (one process per datastore). **Why:** a crashed `gbrain serve` on Postgres stalls Git, embedding and withdrawal work for 2 minutes. **Fix:** record the claiming host and process (pid plus start time) on each claim; a consumer on the same host releases claims whose process has exited. Other hosts keep the lease. The crash robot then drops its 140 s Postgres drain bound to 20 s and pull requests stop skipping lease-bound seams. **Effort:** M. **Priority:** P2.
+- [ ] **P1 — A held sync lock reaches agents as internal_error.**
+ **What:** after an owner dies mid connector run, the source's sync lock row stays until its TTL lapses (a same-host dead holder is stolen after the grace window). Meanwhile a connector run (`LockUnavailableError`) and a sync (`SyncLockBusyError`) reach MCP callers as `internal_error` ("server-side failure, report it"). Crash robot: `sync_and_connector_race_direct_write`, seed 5105, SIGKILL at `publication:after_commit` #31 (Postgres), recorded under the manifest's `deferred`. **Why:** the agent reports a bug instead of waiting and retrying. **Fix:** map both errors to the registered `sync_in_progress` (retryable) with the holder, its age and the retry-after in `why`/`fix` (agent-output rows, GBRA-42's contract), then drop the robot's `KNOWN_DEFERRALS` entry and un-skip the test in `test/persistence-crash-robot.test.ts`. **Effort:** S. **Priority:** P1.
+- [ ] **P1 — Process faults: ENOSPC on the file target and a lost child exit.**
+ **What:** the robot covers SIGKILL at every seam, a stale `index.lock`, a hung git commit and Postgres session drops. **Fix:** an ENOSPC fault on the canonical file write (a tmpfs-sized checkout) and a git child whose exit event is lost; each must end in a terminal state or a typed error. **Effort:** M. **Priority:** P1.
+- [ ] **P1 — Seeded mutation pass over the coordinator and effects.**
+ **What:** report the robot's kill rate against seeded mutants (a dropped receipt update, a double-applied effect, a skipped withdrawal fence). **Effort:** M. **Priority:** P1.
+- [ ] **P1 — Source add/remove/refresh and writer activate/deactivate ops.**
+ **What:** the generator drives page, memory, takes, timeline, sync, connector and revocation ops; topology and writer-lifecycle ops are not in the protocol yet, so the existing `topology-clone.ts`, `topology-recovery.ts`, `worktree-refresh.ts` and `bundle-files.ts` boundary hooks are not crashed. **Effort:** M. **Priority:** P1.
+- [ ] **P2 — CI check that every mutating operation is registered in the generator.**
+ **What:** `MODEL` is a `Record<OpKind, Fold>` and `EFFECT_SEAMS` a `Record<EffectKind, …>`, so a new op kind or effect kind without a fold or seam fails typecheck; a new mutating operation in `operations.ts` is not forced into `OP_KINDS`. **Fix:** a test listing every `mutating: true` operation as either a robot op or an explicit exclusion with its reason. **Effort:** S. **Priority:** P2.
+- [ ] **P2 — Pre-activation claim lock order.**
+ **What:** the unmanaged `claimWorktree` locks brain > sources > worktrees; managed paths lock worktrees before sources. No publication runs before activation, so nothing deadlocks today. **Fix:** reorder the unmanaged claim to brain > worktrees > sources so `lock-order.ts` can trace setup too. **Effort:** S. **Priority:** P2.
+
+ ## Engine graduation follow-ups (filed 2026-10-04, GBRA-50)
+
+ Context: `docs/guides/move-to-postgres.md`, `docs/ENGINES.md#engine-migration-refused`.
+
+ - [ ] **P2 — Postgres → PGLite graduation.**
+ **What:** `gbrain migrate --to pglite` uses the legacy copier, which refuses any brain with write history, withdrawals or worktree ownership. **Why:** a brain that moved to Postgres (or started there) cannot come back to a single-machine PGLite brain without losing its history. **Fix:** a reverse adapter (Postgres source, PGLite target) for the graduation inventory, copier and verify in `src/core/persistence/engine-graduation.ts`, with the same plan, fence, verify, cutover and crash tests. **Effort:** L. **Priority:** P2.
+ - [ ] **P3 — `gbrain migrate --discard-source`.**
+ **What:** after a verified graduation the PGLite copy stays at `<path>.graduated-<run_id>` and the user deletes it by hand (doctor's `pglite_leftovers` names the command). **Why:** the copy still holds private memory and token hashes. **Fix:** a confirmation-gated command that deletes the retained copy and the tombstone only when the run is `graduated` and no rollback is pending, with `--yes --expect` and a dry run. **Effort:** S. **Priority:** P3.
+ - [ ] **P2 — Windows graduation.**
+ **What:** on Windows a PGLite brain with history gets `graduation_unsupported_platform` (history-free brains use the legacy copier). **Why:** the tombstone, kernel-lock retention and SIGKILL crash tests have not run on a Windows runner, so custody across a crash is unproven there. **Fix:** run the tombstone, older-binary and crash suites on a Windows CI runner, fix what fails, then lift the platform refusal. **Effort:** M. **Priority:** P2.
+
## Held files follow-ups (filed 2026-10-04, follow-up from v0.60.47.0)
Context: `docs/guides/repair.md#held-files`, `docs/guides/write-refusals.md#held-files-and-content-refusals`.
@@@ -106,30 -92,26 +117,30 @@@ Spec: `docs/designs/AGENT_OPERATOR_WAVE
## Foundations 1 follow-ups (filed 2026-10-03, follow-up from v0.60.37.0)
-- [ ] **P1 — Mutation attribution for the writers still unattributed.**
- **What:** creation attribution covers journaled and coordinated writes and four unmanaged legacy transactions; the writers listed under "unattributed" in `docs/architecture/system-of-record.md` (extract timeline, sync renames, enrichment, schema-pack conversions, legacy facts and takes helpers, and others) still write `NULL`. **Fix:** route them through `maintenanceTransaction` or the coordinator, shrinking the pinned list. **Effort:** L. **Priority:** P1 (Foundations 2).
-- [ ] **P2 — Classify new content columns for attribution.**
- **What:** a column added to `facts`, `takes` or `timeline_entries` must be classified in `persistence/attribution-schema.ts` (content vs projection), or an edit to it either misses `last_write_*` or stamps a projection-only update. **Fix:** a guard test that fails on an unclassified column. **Effort:** S. **Priority:** P2 (Foundations 2).
-- [ ] **P2 — Verify `gbrain repair attribution-backfill` on a real managed brain.**
- **What:** proven on PGLite, Postgres and PgBouncer fixtures only. **Fix:** run the preview and apply on a managed brain with real history and record the filled and unrecorded counts. **Effort:** S. **Priority:** P2 (Foundations 2).
-- [ ] **P2 — `--json` refusals from CLI-only ops print to stderr only.**
- **What:** `gbrain attribution --json` (and other CLI ops through the shared framework) write refusals to stderr, not as a JSON object on stdout. **Effort:** S. **Priority:** P2 (Foundations 2).
-- [ ] **P2 — PGLite `sources refresh` while `gbrain serve` owns the database.**
- **What:** the refresh needs the writer lock; with a resident serve on PGLite it waits or refuses. **Fix:** delegate the refresh over the local persistence IPC socket. **Effort:** M. **Priority:** P2 (Foundations 2).
-- [ ] **P3 — The consumer's idle probe ignores the refresh effect fence.**
- **What:** the resident consumer's idle tick does not consult an active refresh's fence before probing. Harmless today (the probe writes nothing). **Effort:** S. **Priority:** P3 (Foundations 2).
-- [ ] **P2 — Drop the JSONB grant authority for legacy tokens.**
- **What:** migrated tokens still mirror `permissions` JSON for older binaries, and admin-dashboard-created tokens are still born on the JSONB shape. **Fix:** after one release window, read only the unified columns and have the dashboard mint through `insertUnifiedToken`. **Effort:** M. **Priority:** P2 (Foundations 2).
-- [ ] **P2 — `--sources none` for OAuth clients.**
- **What:** refused for clients in F3 (no behavior change); needs per-client takes holders. **Effort:** M. **Priority:** P2 (Foundations 2).
-- [ ] **P2 — Seat follow-ups (#4618).**
- **What:** Codex hooks' trust hash changes when a seat is added; the harness Codex note should say so; OpenClaw's heartbeat does not report a seat write failure; a pattern page's `seat` is never removed when its sessions age out. **Effort:** M. **Priority:** P2 (Foundations 2).
-- [ ] **P2 — Large-brain ceilings in the 50k nightly.**
- **What:** the progress-aware sync deadline, 20k-file `sources add`, the loud embed budget stop and the serve boot window are pinned by unit and CLI tests, not yet asserted by the 50k scale-tier run; delegated syncs (serve-owned) are not yet progress-aware. **Effort:** M. **Priority:** P2 (Foundations 2).
+- [x] **P1 — Mutation attribution for the writers still unattributed.** **Completed: Foundations 2** — every unmanaged direct writer except three runs in `maintenanceTransaction` (batch writers one bounded transaction per batch); the pinned unattributed inventory went from 90 writer references in 40 files to 7 in 3. Pinned by `test/write-attribution-legacy.test.ts` and the `test/write-attribution-<family>.test.ts` files.
+- [ ] **P2 — Attribute the three link-extraction writers.**
+ **What:** `src/commands/extract.ts`, `src/core/extract-timeline-from-meetings.ts` and `src/core/enrichment-service.ts` still write `NULL` attribution on unmanaged brains (the "unattributed" list in `docs/architecture/system-of-record.md`). They share the link-extraction and mention-linking code that the entity-linking work is reshaping. **Fix:** after that work lands, run their writes in `maintenanceTransaction` (bounded per batch) and move them to the attributed list. **Effort:** S. **Priority:** P2.
+- [ ] **P2 — One write path for unmanaged brains.**
+ **What:** unmanaged brains attribute legacy writes through `maintenanceTransaction`, but those writes skip the coordinator's journal, receipts and effects, so the persistence crash harness (which drives the coordinator) does not exercise them. **Fix:** route unmanaged brains through the coordinator too, retiring the legacy direct writers. Deferred: it changes every unmanaged write path and its failure modes, which needs its own wave. **Effort:** XL. **Priority:** P2.
+- [ ] **P3 — Backfill attribution for pages a `forget` last changed.**
+ **What:** `gbrain repair attribution-backfill` proves page revisions only from page mutations and fenced `remember`; a page whose live revision came from a `forget` withdrawal stays `unrecorded` (3 of 40 pages in the history fixture). **Fix:** accept the committed `forget` request whose withdrawal outcome names that revision as proof. **Effort:** S. **Priority:** P3.
+- [x] **P2 — Classify new content columns for attribution.** **Completed:** the column classification test in `test/write-attribution.test.ts` (`write attribution column classification`) fails on an unclassified column.
+- [x] **P2 — Verify `gbrain repair attribution-backfill` on a real managed brain.** **Completed: Foundations 2** — `test/attribution-backfill-history.test.ts` builds a managed brain through the journaled operations, resets three quarters of the rows to pre-attribution NULLs and runs the repair. At 10,000 pages on Postgres (3,334 edits, 1,429 deletes, 715 restores, 2,000 remembers, 1,000 forgets) it refilled 6,868 of 7,509 reset pages, 5,502 of 5,609 page versions and 1,501 of 1,501 facts to the attribution the coordinator wrote; 641 pages and 107 versions stay `unrecorded` (their revision came from a `forget`), and no content, revision or existing attribution changed.
+- [x] **P2 — `--json` refusals from CLI-only ops print to stderr only.** **Completed (#5991):** `src/cli/cli-error.ts` prints one JSON refusal envelope on stdout under `--json`.
+- [x] **P2 — PGLite `sources refresh` while `gbrain serve` owns the database.** **Completed: Foundations 2** — the refresh runs inside the resident owner through the `writer_refresh` administration operation (`src/commands/sources-refresh-delegate.ts`).
+- [x] **P3 — The consumer's idle probe ignores the refresh effect fence.** **Completed: Foundations 2** — the idle probe applies `refreshFenceClear` to effects like the claims do.
- - [x] **P2 — Drop the JSONB grant authority for legacy tokens.** **Completed: Foundations 2** — the dashboard mints through `mintLegacyToken`, migration v201 converts every legacy grant, the HTTP auth paths read the columns (a later legacy row converts on its first read), and minting no longer writes a JSONB-only grant.
++- [x] **P2 — Drop the JSONB grant authority for legacy tokens.** **Completed: Foundations 2** — the dashboard mints through `mintLegacyToken`, migration v202 converts every legacy grant, the HTTP auth paths read the columns (a later legacy row converts on its first read), and minting no longer writes a JSONB-only grant.
+- [ ] **P2 — Remove the `permissions` grant mirror after its window.**
- **What:** tokens still write the `permissions` JSONB mirror and enforce drift until `GRANT_MIRROR_WINDOW_ENDS` (2026-11-04, `src/core/grants/model.ts`) so older binaries keep working. **Fix:** after that date stop writing the mirror, drop the drift comparison and `legacy_token_grant_drift`, and keep `migrateLegacyTokens` only for brains that skipped v201. **Effort:** M. **Priority:** P2.
- - [x] **P2 — `--sources none` for OAuth clients.** **Completed: Foundations 2** — `auth rescope --client <id> --sources none` and `--takes-holders a,b|none` (migration v202).
++ **What:** tokens still write the `permissions` JSONB mirror and enforce drift until `GRANT_MIRROR_WINDOW_ENDS` (2026-11-04, `src/core/grants/model.ts`) so older binaries keep working. **Fix:** after that date stop writing the mirror, drop the drift comparison and `legacy_token_grant_drift`, and keep `migrateLegacyTokens` only for brains that skipped v202. **Effort:** M. **Priority:** P2.
++- [x] **P2 — `--sources none` for OAuth clients.** **Completed: Foundations 2** — `auth rescope --client <id> --sources none` and `--takes-holders a,b|none` (migration v203).
+- [x] **P2 — Seat follow-ups (#4618).** **Completed: Foundations 2** — the OpenClaw context-engine heartbeat reports seat reasons (write failure, conflict, invalid label) with their hints, and a pattern page drops a seat its reflections no longer share. The Codex trust-hash item closed with no code: the Codex SessionEnd command never carries a seat (`buildCodexSessionEndCommand` takes only the gbrain binary; `--seat` prints a note to set `GBRAIN_SEAT` instead), so adding a seat cannot change its trust hash.
+- [x] **P2 — Large-brain ceilings in the scale tier.** **Completed: Foundations 2** — every scale run asserts the F4d ceilings through the real CLI (`scripts/scale/f4d.ts`: progress-aware sync deadline, loud embed budget stop and serve boot window at every tier, the 20,000-file `sources add` at 20k and up), so the 50k tier carries them once `trend.ts` unlocks it; delegated syncs keep the progress-aware deadline.
+- [ ] **P2 — MCP search on Postgres slows sharply between 10k and 20k pages.**
+ **What:** the scale tier's MCP-path search p50 on Postgres is 615 ms at 20k pages (69.5 ms at 10k) and the source-scoped grant search 1,169 ms, while PGLite at 20k answers in 27 and 19 ms. Interactive ceilings are defined only up to 10k, so this is report-only. **Fix:** read the captured plans in the 20k Postgres report (`scale-report-postgres-20000`) for the statement that grows, and add a 20k ceiling once fixed. **Effort:** M. **Priority:** P2.
+- [ ] **P3 — `embed --stale` takes far longer than its time budget to stop.**
+ **What:** with `GBRAIN_EMBED_TIME_BUDGET_MS=1500` the scale tier's budget-stop check exits 11 correctly but after about 61 s on a 20k brain (2.6 s on an empty one), so the budget does not bound wall time. **Fix:** profile what runs before the first batch and after the stop (stale counting, the remaining-count query) and keep it inside the budget. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — `findOrphans` recomputes the full orphan set per call.**
+ **What:** `find_orphans` pages its rows in TypeScript after computing every orphan, so each page of a large result costs a full scan (the scale verifier reads `total_orphans` and one maximal page instead of paging). **Fix:** page in SQL with `ORDER BY source_id, slug LIMIT/OFFSET` and a separate count. **Effort:** S. **Priority:** P3.
- [ ] **P3 — Keyword search scoped to one source: 18.2 to 22.1 ms at 10k PGLite pages.**
**What:** the five-run ranges overlap (17.4-19.4 vs 18.7-25.0 ms), so this may be noise; the scale tier's calibrated budget will show a trend. **Effort:** S. **Priority:** P3 (Foundations 2).
- [ ] **P3 — Enforce the scale tier's ceilings and calibrated budgets.**
@@@ -3367,14 -3349,16 +3378,14 @@@ which inverts the intent of the metric
Deferred from the #2529/#2477 security-fix wave (plan-eng-review + codex outside
voice CLEARED). None block the wave.
-- [ ] **P2 — Per-OAuth-client `takes_holders` storage (#2529 follow-up).** Legacy
- bearer tokens honor `access_tokens.permissions.takes_holders` through
- `verifyAccessToken`; OAuth clients have no equivalent column on `oauth_clients`,
- so OAuth-minted tokens fail closed to `['world']`. Needs a schema migration
- (`oauth_clients.takes_holders` JSONB or TEXT[]) + a `register-client` flag +
- the `verifyAccessToken` JOIN projection. Include surfacing the EFFECTIVE
- takes-holder scope in `whoami` output as part of this follow-up, so operators
- can self-diagnose the legacy-vs-OAuth semantic split instead of reading docs.
- Where: `src/schema.sql`, `src/core/migrate.ts`, `src/core/oauth-provider.ts`,
- `src/commands/auth.ts`, `src/core/operations.ts` (whoami).
+- [x] **P2 — Per-OAuth-client `takes_holders` storage (#2529 follow-up).**
- **Completed: Foundations 2** — `oauth_clients.takes_holders` (migration v202),
++ **Completed: Foundations 2** — `oauth_clients.takes_holders` (migration v203),
+ set with `gbrain auth rescope --client <id> --takes-holders a,b|none`, read by
+ `verifyAccessToken` and the publication holder reauthorization.
+- [ ] **P3 — `register-client --takes-holders` and effective holders in `whoami`.**
+ **What:** a client's holders are set after registration with
+ `auth rescope --client`; registration takes no holder flag, and `whoami` does
+ not print the effective takes-holder scope. **Effort:** S. **Priority:** P3.
- [ ] **P3 — agent-voice Host-header allowlist (DNS-rebinding hardening).** The
#2477 fix ships default-deny CORS + an Origin gate on `/session`/`/tool`, but
the gate derives self-origin from the `Host` header, so a DNS-rebound page
diff --cc docs/ENGINES.md
index 1df2cd9cdb,416519c767..a38276dbf0
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@@ -299,29 -303,37 +303,37 @@@ The legacy copier handles every other d
| Refusing side | `fix.next` | Next step |
|---|---|---|
- | A PGLite brain moving to Postgres (history or managed) | `ask_user` | Relay `user_message`: keep the brain on PGLite and share it with other machines through `gbrain mcp expose` (effects `persistent_install`, `egress`), or leave it as it is. A verified PGLite-to-Postgres graduation that carries this history is not available yet. |
-| A PGLite brain with history moving to Postgres with graduation turned off | `ask_user` | Relay `user_message`: graduation moves this brain (`gbrain config unset migrate.graduation`, then the [two-command flow](guides/move-to-postgres.md#move-the-brain)), or keep it on PGLite and share it through `gbrain mcp expose`. |
++| A PGLite brain with history (or a managed one) moving to Postgres with graduation turned off | `ask_user` (consent `egress`) | Relay `user_message`: turn graduation back on (`fix.argv`: `gbrain config unset migrate.graduation`) and preview the move with the read-only plan (`fix.then`: `gbrain migrate --to postgres --url-env GBRAIN_TARGET_URL --plan --json`, then the [two-command flow](guides/move-to-postgres.md#move-the-brain)), or keep it on PGLite and share it through `gbrain mcp expose`. |
| A Postgres brain moving to PGLite | `report` | The brain stays on Postgres; moving down would drop its history. |
- | A target that already holds persistence history | `tell_user_to_run` | `gbrain migrate --to <engine> --url <empty_database_url>` with an empty database the user provides (`--path` for a PGLite target). |
-
-
- The migration and the autopilot daemon do not race: `migrate --to` claims a
- cooperative pause marker before touching the target. The marker doubles as a
- migration mutex — a second concurrent migrate refuses to run, and a marker
- that cannot be written refuses the migration outright. Background job workers
- stop picking up new work while it is parked, and the migration waits for
- in-flight sync/embed/cycle work and running jobs to actually drain (watching
- the DB lock table, capped by `GBRAIN_MIGRATE_QUIESCE_SECONDS` — default 300;
- `0` skips the wait). Cleanup registers the moment the claim lands, so the
- marker is released on failure and on catchable signals; a marker orphaned by
- an uncleanly killed run is adopted by a later migrate only after a
- pid-liveness check (a live migrate's marker is never stolen), and the daemon
- clears an orphan whose owning process died on its next poll. `gbrain
- autopilot --status` reports `paused` (exit 1) while the marker is parked and
- prints the marker path; on a host with no daemon running to self-heal,
- remove an orphan by hand only after confirming the pid it names is dead.
- After a clean flip the daemon detects the engine change on its next
- tick and relaunches onto the new engine, and the migration warns if an
- exported connection-string env var would override the new config.
+ | A target that already holds persistence history | `tell_user_to_run` | Rerun with an empty database the user provides (`--path` for a PGLite target). |
+
+ On Windows, a PGLite brain with history gets `graduation_unsupported_platform` instead: it stays on PGLite and is shared with `gbrain mcp expose`.
+
+ <a id="graduation-writer-held"></a>**Graduation refused: the brain is held (`graduation_source_writer_held`).** Graduation needs the PGLite kernel lock. A live stdio `gbrain serve` hands the brain over through the intent marker `<path>.gbrain-graduation.json` and exits; autopilot pauses. When another holder (an HTTP serve, a daemon, another command) does not release the brain within 30 seconds, the run refuses and names it with its pid and transport (`fix.next: tell_user_to_run`). The user stops that process, then the agent reruns the same `gbrain migrate` command. Verify with the read-only `gbrain migrate --status --json`. Nothing has changed in either datastore.
+
+ The migration and the autopilot daemon do not race: both graduation and the
+ legacy copier claim a cooperative pause marker before touching the target. The
+ marker doubles as a migration mutex — a second concurrent migrate refuses to
+ run (graduation exits 75 with `graduation_in_progress`), and a marker that
+ cannot be written refuses the migration outright. Background job workers stop
+ picking up new work while it is parked. The legacy copier then waits for
+ in-flight sync/embed/cycle work and running jobs to drain (watching the DB lock
+ table, capped by `GBRAIN_MIGRATE_QUIESCE_SECONDS` — default 300; `0` skips the
+ wait). Graduation holds the PGLite kernel lock instead, so no other process has
+ the brain open: expired run locks and active job leases are orphans it resets
+ at once, and it waits only for queued write requests, bounded by
+ `--drain-timeout` (default 60 seconds; exhaustion exits 11 with a
+ `resume_command`). Cleanup registers the moment the claim lands, so the marker
+ is released on failure and on catchable signals; a marker orphaned by an
+ uncleanly killed run is adopted by a later migrate only after a pid-liveness
+ check (a live migrate's marker is never stolen), and the daemon clears an
+ orphan whose owning process died on its next poll. `gbrain autopilot --status`
+ reports `paused` (exit 1) while the marker is parked and prints the marker
+ path; on a host with no daemon running to self-heal, remove an orphan by hand
+ only after confirming the pid it names is dead. After a clean flip the daemon
+ detects the engine change on its next tick and relaunches onto the new engine,
+ and the migration warns if an exported connection-string env var would
+ override the new config (graduation lists such a variable as a plan blocker).
### Troubleshooting: startup abort (`RuntimeError: Aborted()`)
diff --cc docs/architecture/KEY_FILES.md
index 2efc5ebe76,9f47ae86b9..0a194b5b47
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@@ -44,9 -44,10 +44,11 @@@ boundary and add its link here rather t
| [Core Minions (2/2)](key-files/core-minions-2.md) | `src/core/minions/run-child.ts` through `src/core/minions/worker.ts` |
| [Core Persistence](key-files/core-persistence.md) | `src/core/persistence/` write journal, coordinator, effects, canonical projections and managed sync |
| [Core Persistence (continued)](key-files/core-persistence-continued.md) | `src/core/persistence/connector-*.ts`, `src/core/connectors/item-holds*.ts`, checkpoint validation, no-op kernel and accepted-pending receipts |
+ | [Core Persistence (engine graduation)](key-files/core-persistence-graduation.md) | `engine-graduation*.ts`, `graduation-*.ts`, `src/commands/migrate-graduation.ts`, the graduation doctor finding |
| [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/rerank.ts` |
| [Core Search (2/2)](key-files/core-search-2.md) | `src/core/search/return-policy.ts` through `src/core/search/vector-pool.ts` |
--| [Core Services (1/3)](key-files/core-services-1.md) | `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` through `src/core/context/ipc-path.ts` |
++| [Core Services (1/3)](key-files/core-services-1.md) | `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` through `src/core/connectors/` |
++| [Core Services (1/3, continued)](key-files/core-services-1-continued.md) | `src/core/context/` through `src/core/context/ipc-path.ts` |
| [Core Services (2/3)](key-files/core-services-2.md) | `src/core/conversation-parser/` through `src/core/progressive-batch/`, except `src/core/persistence/` |
| [Core Services (3/3)](key-files/core-services-3.md) | `src/core/think/index.ts` through `src/core/verbs/usage-log.ts` |
| [Core Utilities (1/2)](key-files/core-utilities-1.md) | `src/core/archive-crawler-config.ts` through `src/core/remediation-checkpoint.ts` |
diff --cc docs/architecture/key-files/commands-4.md
index b6960db9ca,63b2baa4fb..d8a26e1993
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@@ -18,9 -18,9 +18,9 @@@ Current behavior and load-bearing invar
- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. `jobs-readiness.ts` orchestrates bounded driver-lane and selected-child readiness before worker schema/recovery, handler registration or claims. After `ensureSchema`, `maybeRunWorkerStartupRecovery(queue, process.env, true)` runs for both bare and supervised workers; the final worker `ready` event publishes readiness, and a worker handed an owner status channel (`GBRAIN_WORKER_STATUS_PATH` or `GBRAIN_WORKER_STATUS_TOKEN`, even partially) refuses admission if its status cannot be published, while a legacy supervised worker (`GBRAIN_SUPERVISED=1` from a pre-0.59.1 owner, no channel) publishes nothing and proceeds; typed faults report `configuration_blocked` and exit `WORKER_EXIT_CONFIGURATION`, while transient readiness failures admit no jobs and remain retryable. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the `JOBS_SUBCOMMANDS` dispatch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.serial.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `jobs work` (`src/commands/jobs/work.ts`) wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` only when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status --json` adds `processing_ready`, lowercase `processing_state` (`starting`/`ready`/`configuration_blocked`, or `unknown`/`stopped` without current state), `reason_code`, `blocked_since` and worker/child identities without changing `running` or crash counters. A live local pidfile keeps this diagnostic engine-free; a missing pidfile retains the DB-lock fallback. It consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output includes per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `jobs work` resolves the actual selected child and validates its bounded protocol/capability handshake and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `jobs run-child` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes. `jobs work` registers the shell handler always; the startup line names the flag first (`--allow-shell-jobs` / `GBRAIN_ALLOW_SHELL_JOBS=1`); `jobs start` computes `allowShellJobs` as `--allow-shell-jobs || GBRAIN_ALLOW_SHELL_JOBS === '1'` — the same literal `handlers/shell.ts` and `buildChildArgs` check. `extract-atoms-drain` accepts a trusted `retryRequestId` in submitted params; a new job ID distinguishes a newly approved malformed-output provider attempt from provider-free publication replay. PGLite `jobs --follow` still requires exclusive owner access. D2: `jobs supervisor start --detach` writes its payload (`event`, `status:'started'`, `supervisor_pid`, `pid_file`, `detached`, `stderr_log`) through `writeStdoutFinal`; the `jobs` record declares no `json` because work/watch/foreground supervisor stream. Start refusals add an envelope under `--json` (`invalid_params` exit 2 for an unknown subcommand or bad `--health-interval`, `config_error` for PGLite).
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). `runJobs` resolves help and the thin-client refusal, builds the queue, then dispatches through `JOBS_SUBCOMMANDS` (Object.hasOwn lookup, same unknown-subcommand error) to one module per subcommand in `src/commands/jobs/<sub>.ts` (`runJobs<Sub>(ctx)`; parsers, formatters and `JobsCommandContext` in `jobs/shared.ts`; `maybeRunWorkerStartupRecovery` in `jobs/work.ts`), all re-exported from `jobs.ts`. Subcommands that register handlers import `registerBuiltinHandlers` lazily from `jobs.ts`. `registerBuiltinHandlers` is the ordered registration table (worker.register vs gateway-refreshing registerBuiltinJob stay here); handler bodies live in `src/core/minions/handlers/` (see core-minions-1). Registration names and order are pinned by `test/jobs-handler-registry-golden.test.ts`, which also drives the supervisor's `deriveHandlerNames` probe.
-- `src/commands/jobs.ts:refreshGatewayForJob` + `src/core/ai/gateway.ts:refreshGatewayEnvFromFilePlane` — long-lived-worker staleness boundary, three tiers: (1) DB-plane model config re-resolves per gateway-refresh job (`reconfigureGatewayWithEngine`); (2) FILE-plane config (`~/.gbrain/config.json`, incl. provider API keys) re-folds per job via the env-ONLY `refreshGatewayEnvFromFilePlane` — never a full `configureGateway(buildGatewayConfig(loadConfig()))`, which would clobber DB-plane-merged fields (base_urls, chat options) with file-plane-only values; (3) true process env vars are fixed at worker start and need a restart. `gbrain config set *_api_key` writes the DB plane, which `loadConfigWithEngine()` deliberately never merges for key fields — those writes do NOT reach workers (TODO filed to reroute them to the file plane). `facts-absorb` sits in `GATEWAY_REFRESH_JOB_NAMES`; its handler converts execution-time `chat_unavailable` in a KEYED worker into a typed retryable failure (`factsAbsorbShouldRetry`) while a keyless worker completes the job as a calm skip. Pinned by `test/jobs-gateway-refresh.serial.test.ts`.
+- `src/commands/jobs.ts:refreshGatewayForJob` + `src/core/ai/gateway.ts:refreshGatewayEnvFromFilePlane` — long-lived-worker staleness boundary, three tiers: (1) DB-plane model config re-resolves per gateway-refresh job (`reconfigureGatewayWithEngine`); (2) FILE-plane config (`~/.gbrain/config.json`, incl. provider API keys) re-folds per job via the env-ONLY `refreshGatewayEnvFromFilePlane` — never a full `configureGateway(buildGatewayConfig(loadConfig()))`, which would clobber DB-plane-merged fields (base_urls, chat options) with file-plane-only values; (3) true process env vars are fixed at worker start and need a restart. `gbrain config set *_api_key` writes the DB plane, which `loadConfigWithEngine()` deliberately never merges for key fields — those writes do NOT reach workers (TODO filed to reroute them to the file plane). `facts-absorb` sits in `GATEWAY_REFRESH_JOB_NAMES`; its handler converts execution-time `chat_unavailable` in a KEYED worker into a typed retryable failure (`factsAbsorbShouldRetry`) while a keyless worker defers it (`JobDeferredError`, 30 min, no attempt counted) so the backlog runs once a key exists. Pinned by `test/jobs-gateway-refresh.serial.test.ts`.
- - `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. Rule `type-undeclared` flags an explicit frontmatter `type` the active schema pack neither declares nor aliases (resolved once per run from the shared/probed engine's DB-plane `schema_pack`, else file/env config; no resolvable pack skips it; `LintOpts.typePack` injects it), pinned by `test/lint-page-type-vocabulary.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions.
+ - `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. Rule `type-undeclared` flags an explicit frontmatter `type` the active schema pack neither declares nor aliases (resolved once per run from the shared/probed engine's DB-plane `schema_pack`, else file/env config; no resolvable pack skips it; `LintOpts.typePack` injects it), pinned by `test/lint-page-type-vocabulary.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions. On a managed brain (persistence enabled) `runLintCore` skips the legacy filesystem lock and publishes each repair through the persistence coordinator (`maintenancePreflight` + `publishMaintenancePage`: DB row and worktree file in one guarded write) instead of writing the file; a file with no indexed page, or a page that changed mid-scan, is reported as a non-fixable `managed-write-pending` issue and retried next cycle (`LintResult.write_path` / `fix_pending`; #5180).
- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override]` (alias: `gbrain retrieval-upgrade`). ONE shared orchestrator for CLI and the `migrate_embeddings` op: `planMigrationFlow` (plan + `verifyMigrationComplete` + env presence + un-merged file plane + brain/DB identity via `redactPgUrl` + concurrent-writer census + reranker plan + in-flight-other marker) and `executeMigrationFlow` (global `gbrain-embedding-migration` DbLock → retarget gate under it → all-source embed locks sorted with `includeArchived` → worst-case authorization under the locks (a cap below it returns `refused_budget` / op `refused` with `embedding_budget_below_worst_case` before any provider call or invalidation) → live embed probe → apply → reranker probe + switch → drain via `runEmbedCore({heldLocks, …})` so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as `lock_lost` → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on `verify.complete` with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). `--status` is read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome). `persistEmbeddingFileConfig` writes through `loadConfigFileOnly` (never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 3 consent required (agent operator wave C2: `requireConsent` with effects `paid` + `destructive`; `spend.posture=tokenmax` covers only the paid part, `--json` never implies consent, the payload's fix repeats the caller's argv plus `--yes`; the TTY prompt is interaction.readLine, and the `confirm`/`isTTY` test seams map onto ConsentEnv). Spend stays bounded by the durable `--max-cost-usd` authorization, not the consent cap. Pinned by `test/migrate-embeddings-flow.serial.test.ts`, `test/migrate-embeddings-boundary.serial.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`. Migration guidance uses `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`) to keep supported targets and dimensions consistent.
diff --cc docs/architecture/key-files/core-persistence-continued.md
index 42edf1385a,e525ef0dc0..9507b2927c
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@@ -18,4 -18,6 +18,7 @@@ Managed connector ingestion, connector
- `src/core/persistence/sync-waivers.ts` — managed-sync no-op waivers (#5470, #5984). `waiveNoopEntry` screens a frozen, unadmitted entry: an unchanged import (`unchangedSyncImport`, moved here from `sync-run.ts`, with the #5751 working-tree kernel waivers) or a delete whose page is already soft-deleted at the entry's frozen `expected_revision` with its file absent (never an unowned deletion or a rename). A candidate runs `validateSyncAuthority` first (a revoked grant throws before any waiver), then commits in one transaction with a fixed lock order: page guard (`lockPageKeys`), then the managed-sync cursor row `FOR UPDATE`; it re-reads the snapshot (and, for deletes, the origin and file absence) and refuses while `UNFINISHED_PAGE_REQUEST_SQL` finds an unfinished request for the page by slug, page id or a `renameFrom` naming it. That lookup is three `LIMIT 1` branches served by `persistence_requests_pending`, `persistence_requests_recovery` and the database-only pending index (EXPLAIN pinned in `test/persistence-managed-sync.test.ts`). A cursor that moved meanwhile is adopted instead of waived again, so `waived` counts only increment in the winning transaction. `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry. Tests: `test/persistence-managed-sync.test.ts` (#5984 waiver cases), `test/persistence-sync-legacy-files-5751.test.ts`.
- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget.
- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load, and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.
+- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`) and `consumer:prepared` (between preparing a claimed request and publishing it). Used by `scripts/persistence/crash-robot.ts`.
+ - `src/core/persistence/graduation-target.ts` — engine graduation target side. `resolveTargetRoutes` reads the URL from `--url` or the `--url-env` variable and resolves the DDL route once (explicit `GBRAIN_DIRECT_DATABASE_URL`, else the Supabase direct derivation, else the main URL); `connectTargetEngines` hands that route to the connection manager as an explicit override, so no session-pooler fallback is chosen for the run. `targetIdentity` hashes host, port, database and user, never the password; `redactTargetUrl` is the only display form. `probeTarget` runs read-only probes in `BEGIN READ ONLY` sessions on both routes (server version, `vector` with halfvec, CREATE privilege, `session_replication_role` permission inside a savepoint, table ownership, seed-only emptiness, existing embedding columns, the role's superuser and BYPASSRLS standing and the auto-RLS event trigger and its function owner); `targetProbeBlockers` (non-superuser targets get the exact SQL a DBA runs for `vector`, BYPASSRLS and the event trigger) and `assertTargetReachable` turn a probe into plan blockers and typed refusals. `crossCheckRoutes` proves both routes reach one database with a transaction-scoped advisory lock keyed by a fresh nonce, read back from `pg_locks` through the other route. Tests: `test/graduation-target.test.ts`.
+ - `src/core/persistence/graduation-drain.ts` — engine graduation drain. `graduationBlockers` lists what keeps a brain from copying, each with its structured action: requests this host owns (drained), requests and host bindings owned by another host, recovering topology changes and effects, the writer admin lock, and OAuth clients bound to a missing source (an FK only Postgres enforces; never cleared silently, since unbinding widens access). `drainForGraduation` refuses up front on anything the drain cannot clear, then publishes this host's queued, running and recovering requests with a `requestsOnly` `PersistenceConsumer` bounded by the timeout and always runs its stop barrier before returning; the `graduation_drain_timeout` refusal is built by `graduation-errors.ts`. `freezeSource` stops the resident consumer and sets the PGLite connection to read-only transactions; `withSourceWritable` runs one read-write transaction for custody writes. Tests: `test/graduation-drain.test.ts`.
+ - `src/core/persistence/graduation-copy.ts` — engine graduation copier (in process). `copyTable` reads source rows through the digest's own plan (`digestPlan` with inventory transforms, `rowFilter`, `::text` values, COLLATE "C" keyset batches) and writes them in one target transaction per table that sets `gbrain.graduation_run`, bypasses user triggers (`session_replication_role = replica`, or DISABLE/ENABLE TRIGGER by name in the same transaction, never the `gbrain_graduation_fence` triggers), deletes the target's rows (seed rows included) and inserts byte-sized batches as one `$1::text::jsonb` array cast back per column type. The per-column contract (`columnContract`) refuses missing, retyped, target-only or differently generated columns outside the entry's `columnAllowlist`; generated columns are never inserted. Self-FKs take a second update pass under DISABLE TRIGGER. `copySequences` applies each source sequence's exact position, raised to the target column maximum. `deferIndexes`/`buildDeferredIndexes` drop and rebuild HNSW (through `buildDeferredAnnIndexes`) and GIN indexes, keeping the pending list in the target-owned `graduation.deferred_indexes` config row. Tests: `test/graduation-copy.test.ts`, `test/e2e/graduation-copy.test.ts`.
diff --cc docs/architecture/key-files/core-persistence.md
index 60998a958f,cea3ce4095..0c0466cf4c
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@@ -26,7 -26,7 +26,7 @@@ Connector ingestion, item holds and che
- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
- - `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.
-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.
++- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier.
- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.
diff --cc docs/architecture/key-files/core-services-1-continued.md
index 0000000000,0000000000..ee435b55d6
new file mode 100644
--- /dev/null
+++ b/docs/architecture/key-files/core-services-1-continued.md
@@@ -1,0 -1,0 +1,11 @@@
++# Key files: Core Services (1/3, continued)
++
++[Subsystem index](../KEY_FILES.md) · [Previous entries](core-services-1.md). Read only the entries relevant to your change.
++Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
++The Retrieval Reflex and session-context helpers under `src/core/context/`.
++
++- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; `visibility: private` (and derived-private) pages never resolve on any arm unless the caller passes `excludePrivate: false` (default true, the remote-search predicate `privatePagesFilterFragment`; only `volunteer_context` widens, via `resolveExcludePrivatePages` for a trusted local caller — gbrain-evals N8-1/N8-2, pinned by `test/reflex-private-visibility.test.ts`); capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor/checks/verbs-reflex.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract) — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs and pass `excludePrivate: true` on every arm, so private pages never reach the compiled file; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT.
++- `src/core/context/hook-heartbeat.ts` — the hooks telemetry plane under `<gbrain home>/integrations/hooks/` (`heartbeat.jsonl`, `status.json`, session receipts, the memorable relay log; directories 0700, appends 0600). Entries hold counters, durations and codes only: `HEARTBEAT_ALLOWED_KEYS` is the full key allowlist CI greps the fixture against, and includes `pattern` (scanner pattern name), `fingerprint` (`sha256:<16 hex>`) and `hint` (fixed text) for refusals. `near_duplicate` is the shadow count on the `writeback_dedup` event that `facts/capture-dedup.ts` appends (lane in `reason`, exact drops in `duplicate`). `relayRefusalHeartbeat(hit)` builds the line `context-engine.ts` writes when its high-entropy re-scan refuses a memorable relay (`event: relay`, `outcome: degraded`, `reason: secret_scan_refused`); the receipt and relay are skipped for that compaction window and the checkpoint is kept. `memorableGateAllowed` gates the relay lane; span redaction runs `redactFindings` with `highEntropy: true`. Tests: `test/context-engine-checkpoint.serial.test.ts`.
++- `src/core/context/seat.ts` — seat identity for captured sessions (#4618), engine-free. `resolveSeat` returns the lowercased `GBRAIN_SEAT` label when it matches `SEAT_LABEL_RE` (`^[a-z0-9][a-z0-9._-]{0,63}$`), else `home-<8 hex>` over the realpath of the harness home (Claude Code: the directory holding `projects/` in the transcript path, then `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `~/.claude`; codex: `CODEX_HOME` or `~/.codex`; OpenClaw: the agent directory holding `sessions/`), so no raw path reaches frontmatter; `GBRAIN_SEAT=off` (the opt-out) resolves to null and nothing is recorded. `writeSeatSidecar` writes `<sessionId>.seat.json` (`{version: 1, seat, seat_source, hook_lane, harness, first_seen}`, 0600, tmp+rename) unless one exists, reporting `seat_conflict` when the existing seat differs; `readSeatSidecar` accepts only a valid v1 record. `SEAT_REASON_HINTS` holds the fixed heartbeat hints. The sidecar name and its GC live in `corpus-segments.ts` (`seatFileName`, `SEAT_SIDECAR_SUFFIX`).
++
++- `src/core/context/ipc-path.ts` — engine-free local socket discovery and private Unix fallback when the complete role-specific address exceeds 103 UTF8 bytes. Hashes the physical parent plus basename under a fixed OS temporary root, verifies ownership/0700 directory/0600 client socket without following fallback symlinks, and retains a native binding claim through actual server close. Existing Unix socket accessibility is rechecked even when a runtime reports ENOENT; permission/resource probe failures never authorize stale takeover; Windows named pipes retain a native Global mutex through actual close; `windows-ipc.ts` normalizes namespace prefixes while native Windows Unicode casing defines the mutex identity. `test/local-ipc-path.test.ts` covers concurrent real processes, SIGKILL recovery, active-connection shutdown, aliases and unsafe paths. The published CLI smoke also uses a long Unicode datastore path.
diff --cc docs/architecture/key-files/core-services-1.md
index c8f6735c79,2eafe88e0f..4531425c57
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@@ -29,7 -29,7 +29,7 @@@ Current behavior and load-bearing invar
- `src/core/agent-markers.ts` — the one `[AGENT] … [/AGENT]` / `[SHOW USER]` builder (`agentBlock`): fixed field vocabulary, every value through `inertText()` so interpolated text cannot open or close a block.
- `src/core/budget/no-pricing.ts` — the one `no_pricing` refusal builder. `noPricingGuidance(model, kind)` returns the structured fields (`code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope: 'local_cli'`, `docs` = the `ERROR_CATALOGUE.no_pricing` anchor); `noPricingMessage` renders the one-line cause plus `noPricingSteps` (look up the provider's price, run the `gbrain pricing set` command on the brain host, retry; remote MCP callers ask the operator); `pricingSetCommand` gives the command alone for warnings (chat: `--input`/`--output`, other kinds: `--rate`), rendered from `pricingSetArgv`; `noPricingFix(guidance, transport)` is the agent-contract `fix` for a user-cap refusal (the registration argv with `inputs` for each rate and the pricing page). Used by BudgetTracker, enrich, conversation facts (CLI and cycle phase), skillopt receipts, the embedding migration authorization and the extract-atoms, budget-meter, embed-backfill and conversation-budget warnings. Pinned by `test/budget/no-pricing-registration.test.ts`.
- - `src/core/chronicle/{contract,eligibility,config,reasons,ledger,ledger-stats,execute,publish,event-identity,invite-projection,backfill,job,upgrade-notice,extract-events,ontology,narrative}.ts` + `src/core/cycle/chronicle.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `contract.ts` holds the ledger columns, the extractor version (part of the ledger key: a bump makes extracted content new to discovery and backfill), the phase bounds and the phase result details. `reasons.ts` is the one reason table (`CHRONICLE_REASONS`: stage, meaning, stored fix Action with argv/preview_argv/consent/actor, never a stored `next`; `auto_chronicle_off` has no fix because it is off by choice) and builds the `chronicle_backstop` receipt field (`{pending:'next_cycle', daily_remaining}` or `{skipped, stage, why, fix}`, omitted for pages that are not chronicle-shaped); `docs/guides/life-chronicle.md` renders its table from it. `eligibility.isChronicleEligible` is the one eligibility function (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop); with a time policy it also applies the invite end (`not_yet_happened`), the recency window on the page's own date (an authored `effective_date`, else frontmatter `date`/`start`; a `fallback` date counts as undated) and the settle window. `config.ts` owns the switch and knobs: `autoChronicleSetting` reads `auto_chronicle` as on when unset, on/off for true/false words, and `invalid` (off) for any other word; `chronicleSettings` reads `chronicle.job_budget_usd`/`auto_daily_limit`/`auto_recent_days`/`auto_settle_seconds`/`judge_max_tokens` with ranges (`CHRONICLE_NUMERIC_KEYS`, enforced by `config set`; a malformed stored row falls back and is listed in `invalid`) and `chronicle.activated_at` (stamped by the first write decision or phase run; earlier revisions are history); `autoChronicleNeedsAcknowledgement` is true while on and `chronicle.default_on_acknowledged` is unset (stamped by `config set auto_chronicle`). The opt-out is `gbrain config set auto_chronicle false` everywhere. `ledger.ts` owns `chronicle_page_state` (one row per source/page/content hash/extractor version: state, reason, trigger, deciding writer and request, `no_extract`, attempts, `next_attempt_at`, cost/unpriced, event slugs and hashes): `recordChronicleDecision` runs inside every coordinated publication that imports a page (from `queuePublicationEffects`), applies the shared writer-confinement predicate, `--no-extract`, the opt-out and eligibility, and puts `chronicle_backstop` on the outcome through `reasons.ts`; `reserveChronicleSlot` is the rolling 24 h reservation under a transaction advisory lock. `ledger-stats.ts` rolls up the ledger and reservations for doctor and the advisor. `upgrade-notice.ts` is the one-shot post-upgrade notice (`chronicle.default_on_notice_shown`). The global `chronicle` cycle phase (`cycle/chronicle.ts`) supersedes rows whose content is no longer live, discovers pages changed since activation with no row (unmanaged brains decide there; managed ones record `no_write_decision`), and executes settled rows round-robin across sources (≤50 judged items and a wall-time bound per run; automatic rows only while `auto_chronicle` is on, backfill rows always); no chat provider → no calls; the extract_atoms cost gate refuses an explicit cap on an unpriced model. `execute.ts` runs one row: live-content check, time rules, the reservation (automatic rows; attempts count), the judge in a `chronicle:<trigger>` BudgetTracker scope with the per-page cap and an explicit post-call cap check, failure classes (chat_error/budget → failed with backoff, no provider/no_pricing → failed until config changes, refused → skipped, only a parsed `[]` is `no_events`). `invite-projection.ts` stands in for the judge on an ended calendar invite (slug under `calendar/`/`cal/` or type `calendar-event`, with a title, `start` and `end`): one `Scheduled: <title>` event (`kind: meeting`, `captured_via: life-chronicle:invite`, not proof of attendance) with no chat call, no daily reservation and zero cost, through the same publication and ledger path. `publish.ts` publishes one generation against the pinned depth snapshot: each event write re-validates the depth revision, content hash, source incarnation, privacy and the deciding writer's grant (events also read as private when their `event.depth` origin is private by field or declared lineage, or missing, `search/private-visibility.ts`) (`managed_maintenance_chronicle_event`/`_retire` intents on managed brains, one transaction per event otherwise), stamps the depth's visibility, never overwrites an operator-edited event (live hash not in the ledger) or resurrects an operator-deleted one, and after a complete generation retires the previous generation's owned events (`retired_by: life-chronicle`; restored when produced again). `event-identity.ts` assigns final slugs before publication: events sharing a base slug `life/events/<day>-<hash8>` (who, what, depth) are told apart by instant, `where` and `kind`; one keeps the base slug and the rest get `-<hash6>` (identical copies `-2`…); assignment reads the pages already at the candidate slugs, so it is order-independent, keeps a page's existing slug across corrections and re-extractions, and a page extracted before disambiguation keeps its base slug. `extract-events.runChronicleExtract` is the direct-caller body over the same snapshot and publication path: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date), content-addressed `life/events/` pages + a `timeline_entries` projection. An unusable judge response is never recorded as `no_events`: truncation, unparseable output, a provider error and a refusal surface as `judge_truncated`/`judge_parse_failed`/`judge_chat_error`/`judge_refused`. `backfill.ts` (`chronicle_backfill`) queues `trigger='backfill'` ledger rows, exempt from the daily limit and recency (unless `--recent`), across types and rescue prefixes under one global `--limit`; `--since` is the update date, `--dated-since` the page date; a dry run reports `estimated_usd` and skip reasons; a live run needs `--yes`; content already extracted or queued is never re-queued, even after `gbrain jobs prune`. `job.ts` drains `chronicle_extract` jobs from older releases through the same executor. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free; the v188 dedup index adds the stint's `valid_from`, so a crash-retry conflicts while a same-provenance return to an earlier value records a new interval), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value (noop when the same provenance already observed it during the current stint), forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Remote callers read only `visibility = 'world'` observations, like recall: `getOntology`/`findOntologyConflicts` take a `visibility` filter applied before resolution and the conflict HAVING. `ontology_propose` commits through `coordinatedDatabaseWrite` on a managed brain. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts; coverage gap with a scoped `chronicle-backfill --since <date> --limit 50 --dry-run`; `auto_chronicle_default_on` ask_user until acknowledged; `auto_chronicle_invalid`; `chronicle_chat_unavailable`; `chronicle_extraction_failing`; `chronicle_daily_limit`); doctor `chronicle_projection_health` and `auto_chronicle` (`checks/auto-chronicle.ts`; BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts` (automatic path: `chronicle-auto-{decision,phase,unmanaged}`, `chronicle-event-privacy`, `chronicle-event-identity`, `chronicle-invite-projection`, `chronicle-backfill`, `chronicle-reasons-5876`; Postgres arms in `test/e2e/chronicle-*-postgres.test.ts`), `test/eval-chronicle.test.ts`, `test/auto-chronicle-surfaces-5876.test.ts`.
-- `src/core/chronicle/{contract,eligibility,config,reasons,ledger,ledger-stats,execute,publish,backfill,job,upgrade-notice,extract-events,ontology,narrative}.ts` + `src/core/cycle/chronicle.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `contract.ts` holds the ledger columns, the extractor version, the phase bounds and the phase result details. `reasons.ts` is the one reason table (`CHRONICLE_REASONS`: stage, meaning, stored fix Action with argv/preview_argv/consent/actor, never a stored `next`; `auto_chronicle_off` has no fix because it is off by choice) and builds the `chronicle_backstop` receipt field (`{pending:'next_cycle', daily_remaining}` or `{skipped, stage, why, fix}`, omitted for pages that are not chronicle-shaped); `docs/guides/life-chronicle.md` renders its table from it. `eligibility.isChronicleEligible` is the one eligibility function (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop); with a time policy it also applies the invite end (`not_yet_happened`), the recency window on the page's own date (an authored `effective_date`, else frontmatter `date`/`start`; a `fallback` date counts as undated) and the settle window. `config.ts` owns the switch and knobs: `autoChronicleSetting` reads `auto_chronicle` as on when unset, on/off for true/false words, and `invalid` (off) for any other word; `chronicleSettings` reads `chronicle.job_budget_usd`/`auto_daily_limit`/`auto_recent_days`/`auto_settle_seconds`/`judge_max_tokens` with ranges (`CHRONICLE_NUMERIC_KEYS`, enforced by `config set`; a malformed stored row falls back and is listed in `invalid`) and `chronicle.activated_at` (stamped by the first write decision or phase run; earlier revisions are history); `autoChronicleNeedsAcknowledgement` is true while on and `chronicle.default_on_acknowledged` is unset (stamped by `config set auto_chronicle`). The opt-out is `gbrain config set auto_chronicle false` everywhere. `ledger.ts` owns `chronicle_page_state` (one row per source/page/content hash/extractor version: state, reason, trigger, deciding writer and request, `no_extract`, attempts, `next_attempt_at`, cost/unpriced, event slugs and hashes): `recordChronicleDecision` runs inside every coordinated publication that imports a page (from `queuePublicationEffects`), applies the shared writer-confinement predicate, `--no-extract`, the opt-out and eligibility, and puts `chronicle_backstop` on the outcome through `reasons.ts`; `reserveChronicleSlot` is the rolling 24 h reservation under a transaction advisory lock. `ledger-stats.ts` rolls up the ledger and reservations for doctor and the advisor. `upgrade-notice.ts` is the one-shot post-upgrade notice (`chronicle.default_on_notice_shown`). The global `chronicle` cycle phase (`cycle/chronicle.ts`) supersedes rows whose content is no longer live, discovers pages changed since activation with no row (unmanaged brains decide there; managed ones record `no_write_decision`), and executes settled rows round-robin across sources (≤50 judged items and a wall-time bound per run; automatic rows only while `auto_chronicle` is on, backfill rows always); no chat provider → no calls; the extract_atoms cost gate refuses an explicit cap on an unpriced model. `execute.ts` runs one row: live-content check, time rules, the reservation (automatic rows; attempts count), the judge in a `chronicle:<trigger>` BudgetTracker scope with the per-page cap and an explicit post-call cap check, failure classes (chat_error/budget → failed with backoff, no provider/no_pricing → failed until config changes, refused → skipped, only a parsed `[]` is `no_events`). `publish.ts` publishes one generation against the pinned depth snapshot: each event write re-validates the depth revision, content hash, source incarnation, privacy and the deciding writer's grant (events also read as private when their `event.depth` origin is private by field or declared lineage, or missing, `search/private-visibility.ts`) (`managed_maintenance_chronicle_event`/`_retire` intents on managed brains, one transaction per event otherwise), stamps the depth's visibility, never overwrites an operator-edited event (live hash not in the ledger) or resurrects an operator-deleted one, and after a complete generation retires the previous generation's owned events (`retired_by: life-chronicle`; restored when produced again). `extract-events.runChronicleExtract` is the direct-caller body over the same snapshot and publication path: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date), then `screenChronicleProposals` drops, never writes, each proposal without a day (`date_imprecise`: `when` is a year or month) or dated after the page's own day (`future_dated`: `chronicleEventCutoff` is the latest of the page's own date, a meeting's `end` and a conversation's last parsed message, as a day in `chronicle.tz`, capped at today); drops are counted in `events_dropped` (phase details, row outcome, direct result) and a page whose every proposal was dropped records the drop reason on its extracted ledger row instead of `no_events`; content-addressed `life/events/` pages + a `timeline_entries` projection. An unusable judge response is never recorded as `no_events`: truncation, unparseable output, a provider error and a refusal surface as `judge_truncated`/`judge_parse_failed`/`judge_chat_error`/`judge_refused`. `backfill.ts` (`chronicle_backfill`) queues `trigger='backfill'` ledger rows, exempt from the daily limit and recency (unless `--recent`), across types and rescue prefixes under one global `--limit`; `--since` is the update date, `--dated-since` the page date; a dry run reports `estimated_usd` and skip reasons; a live run needs `--yes`; content already extracted or queued is never re-queued, even after `gbrain jobs prune`. `job.ts` drains `chronicle_extract` jobs from older releases through the same executor. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free; the v188 dedup index adds the stint's `valid_from`, so a crash-retry conflicts while a same-provenance return to an earlier value records a new interval), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value (noop when the same provenance already observed it during the current stint), forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Remote callers read only `visibility = 'world'` observations, like recall: `getOntology`/`findOntologyConflicts` take a `visibility` filter applied before resolution and the conflict HAVING. `ontology_propose` commits through `coordinatedDatabaseWrite` on a managed brain. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts; coverage gap with a scoped `chronicle-backfill --since <date> --limit 50 --dry-run`; `auto_chronicle_default_on` ask_user until acknowledged; `auto_chronicle_invalid`; `chronicle_chat_unavailable`; `chronicle_extraction_failing`; `chronicle_daily_limit`); doctor `chronicle_projection_health` and `auto_chronicle` (`checks/auto-chronicle.ts`; BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts` (automatic path: `chronicle-auto-{decision,phase,unmanaged}`, `chronicle-date-quality`, `chronicle-event-privacy`, `chronicle-backfill`, `chronicle-reasons-5876`; Postgres arms in `test/e2e/chronicle-*-postgres.test.ts`), `test/eval-chronicle.test.ts`, `test/auto-chronicle-surfaces-5876.test.ts`.
++- `src/core/chronicle/{contract,eligibility,config,reasons,ledger,ledger-stats,execute,publish,event-identity,invite-projection,backfill,job,upgrade-notice,extract-events,ontology,narrative}.ts` + `src/core/cycle/chronicle.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `contract.ts` holds the ledger columns, the extractor version (part of the ledger key: a bump makes extracted content new to discovery and backfill), the phase bounds and the phase result details. `reasons.ts` is the one reason table (`CHRONICLE_REASONS`: stage, meaning, stored fix Action with argv/preview_argv/consent/actor, never a stored `next`; `auto_chronicle_off` has no fix because it is off by choice) and builds the `chronicle_backstop` receipt field (`{pending:'next_cycle', daily_remaining}` or `{skipped, stage, why, fix}`, omitted for pages that are not chronicle-shaped); `docs/guides/life-chronicle.md` renders its table from it. `eligibility.isChronicleEligible` is the one eligibility function (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop); with a time policy it also applies the invite end (`not_yet_happened`), the recency window on the page's own date (an authored `effective_date`, else frontmatter `date`/`start`; a `fallback` date counts as undated) and the settle window. `config.ts` owns the switch and knobs: `autoChronicleSetting` reads `auto_chronicle` as on when unset, on/off for true/false words, and `invalid` (off) for any other word; `chronicleSettings` reads `chronicle.job_budget_usd`/`auto_daily_limit`/`auto_recent_days`/`auto_settle_seconds`/`judge_max_tokens` with ranges (`CHRONICLE_NUMERIC_KEYS`, enforced by `config set`; a malformed stored row falls back and is listed in `invalid`) and `chronicle.activated_at` (stamped by the first write decision or phase run; earlier revisions are history); `autoChronicleNeedsAcknowledgement` is true while on and `chronicle.default_on_acknowledged` is unset (stamped by `config set auto_chronicle`). The opt-out is `gbrain config set auto_chronicle false` everywhere. `ledger.ts` owns `chronicle_page_state` (one row per source/page/content hash/extractor version: state, reason, trigger, deciding writer and request, `no_extract`, attempts, `next_attempt_at`, cost/unpriced, event slugs and hashes): `recordChronicleDecision` runs inside every coordinated publication that imports a page (from `queuePublicationEffects`), applies the shared writer-confinement predicate, `--no-extract`, the opt-out and eligibility, and puts `chronicle_backstop` on the outcome through `reasons.ts`; `reserveChronicleSlot` is the rolling 24 h reservation under a transaction advisory lock. `ledger-stats.ts` rolls up the ledger and reservations for doctor and the advisor. `upgrade-notice.ts` is the one-shot post-upgrade notice (`chronicle.default_on_notice_shown`). The global `chronicle` cycle phase (`cycle/chronicle.ts`) supersedes rows whose content is no longer live, discovers pages changed since activation with no row (unmanaged brains decide there; managed ones record `no_write_decision`), and executes settled rows round-robin across sources (≤50 judged items and a wall-time bound per run; automatic rows only while `auto_chronicle` is on, backfill rows always); no chat provider → no calls; the extract_atoms cost gate refuses an explicit cap on an unpriced model. `execute.ts` runs one row: live-content check, time rules, the reservation (automatic rows; attempts count), the judge in a `chronicle:<trigger>` BudgetTracker scope with the per-page cap and an explicit post-call cap check, failure classes (chat_error/budget → failed with backoff, no provider/no_pricing → failed until config changes, refused → skipped, only a parsed `[]` is `no_events`). `invite-projection.ts` stands in for the judge on an ended calendar invite (slug under `calendar/`/`cal/` or type `calendar-event`, with a title, `start` and `end`): one `Scheduled: <title>` event (`kind: meeting`, `captured_via: life-chronicle:invite`, not proof of attendance) with no chat call, no daily reservation and zero cost, through the same publication and ledger path. `publish.ts` publishes one generation against the pinned depth snapshot: each event write re-validates the depth revision, content hash, source incarnation, privacy and the deciding writer's grant (events also read as private when their `event.depth` origin is private by field or declared lineage, or missing, `search/private-visibility.ts`) (`managed_maintenance_chronicle_event`/`_retire` intents on managed brains, one transaction per event otherwise), stamps the depth's visibility, never overwrites an operator-edited event (live hash not in the ledger) or resurrects an operator-deleted one, and after a complete generation retires the previous generation's owned events (`retired_by: life-chronicle`; restored when produced again). `event-identity.ts` assigns final slugs before publication: events sharing a base slug `life/events/<day>-<hash8>` (who, what, depth) are told apart by instant, `where` and `kind`; one keeps the base slug and the rest get `-<hash6>` (identical copies `-2`…); assignment reads the pages already at the candidate slugs, so it is order-independent, keeps a page's existing slug across corrections and re-extractions, and a page extracted before disambiguation keeps its base slug. `extract-events.runChronicleExtract` is the direct-caller body over the same snapshot and publication path: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date), then `screenChronicleProposals` drops, never writes, each proposal without a day (`date_imprecise`: `when` is a year or month) or dated after the page's own day (`future_dated`: `chronicleEventCutoff` is the latest of the page's own date, a meeting's `end` and a conversation's last parsed message, as a day in `chronicle.tz`, capped at today); drops are counted in `events_dropped` (phase details, row outcome, direct result) and a page whose every proposal was dropped records the drop reason on its extracted ledger row instead of `no_events`; content-addressed `life/events/` pages + a `timeline_entries` projection. An unusable judge response is never recorded as `no_events`: truncation, unparseable output, a provider error and a refusal surface as `judge_truncated`/`judge_parse_failed`/`judge_chat_error`/`judge_refused`. `backfill.ts` (`chronicle_backfill`) queues `trigger='backfill'` ledger rows, exempt from the daily limit and recency (unless `--recent`), across types and rescue prefixes under one global `--limit`; `--since` is the update date, `--dated-since` the page date; a dry run reports `estimated_usd` and skip reasons; a live run needs `--yes`; content already extracted or queued is never re-queued, even after `gbrain jobs prune`. `job.ts` drains `chronicle_extract` jobs from older releases through the same executor. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free; the v188 dedup index adds the stint's `valid_from`, so a crash-retry conflicts while a same-provenance return to an earlier value records a new interval), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value (noop when the same provenance already observed it during the current stint), forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Remote callers read only `visibility = 'world'` observations, like recall: `getOntology`/`findOntologyConflicts` take a `visibility` filter applied before resolution and the conflict HAVING. `ontology_propose` commits through `coordinatedDatabaseWrite` on a managed brain. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts; coverage gap with a scoped `chronicle-backfill --since <date> --limit 50 --dry-run`; `auto_chronicle_default_on` ask_user until acknowledged; `auto_chronicle_invalid`; `chronicle_chat_unavailable`; `chronicle_extraction_failing`; `chronicle_daily_limit`); doctor `chronicle_projection_health` and `auto_chronicle` (`checks/auto-chronicle.ts`; BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts` (automatic path: `chronicle-auto-{decision,phase,unmanaged}`, `chronicle-date-quality`, `chronicle-event-privacy`, `chronicle-event-identity`, `chronicle-invite-projection`, `chronicle-backfill`, `chronicle-reasons-5876`; Postgres arms in `test/e2e/chronicle-*-postgres.test.ts`), `test/eval-chronicle.test.ts`, `test/auto-chronicle-surfaces-5876.test.ts`.
- `src/core/chunkers/` — 3-tier chunking (recursive, semantic, LLM-guided). `code.ts` is a tree-sitter-based semantic chunker for 30 languages (plus SQL via DerekStride/tree-sitter-sql) with embedded-asset WASMs (`src/assets/wasm/`), `@dqbd/tiktoken` cl100k_base tokenizer, small-sibling merging. `CHUNKER_VERSION` is folded into `importCodeFile`'s `content_hash` so chunker shape changes force clean re-chunks across releases. `extractSymbolName` has an inline SQL branch (`extractSqlSymbolName`) diving through DerekStride's `statement` wrapper into the inner DDL child (`create_table`/`create_function`/`create_view`/`create_index`/`create_procedure`/`create_type`/`create_schema`/`create_database`/`create_trigger`/`alter_table`/`alter_view`) and extracting the target identifier via the `name` field with identifier-shaped fallback; DML kinds (`select`/`insert`/`update`/`delete`/`merge`/`with`) deliberately return null so chunks emit unnamed (code-def is a DDL signal). `normalizeSymbolType` has parallel SQL branches mapping `create_table → 'table'`, `create_view → 'view'`, etc. `DEF_TYPES` (owned by `src/core/chunkers/def-types.ts`, re-exported by `src/commands/code-def.ts` — see that entry) carries the SQL kinds (`'table' | 'view' | 'index' | 'procedure' | 'schema' | 'database' | 'trigger'`) so the new chunks surface in `gbrain code-def <name>` queries.
@@@ -44,9 -44,9 +44,3 @@@
- `src/core/chunkers/symbol-resolver.ts` — resolves and stamps each bounded chunk batch in one transaction. It takes ordered source/page guards before edge reads, revalidates current chunk/page/slug identity under those guards, and commits edge metadata with its backfill watermark. Concurrent projection replacement cannot certify new edges using an old resolver read; rollback leaves both metadata and watermark unchanged. Pinned by `test/symbol-resolver-projection-race.test.ts` with PGLite serialization and a real PostgreSQL lock-wait receipt. A `calls` edge the extractor flagged `memberCall` (an untyped receiver, `obj.m()` emitted as bare `m`; persisted as `edge_metadata.member_call`) is never resolved within the file, since a member call cannot invoke a same-file top-level function (gbrain-evals N13-8, `test/code-intel/n13-edge-resolution.test.ts`); existing code pages pick this up when they re-import (`gbrain reindex-code`).
- `src/core/connectors/` (directory) — the LIVE chat-history connector layer (front-end to the transcripts pipeline). `types.ts`: the `ChatHistoryProvider` contract (mirror of `TranscriptAdapter` — leaf module per provider; `spoolFormat` names the adapter that parses its output; dated `HostSpecTarget`). `credentials.ts`: file-plane store at `~/.gbrain/connectors/<provider>.json` (0600, dir 0700, atomic tmp+rename), env-above-file `resolveCredential` returning `{cred, source}`; credentials NEVER touch the DB / `sources.config` / config planes / op payloads. `classify.ts`: the pure §2A/§2B response classifier — distinguishes a Cloudflare-fingerprint 403 (`forbidden_fingerprint`, dead-end) from an auth-expired 403 (`auth_required`, re-auth) and flags a parses-but-no-`items` body as `drift`. `client.ts`: `ConnectorClient` modeled on `GitHubClient` (plain fetch against a hardcoded ORIGIN + off-origin guard so the cookie/bearer never leaks, browser UA, refresh-once-on-401, Retry-After backoff; `fetchImpl`/`sleep`/`now` injectable — NOT `fetchWithSSRFGuard`, which breaks SNI on Cloudflare hosts). `providers/chatgpt.ts` + `providers/claude.ts` (registry in `registry.ts`; Perplexity deliberately absent — no adapter): offset/updated pagination with a per-pass 500-page cap and a `stopBefore` watermark break, epoch/ISO normalization, ChatGPT's `is_archived` second pass, Claude's `chat_conversations` paged with `limit`/`offset` across every chat-capable org (conversations fetched from the org that listed them; timestamps normalized with ChatGPT's `toIso`), a ChatGPT walk that steps back when `total` shrinks mid-walk (a removal shifts later items to lower offsets) and yields each id once across both passes, content-block text assembly for Claude, and a `refreshAccessToken` (ChatGPT re-mints from the cookie via `/api/auth/session`; Claude's cookie is terminal). `spool.ts`: writes fetched conversations in native-export shape (0600, batched, pruned in the orchestrator `finally`). `sync.ts`: `runConnectorSync` — resolve credential → probe → read the **per-(provider, source) config-scalar watermark** `connectors.<p>.source.<id>.watermark_iso` (NOT op_checkpoint, whose 7-day GC would wipe it → full re-fetch) → list to `watermark − windowDays` → skip stubs whose `updatedAt` the source's `synced` ledger already holds and stubs quarantined in its `failed` ledger (after `QUARANTINE_ATTEMPTS` = 3 fetch OR ingest failures at one `updatedAt`; ingest outcomes are attributed per conversation by session id, a spool-file-level failure fails the batch; an edit or `--full` retries) BEFORE the `--limit` cap, so capped runs progress → fetch → spool → `runTranscriptsIngest` → record each successfully ingested conversation as synced → advance the watermark ONLY on a clean run (quarantined ids no longer block it; ledger entries older than the next list window are pruned) → `logIngest` receipt → stamp per-source `last_sync_at` → engine-branched embed kickoff (`maybeKickoffEmbed`: Postgres `submitEmbedBackfill`, PGLite `runEmbedCore` inline — NEVER `submitEmbedBackfill`, which refuses `no_worker_surface`). `config-keys.ts`: the `connectors.` key builders (sync progress keyed by `(provider, source)`; `auth_error_at` stays per provider because it describes the shared credential), `readConnectorState`/`writeConnectorState` (a legacy per-provider `watermark_iso`/`last_sync_at` is honored only for the scheduled `connectors.source_id` source until that source writes its own key, which retires it), and the pure `isConnectorSyncStale(last, now, floor)` dispatch gate. Status, doctor and the autopilot gate read the scheduled source's state. `oauth-pkce.ts`: dependency-free S256 PKCE loopback (`Bun.serve`, timing-safe state) — best-effort `--try-oauth` only. Surfaces: the `connectors_status`/`connector_sync` ops (`src/core/ops/connectors.ts`, both `localOnly`), the `gbrain connectors` command family (`src/commands/connectors/` peeled dir), the `connector-sync` minion handler (`src/core/minions/handlers/connector-sync.ts`, single-flight lock), the autopilot `maybeDispatchConnectorSyncs` gate, and the `connectors` doctor check. Pinned by `test/connectors-*.test.ts` + `test/e2e/connectors-sync-checkpoints-pglite.test.ts` (per-source watermark, `--limit` progress, quarantine, retitle) + `test/e2e/connectors-sync-pglite.test.ts` (full pipeline against a `Bun.serve` fixture backend, keyless) + `test/e2e/connector-sync-handler-pglite.test.ts` + `test/e2e/doctor-connectors-pglite.test.ts`.
--
--- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; `visibility: private` (and derived-private) pages never resolve on any arm unless the caller passes `excludePrivate: false` (default true, the remote-search predicate `privatePagesFilterFragment`; only `volunteer_context` widens, via `resolveExcludePrivatePages` for a trusted local caller — gbrain-evals N8-1/N8-2, pinned by `test/reflex-private-visibility.test.ts`); capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor/checks/verbs-reflex.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract) — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs and pass `excludePrivate: true` on every arm, so private pages never reach the compiled file; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT.
--- `src/core/context/hook-heartbeat.ts` — the hooks telemetry plane under `<gbrain home>/integrations/hooks/` (`heartbeat.jsonl`, `status.json`, session receipts, the memorable relay log; directories 0700, appends 0600). Entries hold counters, durations and codes only: `HEARTBEAT_ALLOWED_KEYS` is the full key allowlist CI greps the fixture against, and includes `pattern` (scanner pattern name), `fingerprint` (`sha256:<16 hex>`) and `hint` (fixed text) for refusals. `near_duplicate` is the shadow count on the `writeback_dedup` event that `facts/capture-dedup.ts` appends (lane in `reason`, exact drops in `duplicate`). `relayRefusalHeartbeat(hit)` builds the line `context-engine.ts` writes when its high-entropy re-scan refuses a memorable relay (`event: relay`, `outcome: degraded`, `reason: secret_scan_refused`); the receipt and relay are skipped for that compaction window and the checkpoint is kept. `memorableGateAllowed` gates the relay lane; span redaction runs `redactFindings` with `highEntropy: true`. Tests: `test/context-engine-checkpoint.serial.test.ts`.
--- `src/core/context/seat.ts` — seat identity for captured sessions (#4618), engine-free. `resolveSeat` returns the lowercased `GBRAIN_SEAT` label when it matches `SEAT_LABEL_RE` (`^[a-z0-9][a-z0-9._-]{0,63}$`), else `home-<8 hex>` over the realpath of the harness home (Claude Code: the directory holding `projects/` in the transcript path, then `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `~/.claude`; codex: `CODEX_HOME` or `~/.codex`; OpenClaw: the agent directory holding `sessions/`), so no raw path reaches frontmatter; `GBRAIN_SEAT=off` (the opt-out) resolves to null and nothing is recorded. `writeSeatSidecar` writes `<sessionId>.seat.json` (`{version: 1, seat, seat_source, hook_lane, harness, first_seen}`, 0600, tmp+rename) unless one exists, reporting `seat_conflict` when the existing seat differs; `readSeatSidecar` accepts only a valid v1 record. `SEAT_REASON_HINTS` holds the fixed heartbeat hints. The sidecar name and its GC live in `corpus-segments.ts` (`seatFileName`, `SEAT_SIDECAR_SUFFIX`).
--
--- `src/core/context/ipc-path.ts` — engine-free local socket discovery and private Unix fallback when the complete role-specific address exceeds 103 UTF8 bytes. Hashes the physical parent plus basename under a fixed OS temporary root, verifies ownership/0700 directory/0600 client socket without following fallback symlinks, and retains a native binding claim through actual server close. Existing Unix socket accessibility is rechecked even when a runtime reports ENOENT; permission/resource probe failures never authorize stale takeover; Windows named pipes retain a native Global mutex through actual close; `windows-ipc.ts` normalizes namespace prefixes while native Windows Unicode casing defines the mutex identity. `test/local-ipc-path.test.ts` covers concurrent real processes, SIGKILL recovery, active-connection shutdown, aliases and unsafe paths. The published CLI smoke also uses a long Unicode datastore path.
diff --cc docs/architecture/key-files/security.md
index d05c86b151,71b319c786..41da1ec159
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@@ -7,10 -7,9 +7,10 @@@ Current behavior and load-bearing invar
- `src/core/env-trust.ts` — Trust boundary for environment variables Bun auto-loaded from the cwd `.env` family. `CWD_DOTENV_FILES` (the eight names Bun auto-loads across NODE_ENV values), `splitDotenvLines` (Bun's line grammar: `\n`, `\r\n` AND a bare `\r` terminate a line, leading BOM stripped — shared with gbrain-env-file.ts), `dotenvValuesForKey(key, dir)` (value set across all assignments; the #427 `DATABASE_URL` value-match guard in config.ts, which re-exports both), `cwdDotenvAssignsKey(key, dir | assignments)` (KEY-PRESENCE predicate; an empty assignment counts) and `parseCwdDotenv(dir)` → `DotenvAssignment[]` (one read the two preflight consumers share). The assignment RHS is matched as `([^\r\n]*)`, never `.*$`. Protection is one predicate, `isCwdDotenvProtectedKey(key)`: `CWD_DOTENV_PROTECTED_KEYS` (code-loading / exec-target / root- and endpoint-redirect incl. `GBRAIN_DATABASE_URL` (key-presence; the #427 config.ts VALUE guard is separate and covers only bare `DATABASE_URL`), `GBRAIN_DIRECT_DATABASE_URL`, `GBRAIN_REMOTE_MCP_URL`, `GBRAIN_REMOTE_ISSUER_URL`, `GBRAIN_OAUTH_RELAY_URL` / posture-widening `GBRAIN_*`, plus the re-run marker `GBRAIN_CWD_ENV_QUARANTINED`; one why-comment per key, plus the deliberate exclusions and deferrals) PLUS `CWD_DOTENV_PROTECTED_PREFIXES` (`LD_`, `DYLD_`, `GIT_`, `BUN_`, `NPM_CONFIG_`, `npm_config_`, `BASH_FUNC_`) and `CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS` (NODE_OPTIONS/NODE_PATH/CA/TLS, SSH_ASKPASS*, XDG_CONFIG/DATA/CACHE_HOME, GNUPGHOME, SSL_CERT_FILE/DIR, CURL_CA_BUNDLE, REQUESTS_CA_BUNDLE, OPENSSL_CONF/ENGINES/MODULES, TMPDIR/TMP/TEMP, HOME/USERPROFILE, the shell-startup / interpreter-home group BASH_ENV, SHELLOPTS, PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH (sh/ksh `ENV` deliberately excluded: interactive-only and a routine project key), EDITOR/VISUAL/PAGER, PYTHON/PERL/RUBY preload, proxy vars both spellings, CLAUDE_CONFIG_DIR, ANTHROPIC_*/OPENAI/OPENROUTER/LITELLM/OLLAMA/LMSTUDIO/LLAMA_SERVER(_RERANKER)_BASE_URL) — the families a cwd .env could plant for the programs gbrain spawns; a denylist that grows as families are identified. `quarantineCwdDotenv(env = process.env, dir = process.cwd(), { warn, assignments })` iterates the keys the cwd .env files ASSIGN, deletes each protected one present in `env`, prints ONE stderr line (`formatQuarantineWarning`, composed from the exported `CWD_DOTENV_REMEDIATION` that guardrails.ts reuses) naming them sorted, returns them sorted. INVARIANTS: key presence, never value match; the parser accepts every line shape Bun's loader does; in-process only — children spawned without an explicit `env` see Bun's startup snapshot, which is why `cli-preflight.ts` re-runs gbrain from a neutral cwd whenever the list is non-empty; fs/path only, no config import. Pinned by `test/env-trust.test.ts`; the GBRAIN list is guarded against rot by the structural `test/env-trust-protected-keys.test.ts` (every `process.env.GBRAIN_*` / `Bun.env.GBRAIN_*` / `env.GBRAIN_*` read in src/ whose name matches `_BIN|_CLI|_MODULE|_PATH|_HOME|_URL` suffix or `GBRAIN_ALLOW_` prefix must be on the list or carry a `cwd-dotenv-ok: <why>` annotation).
- - `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, and unlimited delegated spend. `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. F3 one grant shape: `model.ts` also holds `PrincipalGrant` (`GrantSources` = `default` | `scalar` | `federated` | `none`), `grantFromTokenRow` (unified rows read the `access_tokens` grant columns and any axis whose `permissions` mirror disagrees evaluates deny-all and is listed in `drift`; an unconverted `source_grant IS NULL` row reads as the conversion `migrateLegacyTokens` would write, and a malformed `permissions` value denies every axis), `GRANT_MIRROR_WINDOW_ENDS` (the date until which the `permissions` mirror is written and drift is enforced; doctor reports it), `authSourcesFromGrant` (the AuthInfo source fields every token reader uses: both HTTP transports, publication `authority.ts`, job admission, shared-skill membership and policy), `grantFromClient`, `validatePrincipalGrant` (tokens and clients may hold `none`); `ClientGrant.sourcesNone` (`oauth_clients.source_grant = 'none'`: NULL `source_id`, empty `federated_read`, verified as `NO_SOURCES`) and `ClientGrant.takesHolders` (`oauth_clients.takes_holders`, NULL = `['world']`; read by `verifyAccessToken` and `authorizeTakeHolder`), both added by migration v202 (fragment `oauth-client-axes-schema.ts`) and set through `auth rescope --client --sources none|--takes-holders` and `permissionsMirror`. `access-token-schema.ts` is the column fragment (migration `f3_access_token_grants`); v201 (`legacy_token_grant_conversion`) converts every legacy grant in bulk. Tests: `test/legacy-token-grant-conversion.test.ts`. `legacy-token.ts` is the token grant editor behind `gbrain auth rescope --token` (aliases `rescope-token`, `permissions set-takes-holders`): one `FOR UPDATE` transaction that writes the columns, bumps `grant_revision` (`--if-version` compare-and-set) and rewrites `permissions` as a mirror with every other key preserved; `none` = explicit empty list; refresh previews and widens only by named operations; a drifted token refuses edits until `--adopt-permissions` or `--adopt-columns`; `migrateLegacyTokens` (`--migrate-legacy` and schema migration v201) writes the columns for every unmigrated token without changing a grant and skips malformed JSONB; `resolveTokenGrant` is the HTTP auth read (both transports): a legacy-shape row converts on that read with one `source_grant IS NULL`-guarded UPDATE (concurrent first reads convert once; a failed write such as a read-only role authorizes with the identical in-memory conversion); `resolveRescopeTarget` refuses a bare name that matches a token and a client. `cli.ts` splits `auth rescope` targets and maps the unified client flags onto `auth rescope-client`'s patch. An explicit empty `permissions.source_id` decodes (`parseLegacyTokenScope` in `src/core/legacy-token-scope.ts`) to the `NO_SOURCES` sentinel, which `sourceScopeOpts`, the dispatch fence (`enforceBoundClientOpAllowList`, `fence=no_source_grant`), `submissionAuthority` and `POST /ingest` refuse and publication reauthorization rejects; it never regains the `default` floor. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit).
-- `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, and unlimited delegated spend. `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. F3 one grant shape: `model.ts` also holds `PrincipalGrant` (`GrantSources` = `default` | `scalar` | `federated` | `none`), `grantFromTokenRow` (unmigrated `source_grant IS NULL` rows read through lane F's JSONB parsers; unified rows read the `access_tokens` grant columns and any axis whose `permissions` mirror disagrees evaluates deny-all and is listed in `drift`), `authSourcesFromGrant` (the AuthInfo source fields every token reader uses: both HTTP transports, publication `authority.ts`, job admission, shared-skill membership and policy), `grantFromClient`, `validatePrincipalGrant` (tokens may hold `none`; clients refuse it with `client_sources_none_unsupported`) and `permissionsMirror`. `access-token-schema.ts` is the column fragment (migration `f3_access_token_grants`). `legacy-token.ts` is the token grant editor behind `gbrain auth rescope --token` (aliases `rescope-token`, `permissions set-takes-holders`): one `FOR UPDATE` transaction that writes the columns, bumps `grant_revision` (`--if-version` compare-and-set) and rewrites `permissions` as a mirror with every other key preserved; `none` = explicit empty list; refresh previews and widens only by named operations; a drifted token refuses edits until `--adopt-permissions` or `--adopt-columns`; `migrateLegacyTokens` (`--migrate-legacy`) writes the columns for every unmigrated token without changing a grant and skips malformed JSONB; `resolveRescopeTarget` refuses a bare name that matches a token and a client. `cli.ts` splits `auth rescope` targets and maps the unified client flags onto `auth rescope-client`'s patch. An explicit empty `permissions.source_id` decodes (`parseLegacyTokenScope` in `src/core/legacy-token-scope.ts`) to the `NO_SOURCES` sentinel, which `sourceScopeOpts`, the dispatch fence (`enforceBoundClientOpAllowList`, `fence=no_source_grant`), `submissionAuthority` and `POST /ingest` refuse and publication reauthorization rejects; it never regains the `default` floor. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit).
++- `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, and unlimited delegated spend. `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. F3 one grant shape: `model.ts` also holds `PrincipalGrant` (`GrantSources` = `default` | `scalar` | `federated` | `none`), `grantFromTokenRow` (unified rows read the `access_tokens` grant columns and any axis whose `permissions` mirror disagrees evaluates deny-all and is listed in `drift`; an unconverted `source_grant IS NULL` row reads as the conversion `migrateLegacyTokens` would write, and a malformed `permissions` value denies every axis), `GRANT_MIRROR_WINDOW_ENDS` (the date until which the `permissions` mirror is written and drift is enforced; doctor reports it), `authSourcesFromGrant` (the AuthInfo source fields every token reader uses: both HTTP transports, publication `authority.ts`, job admission, shared-skill membership and policy), `grantFromClient`, `validatePrincipalGrant` (tokens and clients may hold `none`); `ClientGrant.sourcesNone` (`oauth_clients.source_grant = 'none'`: NULL `source_id`, empty `federated_read`, verified as `NO_SOURCES`) and `ClientGrant.takesHolders` (`oauth_clients.takes_holders`, NULL = `['world']`; read by `verifyAccessToken` and `authorizeTakeHolder`), both added by migration v203 (fragment `oauth-client-axes-schema.ts`) and set through `auth rescope --client --sources none|--takes-holders` and `permissionsMirror`. `access-token-schema.ts` is the column fragment (migration `f3_access_token_grants`); v202 (`legacy_token_grant_conversion`) converts every legacy grant in bulk. Tests: `test/legacy-token-grant-conversion.test.ts`. `legacy-token.ts` is the token grant editor behind `gbrain auth rescope --token` (aliases `rescope-token`, `permissions set-takes-holders`): one `FOR UPDATE` transaction that writes the columns, bumps `grant_revision` (`--if-version` compare-and-set) and rewrites `permissions` as a mirror with every other key preserved; `none` = explicit empty list; refresh previews and widens only by named operations; a drifted token refuses edits until `--adopt-permissions` or `--adopt-columns`; `migrateLegacyTokens` (`--migrate-legacy` and schema migration v202) writes the columns for every unmigrated token without changing a grant and skips malformed JSONB; `resolveTokenGrant` is the HTTP auth read (both transports): a legacy-shape row converts on that read with one `source_grant IS NULL`-guarded UPDATE (concurrent first reads convert once; a failed write such as a read-only role authorizes with the identical in-memory conversion); `resolveRescopeTarget` refuses a bare name that matches a token and a client. `cli.ts` splits `auth rescope` targets and maps the unified client flags onto `auth rescope-client`'s patch. An explicit empty `permissions.source_id` decodes (`parseLegacyTokenScope` in `src/core/legacy-token-scope.ts`) to the `NO_SOURCES` sentinel, which `sourceScopeOpts`, the dispatch fence (`enforceBoundClientOpAllowList`, `fence=no_source_grant`), `submissionAuthority` and `POST /ingest` refuse and publication reauthorization rejects; it never regains the `default` floor. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit).
- `src/core/grants/lifecycle.ts` + `src/commands/serve-http-clients.ts` — owner-authenticated client inspection, setup, export and lifecycle endpoints. Token invalidation/revoke/delete lock the OAuth client row, require reviewed revisions and explicit application, and commit an audit record atomically. Deletion records a tombstone while preserving request history and spending reservations/settlement; missing clients become terminal delegated denials while transient lookup failures remain retryable.
+- `src/commands/serve-http-api-keys.ts` — owner-dashboard legacy API keys (`/admin/api/api-keys`). Mint validates the request (`parseApiKeyMintRequest`: name 1-128 printable characters, registered scopes, active source ids, holder grammar) and goes through `mintLegacyToken`, so keys are born on the unified grant columns; omitted fields take the `gbrain auth create` defaults (scopes `read,write`, never `admin` unless listed; no source grant; holders `['world']`), reported in `defaults_applied` beside the effective grant. Refusals are `invalid_params` agent envelopes with `why` and a `fix`; nothing is minted. The token appears only in the mint response, never in logs or SSE. The list returns ids, scopes, sources and holders through `grantFromTokenRow`; revoke takes the row id (`revokeLegacyTokenById`) and refuses a name. Pinned by `test/serve-http-api-keys.test.ts`.
- `src/core/guarded-http.ts` + `src/core/ssrf-validate.ts` — DNS answer classification, validated-address connections with original TLS/HTTP hostname and port, shared deadline/redirect policy, header-only probes, and bounded gzip/deflate/Brotli decoding. Ambient proxies fail closed with restart guidance. Consumers: URL reachability, remote images, and HTTP integration checks. Real TLS fixtures run on Bun 1.4.0 and 1.4.2.
diff --cc docs/architecture/key-files/tooling-and-tests.md
index fcbc3cbcab,bc4c4e2c2b..4bd22fb1b6
--- a/docs/architecture/key-files/tooling-and-tests.md
+++ b/docs/architecture/key-files/tooling-and-tests.md
@@@ -62,7 -62,8 +62,10 @@@ Current behavior and load-bearing invar
- `scripts/persistence/{harness,schedules,worker,validate,failure-diagnostics}.ts` — executable concurrency gate using real journal/coordinator APIs: 1,000 seeded schedules per engine, eight actual process-kill publication boundaries, and 10,000 writes from four producer processes. Each phase owns a temporary disk PGLite datastore or a fresh test Postgres database. Independent accounting queries verify conservation; every soak receipt is compared to its canonical snapshot and file. JSON manifests separate actual counts and latency measurements from the configured Linux/Bun CI matrix. Failed runs preserve private fixtures and collect bounded, allowlisted request/queue/owner diagnostics without changing deadlines or hiding the original error. Cleanup commands read the existing test URL from the environment. The PGLite loopback endpoint is a fixture transport, not production authentication coverage. Contract and commands: `scripts/persistence/README.md`; smoke entries: `test/persistence-chaos.slow.test.ts`, `test/e2e/persistence-chaos.test.ts`; diagnostic/retention contracts: `test/persistence-failure-diagnostics.test.ts`.
+- `scripts/persistence/{ops,generator,model,crash-robot,robot-driver,shrink,lock-order,history-fixture,would-have-caught}.ts` — the crash robot, a phase of `validate.ts` (`--robot-seconds`, default 300; CI runs it as its own `persistence-validation.yml` job). `ops.ts` is the JSON op-descriptor protocol between driver and workers: each descriptor names an op kind (put/edit/delete/restore page, remember/forget, takes add/supersede, timeline add, sync, connector publish, revoke access), an actor (the local CLI principal or a remote agent whose bearer token the production `verifyAccessToken` resolves), a source, a fixed request id and arguments whose `{ $ref }` values come from earlier observations; workers run every op through its registered operation handler. `generator.ts` builds seeded schedules: the fixed cross-boundary sequences (withdrawal then stale republication, overlapping slugs across two sources, competing writers, caller-bound replay, authority revoked with effects pending, sync and connector publish racing direct writes) plus random sequences with concurrent groups. `model.ts` is the temporal oracle: receipts and revisions at the observation point, legal later transitions, late receipts against page history, withdrawal permanence on recall/get_page/facts, source isolation, caller-bound replay, takes/facts fence projections, attribution, orphans, drain and wedge bounds; `EFFECT_SEAMS` maps every `EffectKind` to its trigger op and seam (typecheck-exhaustive). `crash-robot.ts` runs a schedule in-process or as a worker role (`count`, `run` frozen at a `fault-points.ts` seam and SIGKILLed by the driver, `recover`), plus process faults (stale `index.lock`, a hung git commit holding `index.lock`, Postgres session drops, the owner killed after a `facts-absorb` job's extraction commits and the job re-run). `robot-driver.ts` crashes every seam the fixed sequences reach, then fills the budget with random sequences; Postgres connects through `GBRAIN_PGBOUNCER_URL` when set and, under a budget below 300 s, skips the seams and the pooler disconnect fault that can wait out a dead owner's claim lease (`effect:*`, `consumer:prepared`, three publication seams), listed in the manifest as `lease_bound_seams_skipped` and `lease_bound_faults_skipped`. `shrink.ts` is dependency-preserving ddmin accepted on 3/3 reproduction; `--replay`/`--shrink` re-run a manifest's failing runs. `lock-order.ts` traces each transaction's row locks (worktrees before sources, sources by id, no exclusive brain lock in a publication). `history-fixture.ts` exports `buildHistoryFixture(engine, { pages, seed, sources, worktrees })` (a managed brain with real persistence history up to 10k pages, used by engine graduation and attribution backfill) and `prepareTopology`. `would-have-caught.ts` reverts each fix in `would-have-caught.json` in a scratch worktree and runs the pre-robot gate and the robot against it. Tests: `test/persistence-crash-robot.test.ts`, `test/persistence-crash-robot.slow.test.ts` (shrunk regressions in `test/fixtures/crash-robot/`), `test/persistence-history-fixture.test.ts`.
++
+ - `scripts/persistence/{graduation-fixture,graduation-process,graduation-ttv}.ts` — engine graduation test inputs and measurements. `graduation-fixture.ts` builds the 1k/10k history brains (`buildHistoryFixture` plus deterministic chunk vectors) or the hand-built legacy brain (`test/fixtures/graduation/`) in a keyless child process, caches each as a tarball keyed by its source files, schema version, seed and size, and re-homes a restore (database paths, managed-root records, owner stamps re-stamped with the new inode and birth time; sources marked synced). Its report lists bytes, chunks, versions, requests, effects and embeddings. `graduation-process.ts` spawns the real CLI or an older release with an isolated home and no provider keys, with optional boundary hooks, plus MCP stdio/HTTP clients and the JSON contract accessors. `graduation-ttv.ts` times plan to green doctor (five-minute gate at 1k pages; exit 1 under `--enforce`, 3 on a harness crash). Owners: `test/scripts/graduation-fixture.test.ts`, `test/graduation-legacy-fixture.test.ts`, `test/e2e/graduation-{crash,faults,clients,cli}.test.ts`, `tests/heavy/graduation_10k.sh`.
+
- `scripts/persistence/{matrix,matrix-cases}.ts` — required real Postgres/PgBouncer deployment matrix: 24 combinations of RLS policy enforcement, ordinary pool sizes 1/2/3 and shared/separate direct capacity. Production bulk reservations must leave short claims, renewals and reads usable; size-one publication stays queued. Fresh fixtures also verify successor manifests, stale owners, retained native lock exclusion during root replacement and source deletion/recreation. `test/e2e/persistence-runtime-matrix.test.ts` runs it when configured and refuses missing required pooler fixtures. Supplied URLs pass the test-database guard before its CREATE/DROP control connection uses the maintenance database; fresh case databases isolate it from other E2E shards.
- `scripts/persistence/{performance,read-workload,read-metrics,read-admission,read-diagnostics}.ts` — required median-of-three read-workload validity check with advisory CI latency around the existing heavy query corpus (500 pages, 200 reads, four writers, writesPerWriter 25, four-connection PostgreSQL pool). Both engines use public page mutation handlers; every read/write or drained sampler error invalidates the sample, actual in-flight mutation intervals must cover at least 90% of reads, and CI reports the 50% loaded-versus-idle p99 threshold without blocking on that ratio. CI uses `--informational`, which never suppresses invalid-workload failures; the default CLI and explicit strict heavy runs still enforce the threshold. Isolated children retain runtime/source hashes, queue/admission/commit/RSS/recovery/pool metrics and bounded diagnostic records with total/dropped counts, including failed partial observations. Numeric query/corpus/write indices and monotonic timestamps correlate reads, admissions, terminal receipts and pool samples without retaining SQL, parameters, identifiers, content or raw errors. Fixed failure stages retain only allowlisted error properties; raw stacks are omitted. The root postgres.js begin observer covers lexical readers and writers, preserves the original promise/receiver/arguments, and excludes nested savepoints. Dispatch-to-callback includes BEGIN and client scheduling, not pure checkout wait; PGLite has no transaction-entry timing. Identical 20ms timers record event-loop lateness in both phases. Observers run during seed/warmup before measurement; context setup and read retention sit outside query timing where possible, but transaction/timer callbacks add unquantified overhead. No SQL or server sampling is added, and sparse pool samples cannot establish lock causes. The original `tests/heavy/read_latency_under_sync.sh` invokes this runner. The stable admission proxy requires one resolved top-level queued journal transaction per committed UUID. `test/persistence-performance.test.ts` guards validity, strict threshold semantics and advisory CLI exit behavior; `test/persistence-admission-observer.test.ts` proves rollback/publication boundaries; `test/persistence-read-diagnostics{,.serial}.test.ts` covers bounds, transparency, nested transactions, safe failure retention, tiny manifests and late sampler rejection.
diff --cc docs/fix-wave-notes/capy-foundations-2.md
index fb842de690,0000000000..62658e0d11
mode 100644,000000..100644
--- a/docs/fix-wave-notes/capy-foundations-2.md
+++ b/docs/fix-wave-notes/capy-foundations-2.md
@@@ -1,114 -1,0 +1,114 @@@
+# Foundations 2 notes (`capy/foundations-2`, v0.60.53.0)
+
+One integrated PR. Five lanes were built in parallel from master at
+`5bd9e8497` and merged here with merge commits in the order F (scale and
+operations), A (crash robot), E (keys and grants), C (write attribution), D
- (silent failures). Lane E's placeholder migrations became v201
- `legacy_token_grant_conversion` and v202 `oauth_client_grant_axes`, the next
- numbers after master's v200. Generated files (migration registry, CLI flag
++(silent failures). Lane E's placeholder migrations became v202
++`legacy_token_grant_conversion` and v203 `oauth_client_grant_axes`, the next
++numbers after master's v201 (engine graduation). Generated files (migration registry, CLI flag
+registry, schema blobs, llms bundles, goldens) were regenerated, never
+hand-merged; the module-size ratchet rows that two lanes both grew were merged
+to measured line counts, keeping every lane's rationale.
+
+## Headline
+
+| Outcome | Before | After | Measured on |
+| --- | --- | --- | --- |
+| Crash runs per full persistence gate run (600 s budget) | 0 | PGLite 75 (Bun 1.4.0) and 69 (Bun 1.4.2); Postgres through PgBouncer 18 per Bun version; 11 crash points; 0 violations | `persistence-validation.yml` run 37234740186 on this branch |
+| Local robot long run | n/a | PGLite 300 s budget: 40 sequence x crash-point runs, 3 process faults, 0 violations; Postgres 600 s through PgBouncer: 12 runs, 4 process faults, 0 violations | integrated head `8bd4e81f9` |
+| Past persistence fixes caught when reverted (12 that reverse-apply cleanly) | 0 | 1 on each engine (6fe43935e, hung git child) | Lane A branch, `would-have-caught.ts` |
+| Facts from 10 meeting pages on a served PGLite brain, no command | 0 after 22 min, 10 jobs waiting | 49 facts from 10 pages at about 20 min ($0.084) | Lane D branch, real model |
+| Dashboard-minted keys with full access | 20 of 20 | 0 of 20 | `serve --http` fixture, integrated head |
+| Legacy tokens authorized from the JSON grant after boot | 50 of 50 | 0 of 50 (50 of 50 requests succeed) | same fixture |
+| Unattributed writer references | 90 in 40 files | 7 in 3 files | `test/write-attribution-legacy.test.ts` inventory |
+| Scale tier, 10,000 pages, enforced | n/a | PGLite 25 of 25 gates, Postgres 24 of 24 | `scale-tier.yml` run 37234737519 on this branch |
+| Scale tier, 20,000 pages | nightly red (PGLite timed out at 50 min) | green on both engines, about 8 min per job | Lane F run 37220459411 |
+
+Foreground MCP latency with and without the live facts drain (12 pages, real
+model): `get_page` p95 3.2 to 3.3 ms, `list_pages` 9.1 to 8.8 ms, search 439
+to 389 ms.
+
+Scale tier at 10k on this branch: MCP search p50 37.3 ms (PGLite) and 78.6 ms
+(Postgres); hybrid query 25 and 201 ms; `find_orphans` 41.4 and 31.9 ms;
+import 57 s and 102 s. The Postgres `planner_stats` gate is report-only and
+reports no `pg_stats` rows yet for three tables right after import (autovacuum owns statistics there).
+Ceiling enforcement stays report-only.
+
+## Items
+
+| Lane | What shipped | Priority |
+| --- | --- | --- |
+| A | Crash robot over the real operations (generator, reference model, SIGKILL at every crash seam, process faults, replay and shrink); crash-robot CI job per engine with PgBouncer; restarted PGLite owner releases its dead predecessor's claims; `buildHistoryFixture`; lock-order trace; would-have-caught runner | P0 |
+| C | Unmanaged writers through `maintenanceTransaction`, bounded per batch; attribution-backfill verified on a 10k managed history; `calibration undo-wave` on Postgres | P1 |
+| D | Automatic facts drain on PGLite (serve, serve --http, `facts_drain` cycle phase) with job deferral; #5299 cycle fence; `repair take-supersession` (#5886); doctor `revision_backfill` and the backfill on managed brains (#5216); chronicle event identity and invite projection | P0 drain, P1 rest |
- | E | Dashboard key mint fix (read+write default, revoke by id); v201 bulk legacy grant conversion and column reads on both HTTP transports; v202 client `--sources none` and `--takes-holders`; doctor `legacy_token_null_scope` | P0 mint fix, P2 rest |
++| E | Dashboard key mint fix (read+write default, revoke by id); v202 bulk legacy grant conversion and column reads on both HTTP transports; v203 client `--sources none` and `--takes-holders`; doctor `legacy_token_null_scope` | P0 mint fix, P2 rest |
+| F | `find_orphans` known answer on Postgres; PGLite planner stats in the timeline walk; autocommit WAL checkpoint guard; migrate refusals with why and fix; `sources refresh` inside a resident PGLite owner; projection-readiness cache; F4d ceilings in the scale tier; seat heartbeat and pattern-page seat follow-ups | P0 scale fixes and refusal, P2 rest |
+
+Every P0 item shipped. Nothing was cut.
+
+## Integration fixes
+
+- `8bd4e81f9`: Lane F's planner-stats refresh flushed the timeline batch
+ before page N, so one 100-row maintenance transaction split in two and Lane
+ C's `test/write-attribution-timeline-10k.slow.test.ts` saw 101 transactions
+ for 10,000 rows. The refresh now runs after every N pages, where the batch
+ is already flushed; Lane F's planner-stats test walks 301 pages so its check
+ after page 300 still sees 600 rows.
+- `consumer.ts` composes Lane A's `consumer:prepared` seam and first-tick
+ PGLite `releaseAbandonedClaims` with Lane F's refresh-fence predicate in the
+ idle probe; released claims are still fenced when they are claimed again.
+
+- `gbrain sources add` on a 20,000-file checkout failed intermittently on
+ 4-vCPU runners (also on branches without this wave): the background `git gc`
+ that the fixture's large commit starts pruned `.git/objects/<xx>` while the
+ physical-root overlap scan walked the checkout, and the scan's `readdirSync`
+ threw ENOENT. The scan now skips a subdirectory that vanished mid-walk
+ (`test/persistence-physical-root.test.ts` races it against a churning
+ directory). Reproduced 4 of 5 times on a standard-4 VM before the fix.
+- `test/sweep.test.ts` counted 4 raw queries instead of 3 when an earlier file
+ in the same process had registered a local CLI writer in the shared test
+ home: snapshot brains share one `brain_id`, so the maintenance principal
+ lookup found and verified that registration. The test now runs with its own
+ `GBRAIN_HOME`.
+- PR-budget coverage cut: the 150 s pull-request robot run on Postgres skips
+ the seams and the fault that can wait out a dead owner's 2-minute claim
+ lease (`effect:*`, `consumer:prepared`, `publication:prepared`,
+ `publication:before_publication`, `publication:after_publication`, and the
+ pooler disconnect fault). Before the cut that run took 669 s locally (three
+ publication seams at about 128 s each, the pooler disconnect at 125 s). The
+ manifest lists the cut as `lease_bound_seams_skipped` and
+ `lease_bound_faults_skipped`; 600 s runs on pushes, schedules and manual
+ dispatch still crash every seam and run every fault.
+
+## Gates
+
+- `bun run verify` (69 checks) and `bun run typecheck`.
+- `bun run ci:ubicloud` on `8bd4e81f9`: 3,345 items, 0 failed (gitleaks 1,
+ unit 2,468, serial 433, slow 30, E2E 412 against Postgres and PgBouncer,
+ verify 1), 8 min 27 s wall.
+- Lane focused tests after the merge: the 65 unit, serial and slow files green locally; the 11 E2E files green in `ci:ubicloud`.
+- `persistence-validation.yml` (manual run, every Bun version): all jobs green.
+- OpenClaw native context-engine startup test against pgvector pg16 with
+ openclaw 2026.9.4: 1 of 1 pass.
+- `uvx semgrep scan --config p/default --config p/typescript --error --baseline-commit origin/master`: 0 findings on 177 changed files.
+- `bun run wave-security-scan origin/master..HEAD`: no obfuscation or eval;
+ `admin/dist` changed and rebuilds byte-identical from `admin/src`; one
+ gitleaks hit, a function-body sha256 in the migrations golden, which
+ `.gitleaks.toml` allowlists.
+- `bun run check:agent-contract`: OK.
+- gstack credential pre-push guard on every push: no HIGH findings (MEDIUM
+ hits are minified constants in `admin/dist` and a version-shaped string).
+
+## Deferred (TODOS)
+
+P1: a held sync lock reaches agents as `internal_error` (skipped test; the
+agent-output contract owns it); ENOSPC and lost-exit process faults; a seeded
+mutation pass; source and writer-lifecycle ops in the robot. P2: a restarted
+Postgres owner waits out its predecessor's claims; a CI check that every
+mutating operation is registered with the robot; pre-activation claim lock
+order; the three link-extraction writers' attribution; one write path for
+unmanaged brains; the `permissions` mirror after 2026-11-04; Postgres MCP
+search at 20k pages; chronicle occurrence status, keyless invite projection
+and invite-aware cost accounting. P3: `forget` as backfill proof,
+`register-client --takes-holders`, `embed --stale` budget overshoot,
+`findOrphans` paging.
diff --cc docs/guides/life-chronicle.md
index e35046908a,ece54823f1..9a9c4dc587
--- a/docs/guides/life-chronicle.md
+++ b/docs/guides/life-chronicle.md
@@@ -44,44 -45,29 +44,68 @@@ A page is extracted automatically when
The page must also stay unchanged for `chronicle.auto_settle_seconds` (default
180) so a note written in several passes is extracted once.
+ ## What becomes an event
+
+ An event is something the page records as having happened by the end of its
+ own day: the meeting or conversation itself, what was decided, said or agreed
+ in it, and earlier events the text dates. Plans, follow-ups, deadlines and
+ scheduled meetings are not events, even when the page gives them a date.
+
+ Two rules are enforced after the model answers, before anything is written:
+
+ - **No event after the page's own day.** The page's own day is the latest of
+ its own date (frontmatter `date` or `start`, or an authored effective date),
+ a calendar invite's `end`, and a conversation's last message, read in
+ `chronicle.tz` (default UTC). Anything on that day counts. A proposed event
+ dated later, or after today, is dropped as `future_dated`. "Board meeting in
+ Austin on May 15" in an April 18 meeting note never becomes a May 15 event.
+ - **No invented days.** Events are stored by day. A past event the text dates
+ only by year or month ("back in 2024", "last month") is dropped as
+ `date_imprecise` rather than pinned to January 1 or the first of the month.
+
+ The phase result reports dropped proposals by reason in `events_dropped`. When
+ every proposed event of a page is dropped, its ledger row records that reason
+ instead of `no_events`.
+
+## Calendar invites
+
+A calendar invite is a page under `calendar/` or `cal/` (or of type
+`calendar-event`) with a title and frontmatter `start` and `end`, the shape the
+Google calendar import writes. Once its end time passes, the chronicle phase
+turns it into one event without a chat call:
+
+| Event field | Value |
+|---|---|
+| `what` and title | `Scheduled: <invite title>` |
+| `when` | the invite's `start` |
+| `who` | the invite's `attendees` |
+| `where` | the invite's `location` |
+| `kind` | `meeting` |
+| `captured_via` | `life-chronicle:invite` |
+
+An invite is not proof that you attended. The `Scheduled:` prefix and
+`captured_via: life-chronicle:invite` say the meeting was on the calendar, not
+that it happened; meeting notes under `meetings/` carry what happened. The
+projection takes no daily-limit slot and records a zero cost; publication,
+operator-edit protection and retirement work exactly as for judged events. A
+calendar page without a title, `start` and `end` is judged like a meeting page.
++The date rules above apply to projected invites too.
+
+## Event pages
+
+Each event is a `life/events/<day>-<hash>` page. `<day>` is the event's day in
+the brain timezone (`chronicle.tz`, default UTC), and `<hash>` is derived from
+who, what and the source page, so re-extracting the same content updates the
+same page.
+
+Two events of one page can share who, what and day, for example a morning and
+an afternoon "Call with alice-example". Both are kept: one holds the bare slug
+and the other gets `-<hash6>`, derived from its time, place and kind.
+Byte-identical events get `-2`, `-3`. The assignment does not depend on the
+order the model lists events: an event keeps the slug it already has across
+reorderings and re-extractions, the earliest event takes a free bare slug, and
+correcting one event moves only that event.
+
## Cost and limits
| Setting | Default | What it does |
diff --cc docs/mcp/ADMIN.md
index ddc0bb5054,4199964199..0944e42e34
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@@ -297,10 -247,10 +297,10 @@@ gbrain auth rescope --client CLIENT_ID
| Flag | Value | Effect |
| --- | --- | --- |
-| `--sources` | `a,b` or `none` | Source grant; the first id is the write source, the list is the read set. `default` is the source named `default`; to restore the no-grant floor use `--reset-default sources`. Tokens: `none` grants no source, so reads and writes to every source are refused (`permission_denied`, `fence=no_source_grant`), including writes accepted before the change. Clients: `none` refuses (`client_sources_none_unsupported`); cut a client off with `gbrain auth revoke-client <client_id>`. |
+| `--sources` | `a,b` or `none` | Source grant; the first id is the write source, the list is the read set. `default` is the source named `default`; to restore the no-grant floor use `--reset-default sources`. `none` grants no source, so reads and writes to every source are refused (`permission_denied`, `fence=no_source_grant`), including writes accepted before the change; the token or client keeps its scopes and secret. A client with `none` takes no `--read-sources`, and a delegating agent client cannot hold it. |
| `--read-sources` | `a,b` | Client only: a read set that differs from `--sources`. |
-| `--takes-holders` | `a,b` or `none` | Token only: takes-holder allow-list; `none` hides every take. |
+| `--takes-holders` | `a,b` or `none` | Takes-holder allow-list for a token or client (default `world`); `none` hides every take. |
- | `--operations` | `op,...` or `none` | Operation snapshot; `none` refuses every operation. |
+ | `--operations` | `op,...`, `none` or `all` | Operation snapshot; `none` refuses every operation. Client only: `all` stores no snapshot and clears the profile, so the scopes and the surface alone decide, including operations later upgrades add (tokens: `--reset-default operations`). |
| `--scopes` | `read,write,...` | Replaces the scopes. |
| `--reset-default` | `sources,takes-holders,operations` | Token only: restores the `auth create` default for those axes: no source grant (the historical `default` floor), holders `world`, no operation snapshot. |
| `--refresh-operations` | with optional `--add op,...` or `--all-new` | Token only: previews operations added since the snapshot. Without `--add` or `--all-new` nothing is widened. |
diff --cc llms-full.txt
index b86f34d069,a463826f7f..97c5e99084
--- a/llms-full.txt
+++ b/llms-full.txt
@@@ -5108,29 -5112,37 +5112,37 @@@ The legacy copier handles every other d
| Refusing side | `fix.next` | Next step |
|---|---|---|
- | A PGLite brain moving to Postgres (history or managed) | `ask_user` | Relay `user_message`: keep the brain on PGLite and share it with other machines through `gbrain mcp expose` (effects `persistent_install`, `egress`), or leave it as it is. A verified PGLite-to-Postgres graduation that carries this history is not available yet. |
-| A PGLite brain with history moving to Postgres with graduation turned off | `ask_user` | Relay `user_message`: graduation moves this brain (`gbrain config unset migrate.graduation`, then the [two-command flow](guides/move-to-postgres.md#move-the-brain)), or keep it on PGLite and share it through `gbrain mcp expose`. |
++| A PGLite brain with history (or a managed one) moving to Postgres with graduation turned off | `ask_user` (consent `egress`) | Relay `user_message`: turn graduation back on (`fix.argv`: `gbrain config unset migrate.graduation`) and preview the move with the read-only plan (`fix.then`: `gbrain migrate --to postgres --url-env GBRAIN_TARGET_URL --plan --json`, then the [two-command flow](guides/move-to-postgres.md#move-the-brain)), or keep it on PGLite and share it through `gbrain mcp expose`. |
| A Postgres brain moving to PGLite | `report` | The brain stays on Postgres; moving down would drop its history. |
- | A target that already holds persistence history | `tell_user_to_run` | `gbrain migrate --to <engine> --url <empty_database_url>` with an empty database the user provides (`--path` for a PGLite target). |
-
-
- The migration and the autopilot daemon do not race: `migrate --to` claims a
- cooperative pause marker before touching the target. The marker doubles as a
- migration mutex — a second concurrent migrate refuses to run, and a marker
- that cannot be written refuses the migration outright. Background job workers
- stop picking up new work while it is parked, and the migration waits for
- in-flight sync/embed/cycle work and running jobs to actually drain (watching
- the DB lock table, capped by `GBRAIN_MIGRATE_QUIESCE_SECONDS` — default 300;
- `0` skips the wait). Cleanup registers the moment the claim lands, so the
- marker is released on failure and on catchable signals; a marker orphaned by
- an uncleanly killed run is adopted by a later migrate only after a
- pid-liveness check (a live migrate's marker is never stolen), and the daemon
- clears an orphan whose owning process died on its next poll. `gbrain
- autopilot --status` reports `paused` (exit 1) while the marker is parked and
- prints the marker path; on a host with no daemon running to self-heal,
- remove an orphan by hand only after confirming the pid it names is dead.
- After a clean flip the daemon detects the engine change on its next
- tick and relaunches onto the new engine, and the migration warns if an
- exported connection-string env var would override the new config.
+ | A target that already holds persistence history | `tell_user_to_run` | Rerun with an empty database the user provides (`--path` for a PGLite target). |
+
+ On Windows, a PGLite brain with history gets `graduation_unsupported_platform` instead: it stays on PGLite and is shared with `gbrain mcp expose`.
+
+ <a id="graduation-writer-held"></a>**Graduation refused: the brain is held (`graduation_source_writer_held`).** Graduation needs the PGLite kernel lock. A live stdio `gbrain serve` hands the brain over through the intent marker `<path>.gbrain-graduation.json` and exits; autopilot pauses. When another holder (an HTTP serve, a daemon, another command) does not release the brain within 30 seconds, the run refuses and names it with its pid and transport (`fix.next: tell_user_to_run`). The user stops that process, then the agent reruns the same `gbrain migrate` command. Verify with the read-only `gbrain migrate --status --json`. Nothing has changed in either datastore.
+
+ The migration and the autopilot daemon do not race: both graduation and the
+ legacy copier claim a cooperative pause marker before touching the target. The
+ marker doubles as a migration mutex — a second concurrent migrate refuses to
+ run (graduation exits 75 with `graduation_in_progress`), and a marker that
+ cannot be written refuses the migration outright. Background job workers stop
+ picking up new work while it is parked. The legacy copier then waits for
+ in-flight sync/embed/cycle work and running jobs to drain (watching the DB lock
+ table, capped by `GBRAIN_MIGRATE_QUIESCE_SECONDS` — default 300; `0` skips the
+ wait). Graduation holds the PGLite kernel lock instead, so no other process has
+ the brain open: expired run locks and active job leases are orphans it resets
+ at once, and it waits only for queued write requests, bounded by
+ `--drain-timeout` (default 60 seconds; exhaustion exits 11 with a
+ `resume_command`). Cleanup registers the moment the claim lands, so the marker
+ is released on failure and on catchable signals; a marker orphaned by an
+ uncleanly killed run is adopted by a later migrate only after a pid-liveness
+ check (a live migrate's marker is never stolen), and the daemon clears an
+ orphan whose owning process died on its next poll. `gbrain autopilot --status`
+ reports `paused` (exit 1) while the marker is parked and prints the marker
+ path; on a host with no daemon running to self-heal, remove an orphan by hand
+ only after confirming the pid it names is dead. After a clean flip the daemon
+ detects the engine change on its next tick and relaunches onto the new engine,
+ and the migration warns if an exported connection-string env var would
+ override the new config (graduation lists such a variable as a plan blocker).
### Troubleshooting: startup abort (`RuntimeError: Aborted()`)
diff --cc scripts/e2e-test-map.ts
index 2fc0af4c11,2f1ae8bb76..c32edbc48c
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@@ -129,14 -136,7 +137,14 @@@ export const E2E_TEST_MAP: Record<strin
// F3: unified token grant columns, lazy migration, drift and the born-unified mint on Postgres.
"src/core/grants/model.ts": ["test/e2e/access-token-grants.test.ts"],
"src/core/grants/access-token-schema.ts": ["test/e2e/access-token-grants.test.ts"],
- "src/core/token-mint.ts": ["test/e2e/access-token-grants.test.ts", "test/e2e/auth-rescope-token.test.ts"],
+ "src/core/token-mint.ts": ["test/e2e/access-token-grants.test.ts", "test/e2e/auth-rescope-token.test.ts", "test/e2e/serve-http-api-keys.test.ts"],
+ // Lane E: dashboard API keys, the bulk legacy grant conversion and the OAuth client grant axes on Postgres.
+ "src/commands/serve-http-api-keys.ts": ["test/e2e/serve-http-api-keys.test.ts"],
+ "src/core/grants/oauth-client-axes-schema.ts": ["test/e2e/oauth-client-grant-axes.test.ts"],
+ "src/core/grants/cli.ts": ["test/e2e/oauth-client-grant-axes.test.ts"],
+ "src/core/grants/service.ts": ["test/e2e/oauth-client-grant-axes.test.ts", "test/e2e/client-grants.test.ts"],
- "src/core/schema-migrations/v201-legacy-token-grant-conversion.ts": ["test/e2e/access-token-grants.test.ts"],
- "src/core/schema-migrations/v202-oauth-client-grant-axes.ts": ["test/e2e/oauth-client-grant-axes.test.ts"],
++ "src/core/schema-migrations/v202-legacy-token-grant-conversion.ts": ["test/e2e/access-token-grants.test.ts"],
++ "src/core/schema-migrations/v203-oauth-client-grant-axes.ts": ["test/e2e/oauth-client-grant-axes.test.ts"],
"src/core/facts/withdrawal*.ts": ["test/e2e/delegated-grants-withdrawal.test.ts", "test/e2e/withdrawal-bounded-safety-postgres.test.ts", "test/e2e/withdrawal-crash-postgres.test.ts", "test/e2e/memory-safety-wave-postgres.test.ts", "test/e2e/fact-withdrawal-scope-postgres.test.ts"],
"src/commands/mcp*.ts": ["test/e2e/harness-access.test.ts"],
// OpenRouter subagent-loop families: the family allowlist + recipe feed the
@@@ -267,10 -267,21 +275,22 @@@
"src/commands/migrate-engine.ts": [
"test/e2e/multi-source-bug-class.test.ts",
"test/e2e/migrate-engine-pglite-to-postgres.test.ts",
+ "test/e2e/graduation-legacy-copy.test.ts",
],
+ // Engine graduation (PGLite -> Postgres): the CLI, the orchestrator modules and the serve guard.
+ "src/commands/migrate-graduation.ts": GRADUATION_E2E_TESTS,
+ "src/core/persistence/engine-graduation*.ts": GRADUATION_E2E_TESTS,
+ "src/core/persistence/graduation-*.ts": GRADUATION_E2E_TESTS,
+ "src/core/persistence/graduation-copy.ts": ["test/e2e/graduation-copy.test.ts"],
+ "src/core/persistence/graduation-target.ts": ["test/e2e/graduation-copy.test.ts"],
+ "test/helpers/graduation-copy-harness.ts": ["test/e2e/graduation-copy.test.ts"],
+ "src/commands/doctor/checks/engine-graduation.ts": ["test/e2e/graduation-clients.test.ts"],
+ "scripts/persistence/graduation-*.ts": GRADUATION_E2E_TESTS,
+ "test/helpers/graduation-*.ts": GRADUATION_E2E_TESTS,
+ "test/fixtures/graduation/**": GRADUATION_E2E_TESTS,
// Any minions queue/worker/handler change exercises all minion E2E.
"src/core/minions/**": [
+ "test/e2e/job-deferral-postgres.test.ts",
"test/e2e/minions-legacy-coalesce-postgres.test.ts",
"test/e2e/minions-legacy-journey-postgres.test.ts",
"test/e2e/worker-readiness-cli.test.ts",
@@@ -512,8 -521,7 +532,9 @@@
"test/e2e/chronicle-auto-decision-postgres.test.ts",
"test/e2e/chronicle-auto-phase-postgres.test.ts",
"test/e2e/chronicle-event-privacy-postgres.test.ts",
+ "test/e2e/chronicle-event-identity-postgres.test.ts",
+ "test/e2e/chronicle-invite-projection-postgres.test.ts",
+ "test/e2e/chronicle-date-quality-postgres.test.ts",
"test/e2e/chronicle-surfaces-postgres.test.ts",
],
// #5876: doctor auto_chronicle + the chronicle advisor read the ledger rollups.
diff --cc scripts/function-size-baseline.tsv
index 13956a087f,9c9162efa5..9306b93b6e
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@@ -22,9 -22,9 +22,9 @@@ src/commands/extract.ts runExtract 398
src/commands/import.ts runImport 972 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts); +3 #5988: heldPaths skip so a full sync never imports a rename destination it held this run (logic in commands/sync/holds.ts)
src/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/migrate-engine.ts runMigrateEngine 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
- src/commands/serve.ts installStdioLifecycle 322 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 GBRA-40 Lane D: facts drain install call and its shutdown stop (logic in installFactsDrain)
-src/commands/serve.ts installStdioLifecycle 316 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 engine graduation (GBRA-50 G3): onShutdownReady hook for the graduation hand-off (logic in installGraduationHandoff)
++src/commands/serve.ts installStdioLifecycle 323 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 GBRA-40 Lane D: facts drain install call and its shutdown stop (logic in installFactsDrain); +1 engine graduation (GBRA-50 G3): onShutdownReady hook for the graduation hand-off (logic in installGraduationHandoff)
src/commands/sources.ts runAdd 365 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 4 #5673: connector sources print that autopilot keeps them synced after the first sync
- src/core/ai/gateway.ts chat 311 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+ src/core/ai/gateway.ts chat 313 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5490: a configured chat_fallback_chain hands the call to chatWithFallback (loop lives in ai/chat-fallback.ts)
src/core/bootstrap/harness.ts applyHarness 1167 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/brainstorm/orchestrator.ts _runBrainstormInner 413 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5890 close-set spreads INTERNAL_BREADTH_SEARCH_OPTS
src/core/check-resolvable.ts checkResolvable 419 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --cc scripts/module-size-limits.tsv
index ac699d482a,a5363702a5..7edd9ab883
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@@ -3,28 -3,28 +3,28 @@@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
- src/cli.ts 3200 ratchet +1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured)
-src/cli.ts 3208 ratchet +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed)
++src/cli.ts 3208 ratchet +1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed)
src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts)
src/commands/doctor.ts 667 ratchet +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2219 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts)
src/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch)
src/commands/extract.ts 2528 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit)
src/commands/jobs.ts 660 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5)
-src/commands/serve-http.ts 919 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities)
+src/commands/serve-http.ts 924 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts)
- src/core/ai/gateway.ts 4393 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts)
+ src/core/ai/gateway.ts 4407 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced)
src/commands/sync.ts 510 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured)
-src/core/cycle.ts 3224 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224)
-src/core/cycle/synthesize.ts 3311 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict)
-src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)
+src/core/cycle.ts 3235 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts)
- src/core/cycle/synthesize.ts 3298 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed summary page)
++src/core/cycle/synthesize.ts 3312 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict)
+src/core/cycle/extract-atoms.ts 1809 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement)
src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse)
src/core/import-file.ts 2178 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts)
- src/core/pglite-engine.ts 2930 ratchet +4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts)
- src/core/postgres-engine.ts 2917 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured)
-src/core/pglite-engine.ts 2978 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move)
++src/core/pglite-engine.ts 2982 ratchet +4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move)
+ src/core/postgres-engine.ts 2919 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target)
src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
src/core/types.ts 2124 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field)
-src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys
+src/core/minions/queue.ts 2523 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack
src/commands/init.ts 1869 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch
@@@ -36,7 -36,7 +36,7 @@@ src/core/embedding-migration.ts 1569 ra
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
- src/core/config.ts 1840 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts)
-src/core/config.ts 1840 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts)
++src/core/config.ts 1842 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts)
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 663 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)
diff --cc skills/migrations/v0.60.53.0.md
index 5879f9abaa,0000000000..093cb1f432
mode 100644,000000..100644
--- a/skills/migrations/v0.60.53.0.md
+++ b/skills/migrations/v0.60.53.0.md
@@@ -1,47 -1,0 +1,47 @@@
+# Upgrade to v0.60.53.0: automatic facts on PGLite, scoped dashboard keys
+
+Two behavior changes reach existing brains. On PGLite, `gbrain serve` now
+turns queued pages into facts on its own, which spends money on the
+configured facts model. New admin-dashboard API keys get read and write, not
+admin, unless the user ticks admin.
+
+1. **Finish the upgrade.** `gbrain upgrade` runs it. To be sure, on the brain
+ host:
+ ```bash
+ gbrain apply-migrations --yes --no-autopilot-install
+ ```
- Migration v201 converts every legacy token grant to the grant columns
- without changing what any token can do; v202 adds per-client source and
++ Migration v202 converts every legacy token grant to the grant columns
++ without changing what any token can do; v203 adds per-client source and
+ takes-holder columns. Restart every `gbrain serve`, autopilot and worker.
+
+2. **Tell the user about the automatic facts drain (PGLite only).** It is on
+ by default. Each extracted page is one paid chat call, capped at $1 per run
+ and $5 per rolling day. Show the state:
+ ```bash
+ gbrain doctor --only facts_drain --json
+ ```
+ If the user does not want automatic extraction, run
+ `gbrain config set facts.extraction_enabled false` after they say so. Raise
+ a cap (`facts.drain_budget_usd`, `facts.drain_daily_budget_usd`) only with
+ their agreement. Guide: `docs/guides/facts-drain.md`.
+
+3. **Show the user any full-access API keys.**
+ ```bash
+ gbrain doctor --only legacy_token_null_scope --json
+ ```
+ Each listed key can do everything, including admin. Ask the user which
+ keys need admin; narrow the rest with the printed command, for example
+ `gbrain auth rescope --id <token-id> --scopes read,write`. Never narrow a
+ key without the user's agreement: an agent using it may lose access.
+
+4. **Check the repairs this release adds.**
+ ```bash
+ gbrain doctor --only revision_backfill,legacy_token_grant_shape --json
+ gbrain repair take-supersession # preview; writes nothing
+ ```
+ Follow `revision_backfill`'s printed command if it warns. Show the user the
+ take-supersession preview before running it with `--apply`.
+
+5. **Know the new options.** `gbrain auth rescope --client <id> --sources none`
+ gives an OAuth client no source access without rotating its secret;
+ `--takes-holders a,b|none` sets which takes it can read.
diff --cc skills/skills.lock.json
index e57dbd2a4b,a54625edd5..2382f0465b
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@@ -164,7 -164,7 +164,8 @@@
"migrations/v0.60.45.0.md": "ed92f7b642f1e84e6381ef9e7e855db1ac7d20abd9b79a7bb359c707a04b8b9d",
"migrations/v0.60.47.0.md": "91a6015e3b85c6f2c8048680ee5873895ae2b1948bad8ba6cebce679c3ec7085",
"migrations/v0.60.5.0.md": "0d3ee19359a2740de08ac9ec388ddc15e7c72d663afe33832e1e54170528acab",
- "migrations/v0.60.53.0.md": "ccb5291c02795e73df80baee4ea809756c7c5f0544f879853d89cc05d72662cd",
+ "migrations/v0.60.52.0.md": "ae49b2f51ba6288e4883d8bfda9f494f821e160e227164aa065a645d4e9ae87b",
++ "migrations/v0.60.53.0.md": "0c43dffb7926703d024b4dbe6ed84a87b630b587c84b42c84f931f13f9c089cf",
"migrations/v0.60.6.0.md": "1cbfca2c899e1348acbd61f0baa4c8e723b5283ff868c710c74e116c0cb6726e",
"migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a",
"migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a",
diff --cc src/commands/auth.ts
index b1f8b58696,1a49f5490a..17f9e89190
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@@ -1123,10 -1122,13 +1123,13 @@@ Usage
grants. A bare name matching both a token and a
client refuses; pass --token or --client.
--sources <id1,id2,...|none> Source grant (first = write source; 'none' = deny-all,
- tokens only — revoke a client with revoke-client)
+ scopes and secret unchanged)
--read-sources <id1,id2,...> Client only: a read set that differs from --sources
- --takes-holders <h1,h2,...|none> Token only: takes-holder allow-list ('none' = deny-all)
+ --takes-holders <h1,h2,...|none> Takes-holder allow-list (default world; 'none' = deny-all)
- --operations <op1,op2,...|none> Operation snapshot ('none' = deny-all)
+ --operations <op1,op2,...|none|all> Operation snapshot ('none' = deny-all). Client only:
+ 'all' = no snapshot: every operation the scopes and the
+ surface allow, including ones later upgrades add; clears
+ the profile (tokens: --reset-default operations)
--scopes <read,write,...> Replace the scopes
--reset-default <sources,takes-holders,operations> Token only: restore the auth create default for those axes
--refresh-operations [--add <op,...>|--all-new] Token only: preview operations added since the snapshot;
diff --cc src/commands/doctor/checks/legacy-token-grants.ts
index 9a0416f8ed,a2bcc8ab06..e923d96970
--- a/src/commands/doctor/checks/legacy-token-grants.ts
+++ b/src/commands/doctor/checks/legacy-token-grants.ts
@@@ -1,12 -1,10 +1,12 @@@
/**
* F3 legacy token grants (O-CEO-8, O-DX-9).
*
- * `legacy_token_grant_shape` (informational, status ok): active tokens still
- * on the JSONB-only grant shape. They keep working; the next grant edit
- * migrates each one, or `gbrain auth rescope --migrate-legacy` writes the
- * columns for all of them without changing any grant.
+ * `legacy_token_grant_shape` (warn when non-zero): active tokens still on
- * the JSONB-only grant shape. Schema migration v201 converts every
++ * the JSONB-only grant shape. Schema migration v202 converts every
+ * well-formed one; an older binary's `auth create` can add more, which
+ * convert on their next authorization read or with
+ * `gbrain auth rescope --migrate-legacy`. A malformed one denies every axis
+ * until the user picks its grant. Reports the grant-mirror window end date.
*
* `legacy_token_grant_drift` (warn): migrated tokens whose `permissions`
* mirror disagrees with the grant columns (an older gbrain edited the JSONB).
diff --cc src/commands/migrate-engine.ts
index 7ecb6291a1,83692bc235..3a521c57f0
--- a/src/commands/migrate-engine.ts
+++ b/src/commands/migrate-engine.ts
@@@ -831,11 -826,33 +831,34 @@@ export async function quiesceAutopilot(
return resume;
}
+ /**
+ * PGLite -> Postgres reaches this legacy copier only when graduation is not
+ * routed (src/commands/migrate-graduation.ts routesToGraduation): opted out
+ * with migrate.graduation=false, or Windows. On Windows a brain with write
+ * history gets graduation's platform refusal; a history-free brain copies here.
+ */
+ export async function assertWindowsGraduationPlatform(sourceEngine: BrainEngine, opts: Pick<MigrateOpts, 'targetEngine'>, platform: NodeJS.Platform = process.platform): Promise<void> {
+ if (platform !== 'win32' || sourceEngine.kind !== 'pglite' || opts.targetEngine !== 'postgres') return;
+ const { graduationOptedOut } = await import('./migrate-graduation.ts');
+ if (graduationOptedOut(loadConfig())) return;
+ const tables = ['persistence_requests', 'fact_withdrawals', 'persistence_worktrees'];
+ const present = await sourceEngine.executeRaw<{ name: string }>(
+ `SELECT table_name AS name FROM information_schema.tables WHERE table_schema = 'public' AND table_name = ANY($1::text[])`, [tables]);
+ for (const { name } of present) {
+ const [row] = await sourceEngine.executeRaw<{ present: boolean }>(`SELECT EXISTS(SELECT 1 FROM ${name}) AS present`);
+ if (row?.present) {
+ const { unsupportedPlatformError } = await import('../core/persistence/graduation-errors.ts');
+ throw unsupportedPlatformError({ platform: 'Windows' });
+ }
+ }
+ }
+
export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]): Promise<void> {
const opts = parseArgs(args);
+ await assertWindowsGraduationPlatform(sourceEngine, opts);
- await assertUnmanagedCanonicalWriter(sourceEngine, 'engine migration');
- await assertLegacyEngineMigration(sourceEngine);
+ const migration = { from: sourceEngine.kind, to: opts.targetEngine };
+ await assertUnmanagedCanonicalWriter(sourceEngine, 'engine migration', { migration: { side: 'source', ...migration } });
+ await assertLegacyEngineMigration(sourceEngine, { side: 'source', ...migration });
const config = loadConfig();
if (!config) {
console.error('No brain configured. Run: gbrain init');
diff --cc src/commands/serve.ts
index bbc560696d,388a46fa53..44e1c1085d
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@@ -7,8 -7,8 +7,9 @@@ import { startMcpServer, stdioRpcsInFli
import { VERB_NAMES } from '../core/verbs.ts';
import { RESIDENT_POOL_FLOOR } from '../core/pg-access-classify.ts';
import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';
+import { startFactsDrainScheduler, type FactsDrainScheduler, type FactsDrainSchedulerOpts } from '../core/facts/drain-scheduler.ts';
import { onForwardProgress } from '../core/forward-progress.ts';
+ import { graduationHandoffRequested, writeServeGraduationEnvelope } from '../core/persistence/graduation-serve-guard.ts';
import {
installLoopStallWatchdog,
resolveServeStallWatchdogMs,
diff --cc src/core/chronicle/contract.ts
index 73739e7530,18d5a6b8b0..09b6cd3f02
--- a/src/core/chronicle/contract.ts
+++ b/src/core/chronicle/contract.ts
@@@ -21,14 -21,10 +21,15 @@@
*/
import { CHRONICLE_RUN_NOW_ARGV, type ChronicleReasonCode } from './reasons.ts';
import type { Action } from '../agent-output.ts';
+ import type { ChronicleDropCounts } from './extract-events.ts';
-/** Bump to re-extract every page once (the ledger key includes it). */
-export const CHRONICLE_EXTRACTOR_VERSION = 1;
+/**
+ * The ledger key includes it, so a bump makes already-extracted content new again: the phase's
+ * discovery re-decides pages changed since activation (unmanaged brains judge the recent ones under
+ * the daily limit; managed brains record `no_write_decision`) and backfill re-queues the rest on request.
+ * 2: same-day event slug disambiguation (event-identity.ts) and ended-invite projection (invite-projection.ts).
+ */
+export const CHRONICLE_EXTRACTOR_VERSION = 2;
/** Ledger table and its columns (migration `chronicle_page_state`). */
export const CHRONICLE_LEDGER_TABLE = 'chronicle_page_state';
diff --cc src/core/chronicle/execute.ts
index 5db16bd3b5,bc3a27ce4f..9f46290991
--- a/src/core/chronicle/execute.ts
+++ b/src/core/chronicle/execute.ts
@@@ -22,8 -20,10 +22,11 @@@ import { CHRONICLE_DEFAULTS, CHRONICLE_
import type { ChronicleReasonCode } from './reasons.ts';
import type { ChronicleSettings } from './config.ts';
import { isChronicleEligible } from './eligibility.ts';
- import { buildChronicleEvents, chronicleJudgeContext, isValidProposal, type ChronicleJudge, type ChronicleJudgeResult } from './extract-events.ts';
+ import {
+ allDroppedReason, buildChronicleEvents, chronicleJudgeContext, isValidProposal,
+ type ChronicleDropCounts, type ChronicleJudge, type ChronicleJudgeResult,
+ } from './extract-events.ts';
+import { endedInviteProposal, markInviteEvents } from './invite-projection.ts';
import { RETIRE_REASONS, reserveChronicleSlot } from './ledger.ts';
import { pinDepth, publishChronicleGeneration, type ChronicleDepthPin } from './publish.ts';
@@@ -208,12 -207,12 +211,13 @@@ export async function executeChronicleR
}
const proposals = result?.events ?? [];
+ const { events, dropped } = buildChronicleEvents(proposals, judgeCtx,
+ { slug: pin.slug, visibility: pin.visibility, contentHash: pin.contentHash }, { tz: ctx.tz, now });
let generation;
try {
- const built = buildChronicleEvents(proposals, judgeCtx, { slug: pin.slug, visibility: pin.visibility, contentHash: pin.contentHash }, ctx.tz);
generation = await publishChronicleGeneration(engine, {
- sourceId: row.source_id, pin, decisionRequestId: row.request_id, maintenance: ctx.maintenance, signal: ctx.signal, events,
+ sourceId: row.source_id, pin, decisionRequestId: row.request_id, maintenance: ctx.maintenance, signal: ctx.signal,
- events: invite ? markInviteEvents(built) : built,
++ events: invite ? markInviteEvents(events) : events,
});
} catch (error) {
if ((error as Error)?.name === 'AbortError') throw error;
diff --cc src/core/cli-flag-registry.generated.ts
index 2da4cc8ce9,7ddecc3473..efc875d4cf
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@@ -43,11 -43,11 +43,11 @@@ export const CLI_FLAG_REGISTRY: Record<
'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],
'connectors': ['--accept-pending', '--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--wait', '--window-days', '--yes'],
'conversation-parser': ['--brain', '--help', '--json', '--source'],
- 'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--to', '--url', '--version'],
+ 'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--rollback-to-source', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
- 'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
++ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--rollback-to-source', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
+ 'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
@@@ -69,16 -69,16 +69,16 @@@
'graph-query': ['--brain', '--depth', '--direction', '--help', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--seat', '--session', '--show-current', '--show-toplevel', '--source'],
'import': ['--accept-pending', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--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', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--to', '--touchpoint', '--url', '--version', '--yes'],
+ 'init': ['--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--plan', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--to', '--touchpoint', '--url', '--url-env', '--version', '--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', '--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', '--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', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--hard-deadline', '--health-interval', '--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', '--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-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--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', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--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', '--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-meetings', '--full', '--full-history', '--fuzzy', '--hard-deadline', '--health-interval', '--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', '--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-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--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', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all', '--wait'],
'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
- 'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--sources', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
++ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
- 'migrate': ['--accept-pending', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-migrate', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--wait', '--yes'],
+ 'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
'models': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status', '--to'],
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],
@@@ -100,7 -100,7 +100,7 @@@
'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],
'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],
- 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
- 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
++ 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--scopes', '--source', '--timeout'],
'repair': ['--all', '--apply', '--brain', '--diff', '--expect', '--help', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--only', '--remediate', '--remediation-plan', '--skip', '--source', '--stale', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
@@@ -118,11 -118,11 +118,11 @@@
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],
+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-accept-pending', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait', '--wait-drain', '--yes'],
'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
- 'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],
+ 'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
++ 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
diff --cc src/core/grants/access-token-schema.ts
index f56eb39e5c,2ee074d34e..e990567c3e
--- a/src/core/grants/access-token-schema.ts
+++ b/src/core/grants/access-token-schema.ts
@@@ -1,11 -1,10 +1,11 @@@
/**
* F3 (O-CEO-8, O-ENG-7): legacy bearer tokens get the OAuth client grant
* columns. `source_grant` names the source state explicitly; NULL means the
- * row still uses the `permissions` JSONB shape: migration v201 converts every
- * row still uses the `permissions` JSONB shape and is read through the lane F
- * parsers until its next write (`auth rescope`, `auth create`, rotation, or
- * `auth rescope --migrate-legacy`). No foreign key on `source_id`: the client
- * FK is ON DELETE RESTRICT, and tokens must not start blocking source removal.
++ * row still uses the `permissions` JSONB shape: migration v202 converts every
+ * such active row, and one an older binary adds converts on its next HTTP
+ * read (`resolveTokenGrant`), grant write, or `auth rescope --migrate-legacy`.
+ * No foreign key on `source_id`: the client FK is ON DELETE RESTRICT, and
+ * tokens must not start blocking source removal.
*
* Migration-only, like `permissions` (v038): the schema blob's access_tokens
* has neither, so fresh installs and upgrades both add the columns in the same
diff --cc src/core/grants/cli.ts
index 3dda9b6525,54598087b8..2cd210714b
--- a/src/core/grants/cli.ts
+++ b/src/core/grants/cli.ts
@@@ -122,18 -143,17 +143,18 @@@ const TOKEN_ONLY_FLAGS: Record<string,
};
/**
- * Client flags of `auth rescope --client`: the unified `--sources a,b`
+ * Client flags of `auth rescope --client`: the unified `--sources a,b|none`
* (element 0 = write source, the list = read set unless `--read-sources`
- * names a different one), `--read-sources`, `--operations a,b|none|all` and every
- * `auth rescope-client` flag. `--sources none` refuses (decision 4: client
- * deny-all is `auth revoke-client`).
+ * names a different one; `none` is the explicit no-source grant that refuses
- * every read and write), `--read-sources`, `--operations a,b|none`,
++ * every read and write), `--read-sources`, `--operations a,b|none|all`,
+ * `--takes-holders a,b|none` and every `auth rescope-client` flag.
*/
export function parseClientRescopeArgs(clientId: string, args: string[]): RescopeGrantArgs {
const legacy: string[] = [];
let sources: string[] | undefined;
let readSources: string[] | undefined;
- let operations: string[] | undefined;
+ let operations: string[] | 'all' | undefined;
+ let takesHolders: string[] | undefined;
const csv = (value: string): string[] => [...new Set(value.split(',').map(s => s.trim()).filter(Boolean))];
for (let i = 0; i < args.length; i++) {
const flag = args[i];
@@@ -149,8 -169,7 +170,8 @@@
if (value === undefined || value.startsWith('--')) throw new GrantError('invalid_grant', `${flag} requires a value`);
if (flag === '--sources') sources = value === 'none' ? [] : csv(value);
if (flag === '--read-sources') readSources = csv(value);
- if (flag === '--operations') operations = value === 'none' ? [] : csv(value);
+ if (flag === '--operations') operations = value === 'none' ? [] : value === 'all' ? 'all' : csv(value);
+ if (flag === '--takes-holders') takesHolders = value === 'none' ? [] : csv(value);
}
const result = parseRescopeGrantFlags(legacy);
if (sources !== undefined) {
@@@ -159,18 -178,14 +180,21 @@@
shape: 'unified', drift: [], permissionsMalformed: false,
sources: sources.length === 0 ? { kind: 'none' } : { kind: 'federated', writeSource: sources[0], readSources: sources },
}, { operationNames: new Set() });
- result.patch.sourceId = sources[0];
+ result.patch.sourceId = sources.length === 0 ? null : sources[0];
+ result.patch.sourcesNone = sources.length === 0;
}
if (readSources !== undefined && readSources.length === 0) throw new GrantError('invalid_grant', '--read-sources needs at least one source id');
+ if (sources?.length === 0 && readSources !== undefined) throw new GrantError('invalid_grant', '--sources none grants no source, so it takes no --read-sources');
if (sources !== undefined || readSources !== undefined) result.patch.federatedRead = readSources ?? sources;
- if (operations !== undefined) result.patch.allowedOperations = operations;
+ if (operations === 'all') {
+ clearOperationSnapshot(result.patch);
+ assertProfileKept(result, '--operations all');
+ } else if (operations !== undefined) result.patch.allowedOperations = operations;
+ if (takesHolders !== undefined) {
+ const invalid = takesHolders.filter(h => !isValidHolder(h));
+ if (invalid.length) throw new GrantError('invalid_grant', `Invalid takes holder: ${invalid.join(', ')} (use world, brain, people/<slug>, companies/<slug> or a bare slug)`, ['takes_holders_invalid']);
+ result.patch.takesHolders = takesHolders;
+ }
if (!result.profile && Object.keys(result.patch).length === 0) throw new GrantError('invalid_grant', 'Pass a grant field or --profile to rescope');
return result;
}
diff --cc src/core/grants/legacy-token.ts
index cafbb391f3,9f8be741ac..82e513221b
--- a/src/core/grants/legacy-token.ts
+++ b/src/core/grants/legacy-token.ts
@@@ -18,10 -18,9 +18,10 @@@
* `source_id`, `federated_read`, `allowed_operations`, `takes_holders`), bumps
* `grant_revision`, and rewrites `permissions` as a mirror with every other key
* preserved, so older binaries enforce the same grant. Rows still on the
- * JSONB-only shape convert in bulk (migration v201, `--migrate-legacy`), on
- * JSONB-only shape migrate lazily on their first write, or in bulk with
- * `--migrate-legacy`. A drifted row (JSONB edited by an older binary) refuses
- * grant edits until `--adopt-permissions` or `--adopt-columns` resolves it.
++ * JSONB-only shape convert in bulk (migration v202, `--migrate-legacy`), on
+ * their first HTTP read (`resolveTokenGrant`) or on their first write. A
+ * drifted row (JSONB edited by an older binary) refuses grant edits until
+ * `--adopt-permissions` or `--adopt-columns` resolves it.
*/
import type { BrainEngine } from '../engine.ts';
import { assertAllowedScopes, operationScopesAllowed } from '../scope.ts';
diff --cc src/core/persistence/maintenance.ts
index 6f16fecb7e,2e0e47d0b4..3a46050892
--- a/src/core/persistence/maintenance.ts
+++ b/src/core/persistence/maintenance.ts
@@@ -1,66 -1,21 +1,72 @@@
- import { existsSync, renameSync } from 'node:fs';
- import { join } from 'node:path';
- import { acquireLock, releaseLock } from '../pglite-lock.ts';
+ import { existsSync, lstatSync, realpathSync, renameSync } from 'node:fs';
+ import { flushDirectory } from '../fs-durable.ts';
+ import { dirname, join } from 'node:path';
+ import { acquireLock, releaseLock, type LockHandle } from '../pglite-lock.ts';
import { assertManagedFilesystemWrite } from './filesystem-guard.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
import type { SqlEngine } from './model.ts';
++import { DEFAULT_TARGET_URL_ENV, planArgv } from './graduation-errors.ts';
// Every facts-family bulk writer now publishes through the coordinator on a
// managed brain (#5280); status and activation keep reporting the (empty) list.
export const UNSUPPORTED_MANAGED_BULK_WRITERS: readonly string[] = [];
+export const ENGINE_MIGRATION_DOCS = 'docs/ENGINES.md#engine-migration-refused';
++const GRADUATION_DOCS = 'docs/guides/move-to-postgres.md#move-the-brain';
+const DOCTOR_VERIFY = { argv: ['gbrain', 'doctor', '--no-migrate', '--json'] };
+type EngineKind = 'pglite' | 'postgres';
+/** Which side of `gbrain migrate --to` a refusal names: the brain being moved, or the datastore it would land in. */
+export interface EngineMigrationSide { side: 'source' | 'target'; from: EngineKind; to: EngineKind }
+
+/**
+ * The refusal's next step, by side. A PGLite brain moving up gets the user's
+ * choice: wait for verified graduation, or stay on PGLite and share it over
+ * MCP. A Postgres brain moving down keeps its datastore. A target that
+ * already holds persistence state needs an empty database.
+ */
+function engineMigrationFix(m: EngineMigrationSide, why: string): Action {
+ if (m.side === 'target') {
+ return { argv: ['gbrain', 'migrate', '--to', m.to, ...(m.to === 'postgres' ? ['--url', '<empty_database_url>'] : ['--path', '<empty_brain_path>'])],
+ inputs: [m.to === 'postgres'
+ ? { name: 'empty_database_url', how: 'Ask the user for the connection string of an empty Postgres database (a new database or project).' }
+ : { name: 'empty_brain_path', how: 'Ask the user for a path where no PGLite brain exists yet.' }],
+ consent: [], actor: 'user', requires_exclusive: true, docs: ENGINE_MIGRATION_DOCS, verify: DOCTOR_VERIFY,
+ why: `${why} The migration target already holds another brain's write history, so gbrain will not copy into it; the source brain is untouched.`,
+ user_message: 'The database you chose to migrate into already holds another gbrain brain. Do you have an empty database to use instead? Nothing has changed in your current brain.' };
+ }
+ if (m.from === 'postgres') {
+ return { consent: [], actor: 'agent', requires_exclusive: false, docs: ENGINE_MIGRATION_DOCS, verify: DOCTOR_VERIFY,
+ why: `${why} Moving a Postgres brain with this history to PGLite would drop it, so the brain stays on Postgres; nothing changed.`,
+ user_message: 'Your brain stays on Postgres: moving it to PGLite would lose its write history and withdrawn facts. Nothing changed.' };
+ }
- return { argv: ['gbrain', 'mcp', 'expose'], consent: ['persistent_install', 'egress'], actor: 'agent', requires_exclusive: false,
- docs: ENGINE_MIGRATION_DOCS, verify: DOCTOR_VERIFY,
- why: `${why} A verified PGLite-to-Postgres graduation that carries this history is not available yet. Until it is, the brain stays on PGLite; `
- + '`gbrain mcp expose` shares it with agents on other machines without moving it.',
- user_message: 'Your brain cannot move to Postgres yet without losing its write history and withdrawn facts. '
- + 'Should I keep it on PGLite and share it with your other machines over MCP (gbrain mcp expose), or leave it as it is until graduation to Postgres is available? Nothing has changed.' };
++ return { argv: ['gbrain', 'config', 'unset', 'migrate.graduation'], consent: ['egress'], actor: 'agent', requires_exclusive: false,
++ docs: GRADUATION_DOCS, verify: DOCTOR_VERIFY,
++ why: `${why} The legacy copier cannot carry this history; graduation copies it intact and reaches this brain only while `
++ + '`migrate.graduation` is not turned off. Turning it back on and previewing the plan changes nothing; the move itself runs only after the user approves that plan.',
++ user_message: 'Your brain has write history, which the legacy copier cannot move. Graduation moves it with everything intact, and it is turned off on this machine: '
++ + 'should I turn it back on and preview the move to Postgres (nothing changes yet), or keep the brain on PGLite and share it with `gbrain mcp expose`?',
++ then: { argv: planArgv(), consent: [], actor: 'agent', requires_exclusive: false, docs: GRADUATION_DOCS,
++ inputs: [{ name: DEFAULT_TARGET_URL_ENV, how: `Ask the user for the target Postgres connection string and export it as ${DEFAULT_TARGET_URL_ENV} in this shell; it never goes on the command line.` }],
++ why: 'The read-only graduation plan: what moves, the blockers and the plan_hash the move is approved with. Nothing changes.' } };
+}
+
/** Refuse unsupported multi-stage writers before providers, files or git change. */
-export async function assertUnmanagedCanonicalWriter(engine: SqlEngine, operation: string): Promise<void> {
+export async function assertUnmanagedCanonicalWriter(engine: SqlEngine, operation: string, opts: { migration?: EngineMigrationSide } = {}): Promise<void> {
const rows = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if (rows?.[0]?.enabled) throw new OperationError('writer_coordinator_required',
- `${operation} cannot mutate a managed brain through the legacy writer.`,
- 'Use supported persistence operations. Source topology and maintenance require a verified drain before migration.');
+ if (!rows?.[0]?.enabled) return;
+ const message = `${operation} cannot mutate a managed brain through the legacy writer.`;
+ const why = 'This brain is managed: every write goes through its writer coordinator, which the legacy writer bypasses.';
+ if (opts.migration) {
+ throw opError('writer_coordinator_required', message,
+ 'Keep this datastore; the engine copier cannot carry a managed brain. Ask the user how to proceed.',
+ { why, reason: 'managed_brain', docs: ENGINE_MIGRATION_DOCS, fix: engineMigrationFix(opts.migration, why) });
+ }
+ throw opError('writer_coordinator_required', message,
+ `Run the same gbrain command again: it routes a managed brain through the coordinator, and the brain became managed while ${operation} ran.`,
+ { why, reason: 'managed_brain', fix: { consent: [], actor: 'agent', requires_exclusive: false, verify: DOCTOR_VERIFY,
+ why: `${why} Each gbrain command that changes sources or imports content takes the coordinated path on a managed brain, so the same command run again uses it; nothing was written.`,
+ user_message: `gbrain stopped ${operation} because your brain switched to managed writes while it ran. Nothing was written; running the same command again uses the managed path.` } });
}
/** The legacy engine copier cannot transfer permanent IDs, withdrawals or ownership. */
diff --cc src/core/schema-migrations/registry.generated.ts
index d39f28ec02,36586eea84..a48b20c71b
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@@ -201,8 -201,7 +201,9 @@@ import { v197 } from './v197-managed-gu
import { v198 } from './v198-publication-failure-detail.ts';
import { v199 } from './v199-chronicle-page-state.ts';
import { v200 } from './v200-sync-hold-page-index.ts';
- import { v201 } from './v201-legacy-token-grant-conversion.ts';
- import { v202 } from './v202-oauth-client-grant-axes.ts';
+ import { v201 } from './v201-persistence-graduation.ts';
++import { v202 } from './v202-legacy-token-grant-conversion.ts';
++import { v203 } from './v203-oauth-client-grant-axes.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@@ -403,5 -402,4 +404,6 @@@ export const MIGRATIONS: Migration[] =
v199,
v200,
v201,
+ v202,
++ v203,
];
diff --cc src/core/schema-migrations/v202-legacy-token-grant-conversion.ts
index 0f67bb7e50,0000000000..8b2d85b396
mode 100644,000000..100644
--- a/src/core/schema-migrations/v202-legacy-token-grant-conversion.ts
+++ b/src/core/schema-migrations/v202-legacy-token-grant-conversion.ts
@@@ -1,30 -1,0 +1,30 @@@
+import { migrateLegacyTokens } from '../grants/legacy-token.ts';
+import { migrationNotice } from './helpers.ts';
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// Converts every active legacy bearer token still on the JSONB-only grant
+// shape (`source_grant IS NULL`) to the unified grant columns in one
+// transaction, through the same `migrateLegacyTokens` that
+// `gbrain auth rescope --migrate-legacy` runs: no effective grant changes and
+// `permissions` stays as the mirror older binaries read. A malformed
+// `permissions` value has no faithful column form, so it stays on the legacy
+// shape and denies every axis; doctor `legacy_token_grant_shape` lists it.
+// Handler-only and rerun-safe (a second run finds no unconverted rows).
- export const v201: Migration = {
- version: 201,
++export const v202: Migration = {
++ version: 202,
+ name: 'legacy_token_grant_conversion',
+ idempotent: true,
+ sql: '',
+ handler: async engine => {
+ const result = await migrateLegacyTokens(engine, { dryRun: false });
+ if (result.migrated.length === 0 && result.skipped.length === 0) return;
- migrationNotice(` v201: converted ${result.migrated.length} legacy token grant(s) to the unified grant columns; no grant changed.`
++ migrationNotice(` v202: converted ${result.migrated.length} legacy token grant(s) to the unified grant columns; no grant changed.`
+ + (result.skipped.length
+ ? ` ${result.skipped.length} token(s) with malformed permissions stay denied; gbrain doctor (legacy_token_grant_shape) lists each one with its fix.`
+ : '')
+ + '\n');
+ },
+};
diff --cc src/core/schema-migrations/v203-oauth-client-grant-axes.ts
index e652c0f1ce,0000000000..0dfc5adc7f
mode 100644,000000..100644
--- a/src/core/schema-migrations/v203-oauth-client-grant-axes.ts
+++ b/src/core/schema-migrations/v203-oauth-client-grant-axes.ts
@@@ -1,16 -1,0 +1,16 @@@
+import { OAUTH_CLIENT_GRANT_AXES_SQL } from '../grants/oauth-client-axes-schema.ts';
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// OAuth clients gain the explicit no-source grant (`source_grant = 'none'`)
+// and a per-client takes-holder allow-list (fragment
+// src/core/grants/oauth-client-axes-schema.ts). Additive and metadata-only:
+// every existing client keeps NULL in both, which is its current grant.
- export const v202: Migration = {
- version: 202,
++export const v203: Migration = {
++ version: 203,
+ name: 'oauth_client_grant_axes',
+ idempotent: true,
+ sql: OAUTH_CLIENT_GRANT_AXES_SQL,
+};
diff --cc test/auth-rescope-unified.serial.test.ts
index a12dd59b0f,0625f905fd..2c11da7690
--- a/test/auth-rescope-unified.serial.test.ts
+++ b/test/auth-rescope-unified.serial.test.ts
@@@ -157,18 -158,37 +158,39 @@@ describe('9. OAuth clients', () =>
expect(await clientRow(a.clientId)).toMatchObject({ source_id: 'other', federated_read: ['other', 'default'], allowed_operations: ['get_page', 'search'] });
const none = await cli('auth', 'rescope', '--client', a.clientId, '--sources', 'none', '--json');
- expect(none.exitCode).toBe(1);
- const body = JSON.parse(none.stdout) as { error: { reasons: string[]; message: string } };
- expect(body.error.reasons).toEqual(['client_sources_none_unsupported']);
- expect(body.error.message).toContain(`gbrain auth revoke-client ${a.clientId}`);
- expect((await clientRow(a.clientId)).source_id).toBe('other');
-
- const holders = await cli('auth', 'rescope', '--client', a.clientId, '--takes-holders', 'world');
- expect(holders.exitCode).toBe(1);
- expect(holders.stderr).toContain('--takes-holders applies to legacy tokens only');
+ expect(none.exitCode).toBe(0);
+ expect(JSON.parse(none.stdout).principal_grant.sources).toEqual({ kind: 'none' });
+ expect(await clientRow(a.clientId)).toMatchObject({ source_id: null, federated_read: [] });
+
+ const holders = await cli('auth', 'rescope', '--client', a.clientId, '--takes-holders', 'world,brain');
+ expect(holders.exitCode).toBe(0);
+ expect(holders.stdout).toContain('Takes holders: world, brain');
+
+ const reset = await cli('auth', 'rescope', '--client', a.clientId, '--reset-default', 'sources');
+ expect(reset.exitCode).toBe(1);
+ expect(reset.stderr).toContain('--reset-default applies to legacy tokens only');
}, 180_000);
+
+ test('--operations all drops a profile snapshot on both client spellings; a token refuses it', async () => {
+ const [a, b] = await withBrain(async engine => {
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const register = (name: string) => provider.registerClientManual(name, ['client_credentials'], 'read write', [], 'default', undefined, undefined, undefined,
+ resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }));
+ return [await register('client-all-a-example'), await register('client-all-b-example')];
+ });
+ const grantRow = (id: string) => withBrain(async engine =>
+ (await engine.executeRaw<Record<string, unknown>>('SELECT grant_profile, allowed_operations, scope FROM oauth_clients WHERE client_id = $1', [id]))[0]);
+ expect((await grantRow(a.clientId)).grant_profile).toBe('memory-writer');
+ expect((await cli('auth', 'rescope', '--client', a.clientId, '--operations', 'all')).exitCode).toBe(0);
+ expect((await cli('auth', 'rescope-client', b.clientId, '--allowed-operations', 'all')).exitCode).toBe(0);
+ for (const id of [a.clientId, b.clientId]) expect(await grantRow(id)).toEqual({ grant_profile: null, allowed_operations: null, scope: 'read write' });
+
+ expect((await cli('auth', 'create', 'tok-all')).exitCode).toBe(0);
+ const token = await cli('auth', 'rescope', '--token', 'tok-all', '--operations', 'all');
+ expect(token.exitCode).toBe(1);
+ expect(token.stderr).toContain('--reset-default operations');
+ expect((await tokenRow('tok-all')).allowed_operations).toBeNull();
+ }, 180_000);
test('a bare name that matches both a token and a client refuses as ambiguous', async () => {
const client = await withBrain(async engine => {
diff --cc test/chronicle-date-quality.test.ts
index 0000000000,b4327f9ca2..6312765bb3
mode 000000,100644..100644
--- a/test/chronicle-date-quality.test.ts
+++ b/test/chronicle-date-quality.test.ts
@@@ -1,0 -1,160 +1,161 @@@
+ /**
+ * Life Chronicle date quality (CL-1 premature events, CL-2 invented days) on a managed brain.
+ *
+ * Protects: an event is published only when the page records it as happened by the end of the
+ * page's own day. A plan dated after the page (a follow-up, a scheduled offsite) is dropped as
+ * `future_dated`; a past event the judge can date only by year or month ("back in 2024" → "2024")
+ * is dropped as `date_imprecise` instead of being pinned to YYYY-01-01. Same-day events, ended
+ * invites, a conversation's later messages and generation reconciliation keep working.
+ * Fails when: a proposal dated after the page's day, or without a day, reaches life/events/.
+ * Seams: injected judge (`runPhaseChronicle({ judge })`, `runChronicleExtract({ judge })`).
+ */
+ import { describe, expect, test } from 'bun:test';
+ import type { BrainEngine } from '../src/core/engine.ts';
+ import type { OperationContext } from '../src/core/ops/contract.ts';
+ import { operationsByName } from '../src/core/operations.ts';
+ import { runPhaseChronicle } from '../src/core/cycle/chronicle.ts';
+ import {
+ chronicleEventCutoff, chronicleJudgeContext, runChronicleExtract, screenChronicleProposals,
+ type ChronicleEventProposal, type ChronicleJudge,
+ } from '../src/core/chronicle/extract-events.ts';
+ import { managedBrain, type ManagedBrain } from './helpers/managed-brain.ts';
+ import { requirePostgresTestDatabase } from './helpers/test-backends.ts';
+
+ /** PGLite in the unit lane; the e2e wrapper reruns every case on an isolated Postgres database. */
+ const databaseUrl = process.env.GBRAIN_TEST_BACKEND === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const brain = (run: (b: ManagedBrain) => Promise<void>) => managedBrain(run, { databaseUrl });
+
+ const day = (offsetDays: number) => new Date(Date.now() + offsetDays * 86_400_000).toISOString().slice(0, 10);
+ const PAGE_DAY = day(-3);
+ const BODY = 'Alice and Bob reviewed the launch plan, agreed to ship the beta and scheduled the team offsite. '.repeat(3);
+ const meeting = (body = BODY, extra = `date: ${PAGE_DAY}\n`) => `---\ntype: meeting\ntitle: Sync\n${extra}---\n\n${body}`;
+ const ev = (when: string, what: string, kind = 'meeting'): ChronicleEventProposal => ({ when, who: ['people/alice-example'], what, kind });
+
+ async function put(ctx: OperationContext, slug: string, content: string) {
+ const current = await ctx.engine.readPageSnapshot(slug, { sourceId: 'default' });
+ return operationsByName.put_page.handler(ctx, { slug, content, ...(current ? { expected_revision: current.revision } : {}) });
+ }
+ async function settle(engine: BrainEngine) {
+ await engine.executeRaw("UPDATE chronicle_page_state SET next_attempt_at=now()-interval '1 second', decided_at=now()-interval '1 hour' WHERE state='pending'");
+ }
+ async function events(engine: BrainEngine) {
+ return engine.executeRaw<{ day: string; what: string; deleted: boolean }>(
+ `SELECT substring(slug from 13 for 10) AS day, frontmatter->'event'->>'what' AS what, deleted_at IS NOT NULL AS deleted
+ FROM pages WHERE type='event' ORDER BY what`);
+ }
+ async function ledger(engine: BrainEngine) {
+ return engine.executeRaw<{ slug: string; state: string; reason: string | null }>(
+ 'SELECT slug, state, reason FROM chronicle_page_state WHERE attempts > 0 ORDER BY slug, decided_at');
+ }
+ async function runOnce(engine: BrainEngine, judge: ChronicleJudge) {
+ await settle(engine);
+ return runPhaseChronicle(engine, { judge });
+ }
+
+ describe('CL-1: nothing after the page\'s own day', () => {
+ test('a past meeting mentioning a future offsite publishes the meeting, never the offsite', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'meetings/sync', meeting());
+ const r = await runOnce(engine, async () => ({ events: [
+ ev(PAGE_DAY, 'Alice and Bob reviewed the launch plan'),
+ ev(day(-1), 'Alice to send the beta notes', 'commitment'),
+ ev(day(30), 'Team offsite in Austin', 'travel'),
+ ] }));
+ expect(r.details).toMatchObject({ judged: 1, extracted: 1, events_written: 1, events_dropped: { future_dated: 2 } });
+ expect((await events(engine)).map((e) => [e.day, e.what])).toEqual([[PAGE_DAY, 'Alice and Bob reviewed the launch plan']]);
+ expect(await ledger(engine)).toEqual([{ slug: 'meetings/sync', state: 'extracted', reason: null }]);
+ const offsite = await operationsByName.chronicle_day.handler(ctx, { date: day(30) }) as unknown[];
+ expect(offsite).toEqual([]);
+ }), 120_000);
+
+ test('same-day events are kept, to the end of the page\'s day', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'meetings/sync', meeting(BODY, `date: ${PAGE_DAY}\nstart: ${PAGE_DAY}T10:00:00Z\n`));
+ const r = await runOnce(engine, async () => ({ events: [
+ ev(PAGE_DAY, 'The sync itself'),
+ ev(`${PAGE_DAY}T23:30:00Z`, 'Late follow-up call', 'call'),
+ ] }));
+ expect(r.details).toMatchObject({ events_written: 2, events_dropped: {} });
+ expect((await events(engine)).map((e) => e.day)).toEqual([PAGE_DAY, PAGE_DAY]);
+ }), 120_000);
+
+ test('an ended calendar invite still produces its meeting event', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'calendar/standup', `---\ntype: calendar-event\ntitle: Standup\ndate: ${PAGE_DAY}\nstart: ${PAGE_DAY}T16:00:00Z\nend: ${PAGE_DAY}T16:30:00Z\n---\n\n${BODY}`);
- const r = await runOnce(engine, async () => ({ events: [ev(`${PAGE_DAY}T16:00:00Z`, 'Standup with Alice')] }));
- expect(r.details).toMatchObject({ judged: 1, extracted: 1, events_written: 1 });
- expect((await events(engine)).map((e) => [e.day, e.what])).toEqual([[PAGE_DAY, 'Standup with Alice']]);
++ // An ended invite is projected without the judge (invite-projection.ts); the date screen keeps its event.
++ const r = await runOnce(engine, async () => { throw new Error('an ended invite must not reach the judge'); });
++ expect(r.details).toMatchObject({ judged: 0, extracted: 1, events_written: 1, events_dropped: {} });
++ expect((await events(engine)).map((e) => [e.day, e.what])).toEqual([[PAGE_DAY, 'Scheduled: Standup']]);
+ }), 120_000);
+
+ test('a multi-day conversation runs to its last message', () => brain(async ({ engine, ctx }) => {
+ const chat = [`**Alice** (${day(-4)} 9:30 PM): Can we move the launch review?`,
+ `**Bob** (${day(-3)} 10:05 AM): Yes, moved it and shipped the beta build.`,
+ `**Alice** (${day(-3)} 10:07 AM): Great, thanks for shipping it.`].join('\n\n');
+ await put(ctx, 'conversations/launch', `---\ntype: conversation\ntitle: Launch chat\ndate: ${day(-4)}\n---\n\n${chat}\n`);
+ const r = await runOnce(engine, async () => ({ events: [
+ ev(day(-4), 'Alice asked to move the launch review', 'event'),
+ ev(day(-3), 'Bob shipped the beta build', 'work'),
+ ev(day(-2), 'Launch review', 'meeting'),
+ ] }));
+ expect(r.details).toMatchObject({ events_written: 2, events_dropped: { future_dated: 1 } });
+ expect((await events(engine)).map((e) => e.day).sort()).toEqual([day(-4), day(-3)]);
+ }), 120_000);
+
+ test('re-extraction retires the old generation even when every new proposal is dropped', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'meetings/sync', meeting());
+ await runOnce(engine, async () => ({ events: [ev(PAGE_DAY, 'Alice and Bob reviewed the launch plan')] }));
+ await put(ctx, 'meetings/sync', meeting(`${BODY} Wording changed.`));
+ const r = await runOnce(engine, async () => ({ events: [ev(day(10), 'Offsite planning session')] }));
+ expect(r.details).toMatchObject({ judged: 1, no_events: 1, events_written: 0, events_retired: 1,
+ events_dropped: { future_dated: 1 }, reasons: { future_dated: 1 } });
+ expect((await events(engine)).map((e) => [e.what, e.deleted])).toEqual([['Alice and Bob reviewed the launch plan', true]]);
+ expect((await ledger(engine)).map((row) => [row.state, row.reason])).toEqual([['extracted', null], ['extracted', 'future_dated']]);
+ }), 120_000);
+ });
+
+ describe('CL-2: no invented days', () => {
+ test('"back in 2024" never becomes a 2024-01-01 event', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'meetings/sync', meeting(`${BODY} Back in 2024 Alice ran the first pilot; last month the pilot closed.`));
+ const r = await runOnce(engine, async () => ({ events: [
+ ev('2024', 'Alice ran the first pilot', 'work'),
+ ev('2024-03', 'The pilot closed', 'milestone'),
+ ] }));
+ expect(r.details).toMatchObject({ judged: 1, no_events: 1, events_written: 0,
+ events_dropped: { date_imprecise: 2 }, reasons: { date_imprecise: 1 } });
+ expect(await events(engine)).toEqual([]);
+ expect(await operationsByName.chronicle_day.handler(ctx, { date: '2024-01-01' })).toEqual([]);
+ expect(await ledger(engine)).toEqual([{ slug: 'meetings/sync', state: 'extracted', reason: 'date_imprecise' }]);
+ }), 120_000);
+
+ test('the direct extractor reports drops and keeps the dated events', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'meetings/sync', meeting());
+ const r = await runChronicleExtract(engine, { slug: 'meetings/sync', judge: async () => ({ events: [
+ ev(PAGE_DAY, 'The sync itself'), ev('2024', 'Pilot', 'work'), ev(day(5), 'Offsite', 'travel'),
+ ] }) });
+ expect(r).toMatchObject({ status: 'extracted', events_written: 1, events_dropped: { date_imprecise: 1, future_dated: 1 } });
+ const none = await runChronicleExtract(engine, { slug: 'meetings/sync', judge: async () => ({ events: [ev(day(5), 'Offsite', 'travel')] }) });
+ expect(none).toMatchObject({ status: 'no_events', reason: 'future_dated', events_written: 0, events_dropped: { future_dated: 1 } });
+ }), 120_000);
+ });
+
+ describe('cutoff arithmetic', () => {
+ const ctxFor = (frontmatter: Record<string, unknown>, body = BODY) =>
+ chronicleJudgeContext({ slug: 'meetings/x', type: 'meeting', title: 'X', compiled_truth: body, frontmatter });
+ const now = new Date('2026-10-04T12:00:00Z');
+
+ test('a date-only page keeps its own day in any brain timezone', () => {
+ const ctx = ctxFor({ date: '2026-04-18' });
+ expect(chronicleEventCutoff(ctx, 'America/Los_Angeles', now)).toBe('2026-04-18');
+ expect(chronicleEventCutoff(ctx, 'Asia/Tokyo', now)).toBe('2026-04-18');
+ const { kept, dropped } = screenChronicleProposals([
+ ev('2026-04-18T22:00:00-07:00', 'Late call'), ev('2026-04-19', 'Next day'), ev('2026-04', 'Sometime in April'),
+ ], ctx, 'America/Los_Angeles', now);
+ expect(kept.map((k) => k.what)).toEqual(['Late call']);
+ expect(dropped).toEqual({ future_dated: 1, date_imprecise: 1 });
+ });
+
+ test('a meeting\'s end extends the day in the brain timezone; nothing passes today', () => {
+ expect(chronicleEventCutoff(ctxFor({ start: '2026-04-18T23:00:00Z', end: '2026-04-19T01:00:00Z' }), 'UTC', now)).toBe('2026-04-19');
+ expect(chronicleEventCutoff(ctxFor({ start: '2026-04-18T23:00:00Z', end: '2026-04-19T01:00:00Z' }), 'America/Los_Angeles', now)).toBe('2026-04-18');
+ expect(chronicleEventCutoff(ctxFor({ date: '2026-12-01' }), 'UTC', now)).toBe('2026-10-04');
+ expect(chronicleEventCutoff(ctxFor({}), 'UTC', now)).toBe('2026-10-04');
+ });
+ });
diff --cc test/chronicle-event-identity.test.ts
index f6fbe5b01f,0000000000..a827ae18eb
mode 100644,000000..100644
--- a/test/chronicle-event-identity.test.ts
+++ b/test/chronicle-event-identity.test.ts
@@@ -1,188 -1,0 +1,189 @@@
+/**
+ * Life Chronicle same-day event identity (event-identity.ts).
+ *
+ * Protects: two distinct proposals that share who, what and day on one depth
+ * page publish as two events; the slug set does not depend on proposal order;
+ * a correction leaves the other events' slugs alone; a page extracted before
+ * disambiguation keeps its event slug when an extractor-version bump
+ * reprocesses it; the day is the brain timezone's day.
+ * Fails when: a collision collapses two events into one page, reordering or
+ * a correction moves an unrelated event to another slug, or reprocessing a
+ * legacy page retires and recreates its existing event.
+ * Existing coverage: chronicle-auto-phase pins reconciliation with distinct
+ * summaries only; nothing exercised two proposals with one base slug.
+ * Seams: injected judge (`runPhaseChronicle({ judge })`).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { runPhaseChronicle } from '../src/core/cycle/chronicle.ts';
+import { runChronicleBackfill } from '../src/core/chronicle/backfill.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { buildChronicleEvents, type ChronicleEventProposal, type ChronicleJudge } from '../src/core/chronicle/extract-events.ts';
+import { assignChronicleEventSlugs } from '../src/core/chronicle/event-identity.ts';
+import { managedBrain, type ManagedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase } from './helpers/test-backends.ts';
+
+const databaseUrl = process.env.GBRAIN_TEST_BACKEND === 'postgres' ? requirePostgresTestDatabase() : undefined;
+const brain = (run: (b: ManagedBrain) => Promise<void>) => managedBrain(run, { databaseUrl });
+
+const today = new Date().toISOString().slice(0, 10);
+const BODY = 'Alice and Bob reviewed the launch plan and agreed on the next steps for the beta. '.repeat(3);
+const meeting = (body = BODY) => `---\ntype: meeting\ntitle: Day notes\ndate: ${today}\n---\n\n${body}`;
+const call = (when: string, extra: Partial<ChronicleEventProposal> = {}): ChronicleEventProposal =>
+ ({ when, who: ['people/alice-example'], what: 'Call with alice-example', kind: 'call', ...extra });
+const MORNING = call(`${today}T09:00:00Z`);
+const AFTERNOON = call(`${today}T16:00:00Z`);
+
+async function put(ctx: OperationContext, slug: string, content: string) {
+ const current = await ctx.engine.readPageSnapshot(slug, { sourceId: 'default' });
+ await operationsByName.put_page.handler(ctx, { slug, content, ...(current ? { expected_revision: current.revision } : {}) });
+}
+async function settle(engine: BrainEngine) {
+ await engine.executeRaw("UPDATE chronicle_page_state SET next_attempt_at=now()-interval '1 second', decided_at=now()-interval '1 hour' WHERE state='pending'");
+}
+async function judged(engine: BrainEngine, events: ChronicleEventProposal[]) {
+ await settle(engine);
+ let calls = 0;
+ const judge: ChronicleJudge = async () => { calls++; return { events }; };
+ const r = await runPhaseChronicle(engine, { judge });
+ return { calls, details: r.details };
+}
+async function eventPages(engine: BrainEngine) {
+ return engine.executeRaw<{ id: number; slug: string; when: string; what: string; deleted: boolean }>(
+ `SELECT id, slug, frontmatter->'event'->>'when' AS "when", frontmatter->'event'->>'what' AS what, deleted_at IS NOT NULL AS deleted
+ FROM pages WHERE type='event' ORDER BY slug`);
+}
+const live = async (engine: BrainEngine) => (await eventPages(engine)).filter((e) => !e.deleted);
+const at = (whenIso: string) => new Date(whenIso).toISOString();
+
+function slugsFor(proposals: ChronicleEventProposal[], tz = 'UTC', existing = new Map<string, string>()) {
- const ctx = { input: {} as never, effectiveDate: today, attendees: [] };
- const built = buildChronicleEvents(proposals, ctx, { slug: 'meetings/day', visibility: 'world', contentHash: 'h' }, tz);
++ const ctx = { input: {} as never, effectiveDate: today, attendees: [], pageDates: [new Date(`${today}T23:59:59Z`)] };
++ const { events: built, dropped } = buildChronicleEvents(proposals, ctx, { slug: 'meetings/day', visibility: 'world', contentHash: 'h' }, { tz, now: new Date(`${today}T23:59:59Z`) });
++ expect(dropped).toEqual({});
+ return { legacy: built.map((e) => e.slug), assigned: assignChronicleEventSlugs(built, existing).map((e) => e.slug) };
+}
+
+describe('assignment (no database)', () => {
+ test('collision count on a proposal fixture: legacy slugs vs disambiguated slugs', () => {
+ const fixture: ChronicleEventProposal[] = [
+ MORNING, AFTERNOON,
+ call(`${today}T11:00:00Z`, { what: 'Standup with the beta team', who: ['people/bob-example'], kind: 'meeting' }),
+ call(`${today}T15:00:00Z`, { what: 'Standup with the beta team', who: ['people/bob-example'], kind: 'meeting', where: 'Room 2' }),
+ call(`${today}T15:00:00Z`, { what: 'Standup with the beta team', who: ['people/bob-example'], kind: 'meeting', where: 'Room 3' }),
+ call(`${today}T12:00:00Z`, { what: 'Lunch with carol-example', who: ['people/carol-example'], kind: 'meal' }),
+ ];
+ const { legacy, assigned } = slugsFor(fixture);
+ const collisions = (slugs: string[]) => slugs.length - new Set(slugs).size;
+ expect({ proposals: fixture.length, before: collisions(legacy), after: collisions(assigned) }).toEqual({ proposals: 6, before: 3, after: 0 });
+ // Every group keeps its legacy base slug for exactly one member.
+ expect(new Set(assigned.filter((s) => legacy.includes(s))).size).toBe(new Set(legacy).size);
+ });
+
+ test('reordered proposals produce the same slug set, and the earliest keeps the base slug', () => {
+ const forward = slugsFor([MORNING, AFTERNOON]);
+ const reverse = slugsFor([AFTERNOON, MORNING]);
+ expect(forward.assigned[0]).toBe(forward.legacy[0]);
+ expect(forward.assigned[1]).toMatch(new RegExp(`^${forward.legacy[0]}-[0-9a-f]{6}$`));
+ expect(reverse.assigned).toEqual([forward.assigned[1], forward.assigned[0]]);
+ });
+
+ test('identical copies keep their count with an ordinal suffix', () => {
+ const { legacy, assigned } = slugsFor([MORNING, MORNING]);
+ expect(assigned).toEqual([legacy[0], `${legacy[0]}-2`]);
+ });
+
+ test('timezone boundary: the day is the brain timezone\'s day', () => {
+ const lateNight = call('2026-10-01T23:30:00-07:00');
+ const nextMorning = call('2026-10-02T09:00:00-07:00');
+ const pacific = slugsFor([lateNight, nextMorning], 'America/Los_Angeles');
+ expect(pacific.assigned.map((s) => s.slice('life/events/'.length, 'life/events/'.length + 10))).toEqual(['2026-10-01', '2026-10-02']);
+ expect(pacific.assigned).toEqual(pacific.legacy);
+ // In UTC both instants fall on 2026-10-02 and share a base slug; they still publish as two events.
+ const utc = slugsFor([lateNight, nextMorning], 'UTC');
+ expect(new Set(utc.legacy).size).toBe(1);
+ expect(new Set(utc.assigned).size).toBe(2);
+ });
+});
+
+describe('publication through the chronicle phase', () => {
+ test('two same-day calls publish as two events; reordering changes nothing; a correction moves only the corrected event', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'meetings/day', meeting());
+ expect((await judged(engine, [MORNING, AFTERNOON])).details).toMatchObject({ events_written: 2 });
+ const first = await live(engine);
+ expect(first.map((e) => e.when).map(at).sort()).toEqual([at(MORNING.when), at(AFTERNOON.when)]);
+
+ await put(ctx, 'meetings/day', meeting(`${BODY} Reordered.`));
+ expect((await judged(engine, [AFTERNOON, MORNING])).details).toMatchObject({ events_written: 2, events_retired: 0 });
+ expect(await live(engine)).toEqual(first);
+
+ // The morning call's summary is corrected: it leaves the group, and the afternoon call keeps its slug.
+ await put(ctx, 'meetings/day', meeting(`${BODY} Corrected.`));
+ const corrected = { ...MORNING, what: 'Call with alice-example about the beta' };
+ expect((await judged(engine, [corrected, AFTERNOON])).details).toMatchObject({ events_written: 2, events_retired: 1 });
+ const after = await live(engine);
+ const afternoon = first.find((e) => at(e.when) === at(AFTERNOON.when))!;
+ expect(after.find((e) => e.what === AFTERNOON.what)).toEqual(afternoon);
+ expect(after.map((e) => e.what).sort()).toEqual([AFTERNOON.what, corrected.what]);
+ }), 120_000);
+
+ test('a legacy page reprocessed after the extractor-version bump keeps its event slug', () => brain(async ({ engine, ctx }) => {
+ // Before disambiguation, both calls landed on one base slug and the last proposal won it.
+ await put(ctx, 'meetings/day', meeting());
+ await judged(engine, [AFTERNOON]);
+ const [legacy] = await live(engine);
+ await engine.executeRaw('UPDATE chronicle_page_state SET extractor_version=1');
+
+ // A managed brain leaves the re-decision to backfill; the run then judges the page once more.
+ const queued = await runChronicleBackfill(engine, { yes: true });
+ expect(queued).toMatchObject({ queued: 1, already_done: 0 });
+ const run = await judged(engine, [MORNING, AFTERNOON]);
+ expect(run.calls).toBe(1);
+ expect(run.details).toMatchObject({ events_written: 2, events_retired: 0 });
+ const events = await eventPages(engine);
+ expect(events.every((e) => !e.deleted)).toBe(true);
+ expect(events.find((e) => e.slug === legacy.slug)).toEqual(legacy);
+ const separated = events.find((e) => e.slug !== legacy.slug)!;
+ expect(separated.slug).toMatch(new RegExp(`^${legacy.slug}-[0-9a-f]{6}$`));
+ expect(at(separated.when)).toBe(at(MORNING.when));
+ }), 120_000);
+
+ test('an operator-edited colliding event stays the operator\'s; its sibling still publishes', () => brain(async ({ engine, ctx }) => {
+ await put(ctx, 'meetings/day', meeting());
+ await judged(engine, [MORNING, AFTERNOON]);
+ const before = await live(engine);
+ const morning = before.find((e) => at(e.when) === at(MORNING.when))!;
+ const page = (await engine.readPageSnapshot(morning.slug, { sourceId: 'default' }))!;
+ const { serializePageToMarkdown } = await import('../src/core/markdown.ts');
+ await operationsByName.put_page.handler(ctx, { slug: morning.slug, expected_revision: page.revision,
+ content: serializePageToMarkdown({ ...page.page, compiled_truth: 'Call with alice-example (the operator confirmed it).' }, page.tags) });
+ const edited = (await engine.readPageSnapshot(morning.slug, { sourceId: 'default' }))!;
+ await put(ctx, 'meetings/day', meeting(`${BODY} Again.`));
+ await judged(engine, [AFTERNOON, MORNING]);
+ const after = (await engine.readPageSnapshot(morning.slug, { sourceId: 'default' }))!;
+ expect(after.page.content_hash).toBe(edited.page.content_hash);
+ expect((await live(engine)).map((e) => e.slug)).toEqual(before.map((e) => e.slug));
+ }), 120_000);
+});
+
+describe.skipIf(databaseUrl !== undefined)('unmanaged brain', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+ afterAll(async () => { await engine.disconnect(); });
+
+ test('an extractor-version bump re-queues an already-extracted page automatically', async () => {
+ await engine.setConfig('chronicle.auto_settle_seconds', '0');
+ await engine.setConfig('chronicle.activated_at', new Date(Date.now() - 60_000).toISOString());
+ await engine.putPage('meetings/day', { type: 'meeting', title: 'Day notes', compiled_truth: BODY, frontmatter: { date: today } });
+ expect((await judged(engine, [AFTERNOON])).calls).toBe(1);
+ const [legacy] = await live(engine);
+ expect((await judged(engine, [MORNING, AFTERNOON])).calls).toBe(0);
+ await engine.executeRaw('UPDATE chronicle_page_state SET extractor_version=1');
+ const run = await judged(engine, [MORNING, AFTERNOON]);
+ expect(run.calls).toBe(1);
+ const events = await live(engine);
+ expect(events).toHaveLength(2);
+ expect(events.find((e) => e.slug === legacy.slug)).toEqual(legacy);
+ }, 120_000);
+});
diff --cc test/engine-migration-refusal.test.ts
index 53c5e99414,0000000000..0cf7696800
mode 100644,000000..100644
--- a/test/engine-migration-refusal.test.ts
+++ b/test/engine-migration-refusal.test.ts
@@@ -1,128 -1,0 +1,126 @@@
+/**
+ * `gbrain migrate --to` refusals carry the agent contract (Foundations 2,
+ * "Lane B: refusal now", refusal envelopes and refusal branches).
+ *
+ * Protects: the envelope an agent reads when the legacy engine copier refuses
+ * a brain. The history refusal and the managed-brain refusal are `opError`s
+ * with `why` and a filled `fix` that names the refusing side: a PGLite brain
- * gets the user's choice (stay on PGLite and share it with `gbrain mcp
- * expose`, or wait for graduation, which is not available yet), a Postgres
++ * gets the user's choice (turn graduation back on and preview the move with
++ * its read-only plan, or stay on PGLite and share it with `gbrain mcp
++ * expose`), a Postgres
+ * brain moving down keeps its datastore, and a target that already holds
+ * history needs an empty database. Every branch verifies read-only with
+ * `gbrain doctor --no-migrate --json`. The unknown-engine error is an
+ * `invalid_params` opError, and the usage text names every accepted engine.
+ * Fails when: a refusal goes back to a prose-only OperationError (no `fix`),
+ * a branch loses its side, or the usage text drops `postgres`.
+ * Why new: test/persistence-migration-preservation.test.ts pins only the code.
+ * Seam: none (real PGLite brains; toAgentError renders the CLI and MCP wire).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { assertLegacyEngineMigration, assertUnmanagedCanonicalWriter } from '../src/core/persistence/maintenance.ts';
+import { runMigrateEngine } from '../src/commands/migrate-engine.ts';
+import { toAgentError, type RenderContext } from '../src/core/agent-output.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+
+const routing = { brain: 'host', source: 'default' };
+const cli: RenderContext = { transport: 'cli', isCallable: () => false, preapproved: () => false, routing };
+const stdio: RenderContext = { transport: 'stdio', surface: 'full', isCallable: () => true, preapproved: () => false, routing };
+const VERIFY = ['gbrain', 'doctor', '--no-migrate', '--json'];
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw("INSERT INTO fact_withdrawals(source_id,visibility,fact_hash) VALUES('default','world','refusal-example')");
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+async function refusal(run: () => Promise<unknown>): Promise<OperationError> {
+ const error = await run().then(() => null, (e: unknown) => e);
+ expect(error).toBeInstanceOf(OperationError);
+ return error as OperationError;
+}
+const envelope = (e: unknown, render: RenderContext) => toAgentError(e, { transport: render.transport, render });
+
+describe('history refusal names the refusing side', () => {
- test('a PGLite brain moving to Postgres: ask the user, stay on PGLite and expose it, graduation not available yet', async () => {
++ test('a PGLite brain moving to Postgres: ask the user, preview graduation or stay on PGLite and expose it', async () => {
+ const e = await refusal(() => assertLegacyEngineMigration(engine, { side: 'source', from: 'pglite', to: 'postgres' }));
+ expect(e.code).toBe('writer_coordinator_required');
+ expect(e.why).toContain('fact_withdrawals');
+ const env = envelope(e, cli);
+ expect(env.code).toBe('writer_coordinator_required');
- expect(env.fix).toMatchObject({ next: 'ask_user', consent: ['persistent_install', 'egress'], verify: { argv: expect.arrayContaining(VERIFY) } });
- expect(env.fix?.argv?.slice(0, 3)).toEqual(['gbrain', 'mcp', 'expose']);
++ expect(env.fix).toMatchObject({ next: 'ask_user', consent: ['egress'], verify: { argv: expect.arrayContaining(VERIFY) } });
++ expect(env.fix?.argv?.slice(0, 4)).toEqual(['gbrain', 'config', 'unset', 'migrate.graduation']);
++ expect(env.fix?.then?.argv?.slice(0, 8)).toEqual(['gbrain', 'migrate', '--to', 'postgres', '--url-env', 'GBRAIN_TARGET_URL', '--plan', '--json']);
++ expect(env.fix?.then?.consent).toEqual([]);
++ expect(env.fix?.user_message).toContain('preview the move to Postgres (nothing changes yet)');
+ expect(env.fix?.user_message).toContain('gbrain mcp expose');
- expect(env.fix?.user_message).toContain('until graduation to Postgres is available');
- expect(env.fix?.why).toContain('not available yet');
- expect(JSON.stringify(env)).not.toContain('--plan');
++ expect(env.fix?.why).toContain('graduation copies it intact');
++ expect(JSON.stringify(env)).not.toContain('not available yet');
+ // Over MCP the CLI command is the user's to run; the choice they are asked about is unchanged.
+ expect(envelope(e, stdio).fix).toMatchObject({ next: 'tell_user_to_run', user_message: env.fix?.user_message });
+ });
+
- test('the default side is the PGLite source moving up', async () => {
- const e = await refusal(() => assertLegacyEngineMigration(engine));
- expect(envelope(e, cli).fix?.argv?.slice(0, 3)).toEqual(['gbrain', 'mcp', 'expose']);
- });
-
+ test('a Postgres brain moving to PGLite keeps its datastore', async () => {
+ const e = await refusal(() => assertLegacyEngineMigration(engine, { side: 'source', from: 'postgres', to: 'pglite' }));
+ const env = envelope(e, cli);
+ expect(env.fix?.next).toBe('report');
+ expect(env.fix?.argv).toBeUndefined();
+ expect(env.fix?.user_message).toContain('stays on Postgres');
+ expect(env.fix?.verify?.argv).toEqual(expect.arrayContaining(VERIFY));
+ });
+
+ test('a target that already holds history needs an empty database from the user', async () => {
+ const e = await refusal(() => assertLegacyEngineMigration(engine, { side: 'target', from: 'pglite', to: 'postgres' }));
+ const env = envelope(e, cli);
+ expect(e.why).toContain('target datastore');
+ expect(env.fix).toMatchObject({ next: 'tell_user_to_run', inputs: [{ name: 'empty_database_url' }] });
+ expect(env.fix?.argv?.slice(0, 4)).toEqual(['gbrain', 'migrate', '--to', 'postgres']);
+ expect(env.fix?.user_message).toContain('empty database');
+ });
+
+ test('runMigrateEngine refuses a PGLite brain with history before touching a target, with the filled fix', async () => {
+ const e = await refusal(() => runMigrateEngine(engine, ['--to', 'postgres', '--url', 'postgresql://user@localhost:1/never']));
+ expect(envelope(e, cli).fix?.next).toBe('ask_user');
+ });
+});
+
+describe('managed-brain refusal', () => {
+ beforeAll(async () => { await engine.executeRaw('UPDATE persistence_brain SET enabled = true WHERE singleton = 1'); });
+ afterAll(async () => { await engine.executeRaw('UPDATE persistence_brain SET enabled = false WHERE singleton = 1'); });
+
+ test('engine migration of a managed brain gets the same graduate-or-expose choice', async () => {
+ const e = await refusal(() => assertUnmanagedCanonicalWriter(engine, 'engine migration', { migration: { side: 'source', from: 'pglite', to: 'postgres' } }));
+ expect(e.code).toBe('writer_coordinator_required');
+ expect(e.why).toContain('managed');
+ expect(envelope(e, cli).fix?.next).toBe('ask_user');
- expect(envelope(e, cli).fix?.argv?.slice(0, 3)).toEqual(['gbrain', 'mcp', 'expose']);
++ expect(envelope(e, cli).fix?.then?.argv).toContain('--plan');
+ });
+
+ test('another legacy writer names the coordinated path and verifies read-only', async () => {
+ const e = await refusal(() => assertUnmanagedCanonicalWriter(engine, 'sources archive'));
+ const env = envelope(e, cli);
+ expect(env.fix?.next).toBe('report');
+ expect(env.fix?.why).toContain('coordinated path');
+ expect(env.fix?.user_message).toContain('sources archive');
+ expect(env.fix?.verify?.argv).toEqual(expect.arrayContaining(VERIFY));
+ });
+});
+
+describe('gbrain migrate argument errors', () => {
+ test('an unknown engine is an invalid_params opError whose fix names the accepted engines', async () => {
+ const e = await refusal(() => runMigrateEngine(engine, ['--to', 'duckdb']));
+ expect(e.code).toBe('invalid_params');
+ expect(e.why).toContain('postgres and pglite');
+ const env = envelope(e, cli);
+ expect(env.fix?.inputs?.[0]?.how).toContain('postgres (alias supabase) or pglite');
+ });
+
+ test('the usage text lists every accepted --to value', async () => {
+ const e = await refusal(() => runMigrateEngine(engine, []));
+ for (const value of ['postgres', 'supabase', 'pglite']) expect(e.suggestion).toContain(value);
+ });
+});
diff --cc test/fixtures/goldens/cli/tools-json.json
index cbfe96d68e,5e17c00079..2f3183df9d
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@@ -2,8 -2,8 +2,8 @@@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 196872,
- "stdoutSha256": "f3f521d380697ea70f77982759504f2538ce69d96b7e3ea7c0fb37e36546472d",
- "stdoutBytes": 196986,
- "stdoutSha256": "a94ef05467e333a594813f1214c3c3d5d17174ebf09c587a357b40fde49c668e",
++ "stdoutBytes": 197023,
++ "stdoutSha256": "20847890a8675cef50b3fc32b88c43beae726ee1a0b84a78e7de69d2ce63fa9c",
"toolNames": [
"remember",
"entity",
diff --cc test/fixtures/goldens/doctor/json-pglite-degraded.json
index edc27682eb,96e9a19b27..cfc2cce3e4
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@@ -507,7 -507,7 +507,7 @@@
},
{
"category": "meta",
- "message": "Version 202 (latest: 202)",
- "message": "Version 201 (latest: 201)",
++ "message": "Version 203 (latest: 203)",
"name": "schema_version",
"status": "ok"
},
diff --cc test/fixtures/goldens/doctor/json-pglite-fresh.json
index b67a08ef7e,a93014abc8..78cc0f150b
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@@ -510,7 -510,7 +510,7 @@@
},
{
"category": "meta",
- "message": "Version 202 (latest: 202)",
- "message": "Version 201 (latest: 201)",
++ "message": "Version 203 (latest: 203)",
"name": "schema_version",
"status": "ok"
},
diff --cc test/fixtures/goldens/doctor/json-postgres-fresh.json
index a2499c7217,fec0a85688..d80188b072
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@@ -503,7 -503,7 +503,7 @@@
},
{
"category": "meta",
- "message": "Version 202 (latest: 202)",
- "message": "Version 201 (latest: 201)",
++ "message": "Version 203 (latest: 203)",
"name": "schema_version",
"status": "ok"
},
diff --cc test/fixtures/goldens/doctor/registry-build-checks.json
index c66e9b42f6,bbea2949bb..6440d1562b
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@@ -637,14 -633,6 +641,10 @@@
"category": "ops",
"name": "planner_stats_stale"
},
+ {
+ "category": "meta",
+ "name": "revision_backfill"
+ },
- {
- "category": "ops",
- "name": "chat_fallback_chain_inert"
- },
{
"category": "ops",
"name": "search_mode"
diff --cc test/fixtures/goldens/exports/types.json
index bca7109f3d,7b2ba02b50..b92cdfeeb6
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@@ -5627,7 -5629,7 +5631,7 @@@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_skill\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_disabled\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"fetch_failed\" | \"file_too_large\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_client\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"method_not_allowed\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"redirect_uri_mismatch\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_in_progress\" | \"sync_parser_regression\" | \"target_escape\" | \"topology_change_required\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",
- "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_skill\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_disabled\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_payload_expired\" | \"fetch_failed\" | \"file_too_large\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_client\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"method_not_allowed\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"redirect_uri_mismatch\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_in_progress\" | \"sync_parser_regression\" | \"target_escape\" | \"topology_change_required\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",
++ "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_skill\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_disabled\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"fetch_failed\" | \"file_too_large\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_client\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"method_not_allowed\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"redirect_uri_mismatch\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_in_progress\" | \"sync_parser_regression\" | \"target_escape\" | \"topology_change_required\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --cc test/fixtures/goldens/migrations/records.json
index 083ae70c64,3412cdfbaf..df0f693023
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@@ -1,6 -1,6 +1,6 @@@
{
"golden": {
- "count": 197,
- "count": 196,
++ "count": 198,
"gaps": [
17,
18,
@@@ -29,7 -28,7 +29,7 @@@
"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063",
"verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"
},
- "latest": 202,
- "latest": 201,
++ "latest": 203,
"records": [
{
"handler": {
@@@ -2970,39 -2969,18 +2970,52 @@@
"verify": "absent",
"version": 200
},
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "persistence_graduation",
+ "sql": {
+ "length": 1498,
+ "sha256": "79590a9d55a008e72d52b9b2482a4071b0b0736bac505bdfebf8d23a5ff7b098"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 201
++ },
+ {
+ "handler": {
+ "form": "arrow",
+ "helpers": [
+ "migrateLegacyTokens",
+ "migrationNotice",
+ "quietMigrationNotices"
+ ],
- "sha256": "78b88e6a006553fb8cfb8f292589033de56a1a221bad085d9ae56c2d6ecf1b80"
++ "sha256": "c9c0d95a39855d618deba658ac99c5294047183f38f8abbb92c49d0196021b01"
+ },
+ "idempotent": true,
+ "name": "legacy_token_grant_conversion",
+ "sql": {
+ "length": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
- "version": 201
++ "version": 202
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "oauth_client_grant_axes",
+ "sql": {
+ "length": 179,
+ "sha256": "3bc9490443e69f225bf65df711dbe889a52300ae2b1d5ab977206456c6ed22c8"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
- "version": 202
++ "version": 203
}
],
"versions": [
@@@ -3201,8 -3179,7 +3214,9 @@@
198,
199,
200,
- 201
+ 201,
- 202
++ 202,
++ 203
]
},
"normalizer": "migrations-record-v1"