Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge origin/master (v0.60.52.0) into cat40-entity-wave; release v0.60.57.0
garrytandf4acbebe0dd
diff --cc .claude-plugin/plugin.jsonindex 125eea6d92,2727716b60..afbd2670af--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@@ -1,6 -1,6 +1,6 @@@{"name": "gbrain",- "version": "0.61.1.0",- "version": "0.60.52.0",++ "version": "0.60.57.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --cc .codex-plugin/plugin.jsonindex 7f1bcfd26c,01301db9b2..5d3984604b--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@@ -1,6 -1,6 +1,6 @@@{"name": "gbrain",- "version": "0.61.1.0",- "version": "0.60.52.0",++ "version": "0.60.57.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --cc BOOTSTRAP_FOR_AGENTS.mdindex 81cec98428,6aec89e070..4beb06d119--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@@ -1,4 -1,4 +1,4 @@@- <!-- gbrain-runbook-stamp: 0.61.1.0 -->-<!-- gbrain-runbook-stamp: 0.60.52.0 -->++<!-- gbrain-runbook-stamp: 0.60.57.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --cc CHANGELOG.mdindex df60525c2a,453fa8ccdc..75fffd873b--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -10,87 -10,147 +10,237 @@@ credits are retained; no result has beeidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).- ## [0.61.1.0] - 2026-10-04++## [0.60.57.0] - 2026-10-05+- **Ask your brain about an account and it now hands back every ticket, meeting and email that names it, not just the few a search happens to rank first.**++**Ask your agent for a brief on an account and it now finds the open ticket, the latest contact and the blocker, and it spends about a quarter less to get there.**+- Before this release, a ticket that said `Customer: QUCO` or a meeting titled `QUCO renewal prep` was not connected to the account it was about. Your agent had to search, and search returns the best-matching handful. Nine near-identical tickets look alike to it, so the open one often never showed up. Now the brain links every page that names a person, company or account, by its name, by the name inside a record title (`CRM record: Acme Example`), or by a code the record declares (`Account code: ACMX`). Ask for the account and the card lists all of those pages by type, newest first, each with a one-line preview, plus the exact call to page through the rest. It costs nothing to run: no model calls, no API key.++Before this release, a ticket that said `Customer: QUCO` or a meeting titled `QUCO renewal prep` was not connected to the account it was about. Your agent had to search, and search returns the best-matching handful. Nine near-identical tickets look alike to it, so the open one often never showed up. Now the brain links every page that names a person, company or account, by its name, by the name inside a record title (`CRM record: Acme Example`), or by a code the record declares (`Account code: ACMX`). Ask for the account and the card lists all of those pages by type, newest first, each with a one-line preview, plus the exact call to page through the rest. Building the links costs nothing: no model calls, no API key.++++On Cat 40, the agent benchmark run on five frontier models (Sonnet 5.5, Opus 5.5, Fable 5.1, GPT-6.1 Sol, GPT-6 Astra), account briefs on the held-out world gained 7 points, and overall scores held while cost per task fell 26%. Most tasks already sit near the ceiling, so the overall score cannot move much in either direction; the gain shows up in the briefs and in the bill.++### How to use it++```bash+gbrain extract --stale --catch-up # once after upgrading; autopilot keeps it current+gbrain entity ACMX # the card, with "referenced by N page(s)"+gbrain backlinks crm/acme-example --type ticket --group page+gbrain extract mentions --explain acmx --page meetings/2026-04-03 # why a name did not link+```++Over MCP, the `entity` card adds `referenced_by`, `referenced_by_count` and `coverage`; `get_backlinks` takes `type`, `group: "page"`, `limit` and `cursor`. Guide with a two-minute keyless tutorial: `docs/guides/entity-recall.md`.++### The numbers that matter++| Measure | Before | Now |+|---|---|---|- | Cat 40 account briefs (family E), development world | TODO(cat40 round 1 / round 2) | TODO |- | Cat 40 held-out world, paired gain vs v0.60.44.0 | n/a | TODO(cat40 A3) |- | Links from documents to the account they name (dev brain, 3,973 pages) | 0 | TODO(cat40 slot build) |++| Account briefs (family E), held-out world, vs v0.60.44.0 (5 models × 2 repeats × 50 tasks) | baseline | +7.0 pts [+1.0, +12.0] |++| All tasks, held-out world, vs v0.60.44.0 | baseline | +0.4 pts [−2.0, +2.4] |++| Cost per task, held-out world | $0.323 | $0.238 (−26%) |++| Account briefs (family E), development world | 44/50 | 46/50 |++| All tasks, development world | 239/250 at $0.341/task | 239/250 at $0.240/task (−30%) |++| Private finance-only text leaked into answers, held-out world | 0 | 0 |++| Links from documents to the account they name (dev brain, 3,973 pages) | 0 | 4,124 |+| First full mention pass, 52,000-document world, PGLite, no embeddings | n/a | 7-16 s (52,956 links; 0.2 s when nothing changed) |+| `entity` p99 with references, 20K pages, a 10,000-link hub | n/a | 61-71 ms (budget 100 ms) |+| Keyless tutorial on a fresh install | n/a | 8 s |- | Tool list the model receives (starter surface) | 24,100 chars | 24,324 chars (cap 25,000) |++| Tool list the model receives (starter surface) | 24,174 chars | 24,363 chars (cap 25,000) |++++The links and the card alone scored 236/250 overall and 43/50 on briefs in development; the instruction to start a brief with `entity` brings that to 239/250 and 46/50 at the lower cost. Against an agent reading the same documents as plain files, the held-out score is a tie at the ceiling (95.6% vs 95.6%, difference 0.0 [−3.2, +3.0]). Files cost about half as much per task ($0.11 vs $0.24), but the file agent read finance-only private text into its context 100 times, and gbrain did so 0 times.++### Things to watch++- `extract --stale` reads every page once after the upgrade. `gbrain post-upgrade` prints the command and an estimate while pages are due; autopilot does the same work over several cycles if you skip it.+- A one-word code links only as written: `ACMX` links, `acmx` in prose does not. Names under 4 characters, generic words, a first word shared by two accounts, and names inside private facts or takes fences never link.+- `entity("Acme Example")` stays the company page when a `CRM record: Acme Example` page also exists: an exact title always wins over a derived name.+- `get_backlinks` without the new parameters returns the same link list as before.+- Off switch: `gbrain config set mentions.auto_link false` removes mention links and derived names on the next sweep (typed links from `extract --ner` stay).+- ## To take advantage of v0.61.1.0++## To take advantage of v0.60.57.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.61.1.0.md` the next time you interact with it.** It runs the first mention pass (`gbrain extract --stale --catch-up`, free) or leaves it to autopilot.++2. **Your agent reads `skills/migrations/v0.60.57.0.md` the next time you interact with it.** It runs the first mention pass (`gbrain extract --stale --catch-up`, free) or leaves it to autopilot.+3. **Verify the outcome:**+ ```bash+ gbrain extract --stale --dry-run --json # mention_due_pages: 0+ gbrain entity "<an account or person in your brain>"+ ```+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++- **Linkable types follow the schema pack** (`src/core/mentions/policy.ts`): person, company, organization and entity, plus every type the source's pack marks `primitive: entity` and its type aliases (`product` excluded), adjusted by `mentions.entity_types` (`+type`, `-type`). The entity card's exact-title preference uses the same set.+- **`gbrain-base-v2` 1.3.0** adds the `account` page type (alias `crm`, `accounts/` and `crm/` folders, not routed to expert lookup).+- **Derived names** (`src/core/mentions/aliases.ts`): an entity page's title subject and the codes it declares (`account code`, `also known as`, `aka`, `short name`, `ticker`, `code name`) are stored in `page_aliases` with `origin` `subject` or `declared`, read from text with private fences stripped. A one-word declared code is case-sensitive. Import, `gbrain reindex --aliases` and the stale sweep write the same rows; on managed brains through the coordinated writer. Frontmatter aliases are never touched by them.+- **Precedence everywhere aliases are read**: frontmatter > declared > subject within a source, and a derived alias never answers for another page's exact title (`readAliases`, used by `resolveEntitySlug`, the retrieval reflex, the search alias hop, intent weights and `search-diagnose`).+- **The mention pass** (`src/core/mentions/pass.ts`) runs after link work in `gbrain extract --stale`, autopilot's stale drain and the managed stale path (sync's inline extraction stays link-only). It has its own per-page state and extractor version, so it never reruns link or timeline extraction. A changed name rescans only pages that link to the old target or match the new name; an edit or a name change during a scan leaves the page due instead of publishing a stale result; a failed index build writes nothing and records `failed`; only plain mention links are reconciled (`typed_ner` links stay). Page titles are scanned too; frontmatter `mention_ignore` and `mentions.ignore` skip names. A budgeted cycle gives the mention pass half its time while pages are due.+- **Gazetteer guards** (`src/core/by-mention.ts`): an alias claimed by two pages is dropped, a same-source title wins over an alias, a one-word alias equal to the first word of another multi-word entity name is dropped, and the generic-word list applies to every one-word alias (titles keep the person-only rule).+- **`entity` card**: `referenced_by_count`, `referenced_by` (groups by pack-canonical type, newest first by `COALESCE(effective_date, updated_at)`, 10 rows per group, 50 per card, 160-character previews, `next` continuation) and `coverage` (`complete`, `pending`, `disabled`, `type_not_linkable`, `failed`); misses carry `coverage` too. Remote callers never see or count private or derived-private referrers. `context_pack` and `delta` do not compute them.+- **`get_backlinks`** (`src/core/ops/backlinks-paged.ts`): `type`, `limit` (max 500), and `group: "page"` returning `{rows, total, truncated, cursor, coverage}` with a keyset cursor; an unknown `type` or out-of-range `limit` is an error naming the valid values. No new parameters, no change.+- **`gbrain extract mentions --explain <name|slug> [--page <slug>]`** reports the matched name and origin, or one of 11 reason codes.+- **Notices and doctor**: a non-complete coverage adds a `[gbrain notice mention_index]` block; `links_extraction_lag` reports mention-due pages; `gbrain post-upgrade` prints an `[AGENT]` catch-up line; `extract --stale --dry-run` reports `mention_due_pages` and `mention_last_pass_at`.- - **Schema**: migration v201 adds `page_aliases.origin`, `case_sensitive` and `alias_text` (unique key widened to include `origin`) and the `page_mention_state`, `mention_gazetteer_entries` and `mention_index_status` tables. No existing row is rewritten.++- **Schema**: migration v202 adds `page_aliases.origin`, `case_sensitive` and `alias_text` (unique key widened to include `origin`) and the `page_mention_state`, `mention_gazetteer_entries` and `mention_index_status` tables. No existing row is rewritten.+- **Config**: `mentions.auto_link` (default on), `mentions.entity_types`, `mentions.ignore`.+- **Faster private-page filtering for remote callers** (`src/core/search/private-visibility.ts`): the declared-lineage check runs only for pages that carry `derived_from`, so remote reads no longer probe the source's private pages once per candidate row. Results are unchanged.+- **Server instructions**: wherever `entity` is served, the initialize instructions say: for a brief on an account, person or company, call `entity`, then walk `referenced_by` (or `get_backlinks`, where served) by type. The sentence replaces "several names" guidance on those surfaces; the full contract is 4,607 characters (ceiling 4,628).+- **Tool descriptions**: `entity` and `get_backlinks` describe the new fields within the unchanged schema ceilings; `query` and `search` descriptions are shorter to pay for it.++### For contributors++- Tests: `test/mentions-*.test.ts`, `test/e2e/mentions-parity.test.ts` (PGLite and Postgres produce the same rows), and a 10,000-link hub gate in `test/entity-card-perf.slow.test.ts`.- - Catalog, upgrade-replay and doctor goldens regenerated for migration v201 and the pack version.++- Catalog, upgrade-replay and doctor goldens regenerated for migration v202 and the pack version.+++ ## [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-04diff --cc VERSIONindex 87d753fa4e,081b46bce2..02146a61c9--- a/VERSION+++ b/VERSION@@@ -1,1 -1,1 +1,1 @@@- 0.61.1.0-0.60.52.0++0.60.57.0diff --cc docs/architecture/KEY_FILES.mdindex 212a402e29,9f47ae86b9..5d5f172220--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@@ -58,7 -59,6 +59,7 @@@ boundary and add its link here rather t| [Files And Sync (1/2)](key-files/files-and-sync-1.md) | `src/core/audit-week-file.ts` through `src/core/sync-git.ts:resolveSlugByPathOrSourcePath` || [Files And Sync (2/2)](key-files/files-and-sync-2.md) | `src/core/sync-policy.ts` through `src/core/write-through.ts` || [Graph And Facts](key-files/graph-and-facts.md) | `src/core/check-resolvable.ts` through `src/core/trajectory-format.ts` |- | [Entity recall](key-files/entity-recall.md) | `src/core/mentions/*`, `src/core/ops/backlinks-paged.ts`, `extract mentions --explain`, migration v201 |++| [Entity recall](key-files/entity-recall.md) | `src/core/mentions/*`, `src/core/ops/backlinks-paged.ts`, `extract mentions --explain`, migration v202 || [Mcp](key-files/mcp.md) | `src/mcp/dispatch.ts` through `src/mcp/validate-params.ts` || [Providers](key-files/providers.md) | `src/core/anthropic-pricing.ts` through `src/core/transcription.ts` || [Runtime](key-files/runtime.md) | `src/core/abort-check.ts` through `src/core/zombie-reap.ts` |diff --cc docs/architecture/key-files/entity-recall.mdindex b3ddcbc15b,0000000000..5f24e12b6fmode 100644,000000..100644--- a/docs/architecture/key-files/entity-recall.md+++ b/docs/architecture/key-files/entity-recall.md@@@ -1,19 -1,0 +1,19 @@@+# Key files — entity recall (mention index)++The mention index links every page that names an entity (by title, title+subject, frontmatter alias or declared code) to that entity page, keeps the+links current from `gbrain extract --stale`, and serves them on the `entity`+card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).++- `src/core/mentions/policy.ts` — the one linkable-type resolver. `linkableTypesFor(pack, policy)`: `person`, `company`, `organization`, `entity` (`ALWAYS_LINKABLE_TYPES`, never removable) plus every pack type with `primitive: entity` and its type aliases (`product` excluded), adjusted by `mentions.entity_types` (`+type`/`type` adds, `-type` removes). `readMentionPolicy` reads `auto_link`, `mentions.auto_link`, `mentions.entity_types`, `mentions.ignore` (JSON array or comma list, `parseNameList`). `canonicalTypeOf` / `typeAliasPairs` map a stored type through the pack's type aliases (`untyped` for none); pairs are bound as two `text[]`. `loadSourcePack(engine, sourceId, {strict})` returns null on a resolution failure unless strict. Tests: `test/mentions-policy-aliases.test.ts`.+- `src/core/mentions/aliases.ts` — derived names of an entity page. `titleSubject` (text after the last `: `), `declaredNames` (the `account code` / `also known as` / `a.k.a.` / `aka` / `short name` / `ticker` / `code name` parser shared with search's `aliasDeclarations`), `deriveEntityAliases` (subject `origin='subject'`, declarations `origin='declared'`, read from `publicBody`: private takes and facts fences stripped; a single-token declaration is `case_sensitive`). `aliasRejection`: under 4 characters, a generic word, or the first word of the page's own multi-word name. Rejections are returned for explain. Tests: `test/mentions-policy-aliases.test.ts`.+- `src/core/mentions/pass.ts` — `runMentionPass(engine, {sourceId?, deadline?, signal?, beforePublish?})`, run by `extractStaleFromDB` (unmanaged) and `extractManagedStaleLinks` (managed, unless `mentions: false`). Per source: policy off → `disableSource` deletes plain mention links (`link_kind` null or `plain`; `typed_ner` stays), derived alias rows, saved entries and page state once and records `disabled`; a changed policy fingerprint (types, cross-source flag, ignore list) marks every page due; `refreshAliases` rewrites derived rows of entity pages whose `page_mention_state.alias_revision`/`alias_version` differ (revision-checked, coordinated write when managed) and removes them from pages that stopped being entities; `buildGazetteer({strict: true})` failing writes nothing and records `failed`; `saveEntries` diffs `mention_gazetteer_entries` under `pg_advisory_xact_lock`, bumps the source generation and marks due only pages linking to a removed target plus pages a mini-gazetteer of added names matches (ASCII names prefiltered with `LIKE` on lower-cased text, others scanned in JS; a first save marks the source due); `reconcileSource` scans due pages (no state row, or `mention_revision`/`mention_version` differ) in batches of 200 and publishes only when the source generations (`FOR SHARE`) and each page's `knowledge_revision` (`FOR SHARE`) are unchanged, writing link diffs (`addLinksBatch`, audit site `extract.mentions`) and page state in one transaction; then the status row gets state, pending count and `last_pass_at`. `writeDerivedAliases` / `writePageAliases` are import's and `reindex --aliases`' alias projection. `MENTION_EXTRACTOR_VERSION` and `ALIAS_DERIVATION_VERSION` are independent of `LINK_EXTRACTOR_VERSION_TS`. The scanned text is title, compiled truth and timeline; frontmatter `mention_ignore` names are skipped per page. Tests: `test/mentions-pass.test.ts`, `test/mentions-managed.test.ts`, `test/e2e/mentions-parity.test.ts`.+- `src/core/mentions/stale.ts` — the pass as a sweep phase: `previewMentionPass` (due pages and newest `last_pass_at`, for `--dry-run`, doctor `links_extraction_lag` and post-upgrade), `linkPhaseDeadline` (a budgeted sweep gives link work half its budget while mention-due pages exist), `formatMentionSummary`, `mentionJsonFields`.+- `src/core/mentions/coverage.ts` — `readMentionCoverage(engine, sourceIds)`: `{state, pending_pages, last_pass_at, degraded?}` from `mention_index_status` plus due pages written at or after the row's `counted_at` (states `complete`, `pending`, `disabled`, `failed`; the card adds `type_not_linkable`). `mentionCoverageNotice` builds the `mention_index` notice (kind `degraded`, a per-call code): the free catch-up sweep for pending/failed, the user's setting for disabled/type-not-linkable, each with a read-only verify.+- `src/core/mentions/referrers.ts` — the shared referrer query behind `referenced_by` and `get_backlinks {group:"page"}`: one row per referring page (every link source), semi-join over links to the target (plus identity co-members under `entity_identity.union`), canonical type via bound alias arrays, date `COALESCE(effective_date, updated_at)` with `date_source`, previews (160 characters after an optional `# ` heading, fences stripped, `redactFindings`). `readReferrerGroups`: per-type totals and a bounded top-10 per type, water-filled to 50 rows per card. `readReferrerPage`: keyset paging on `(date DESC, source_id, slug)` with an opaque cursor (microsecond UTC text). Untrusted scopes apply `privatePagesFilterFragment` to referrer and target and `privateLinkOriginFilterFragment` to the link, in rows and counts. Tests: `test/mentions-card-backlinks.test.ts`, `test/entity-card-perf.slow.test.ts` (10,000-link hub gate).+- `src/core/mentions/upgrade-notice.ts` — `gbrain post-upgrade` prints an `[AGENT]` block naming `gbrain extract --stale --catch-up` with a time estimate (`MENTION_PASS_PAGES_PER_SECOND`) while mention-due pages exist.+- `src/core/ops/backlinks-paged.ts` — `get_backlinks`' `type` / `group` / `limit` / `cursor`. With none, `ops/links.ts` returns the legacy `Link[]`. `group: "page"` → `{rows, total, truncated, cursor, coverage}` (target = the first source in scope holding the slug; referrers from the read scope). Array mode filters by referrer type and cuts at `limit` with a `listing_truncated` notice naming the paged call. `limit` outside 1..500, a foreign cursor, or an unknown type (not a pack type, alias, observed referrer type or `untyped`) is `invalid_params` naming the valid values.+- `src/commands/extract-mentions-explain.ts` — `gbrain extract mentions --explain <name|slug> [--page <slug>] [--source-id <id>] [--json]` (dispatched from `extract-explain.ts`): the matched entries with origin and case flag, or one reason code (`ambiguous_first_word`, `below_min_length`, `generic_token`, `alias_collision`, `case_mismatch`, `type_not_linkable`, `linking_disabled`, `pending`, `ignored_by_page`, `ignored_by_config`, `not_a_known_name`); only `pending` names a sweep. Tests: `test/mentions-explain.test.ts`.- - `src/core/schema-migrations/v201-entity-mention-index.ts` — additive: `page_aliases.origin` (`frontmatter` default, `declared`, `subject`), `case_sensitive`, `alias_text`, unique key `(source_id, alias_norm, slug, origin)`; tables `page_mention_state`, `mention_gazetteer_entries`, `mention_index_status` (RLS on when the role bypasses RLS). `GUARDED_TABLE_COLUMNS` lists the new `page_aliases` columns.++- `src/core/schema-migrations/v202-entity-mention-index.ts` — additive: `page_aliases.origin` (`frontmatter` default, `declared`, `subject`), `case_sensitive`, `alias_text`, unique key `(source_id, alias_norm, slug, origin)`; tables `page_mention_state`, `mention_gazetteer_entries`, `mention_index_status` (RLS on when the role bypasses RLS). `GUARDED_TABLE_COLUMNS` lists the new `page_aliases` columns.++Alias readers apply precedence frontmatter > declared > subject per source, and a derived alias never answers for another live page's exact title (`readAliases` in `src/core/search/read-enrichment.ts`, shared by both engines' `resolveAliases`), so `resolveEntitySlug`, the retrieval reflex, the alias hop, intent weights and `search-diagnose` rank an exact title first. `buildGazetteer` (`src/core/by-mention.ts`) applies the same precedence, drops an alias claimed by two pages at its best origin, yields to a same-source title, drops a single-word alias equal to the first word of another multi-word entity name, applies the generic-word list to every single-word name, and carries `caseTokens` for case-sensitive entries; `opts.dropped` records every dropped name with its reason.diff --cc openclaw.plugin.jsonindex 2be7980040,e01e5f1097..a7fcefa18b--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@@ -1,7 -1,7 +1,7 @@@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.61.1.0",- "version": "0.60.52.0",++ "version": "0.60.57.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --cc package.jsonindex 79f685d4ad,ccc4cbd1bc..a890a96c63--- a/package.json+++ b/package.json@@@ -212,7 -212,7 +212,7 @@@"bun": ">=1.4.0"},"license": "MIT",- "version": "0.61.1.0",- "version": "0.60.52.0",++ "version": "0.60.57.0","overrides": {"@ai-sdk/provider-utils": "4.0.56","@hono/node-server": "^2.0.5",diff --cc plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 639f94b670,1fd0f221cd..22b0fed58f--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@@ -1,6 -1,6 +1,6 @@@{"name": "gbrain-coding",- "version": "0.61.1.0",- "version": "0.60.52.0",++ "version": "0.60.57.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --cc plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex f5ccd95a5d,df2e4866b2..a49ead21a4--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@@ -1,6 -1,6 +1,6 @@@{"name": "gbrain-coding",- "version": "0.61.1.0",- "version": "0.60.52.0",++ "version": "0.60.57.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --cc plugin-variants/gbrain-coding/README.mdindex 55b377f223,7663aa2538..4df47db601--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@@ -1,4 -1,4 +1,4 @@@- <!-- gbrain-plugin-tree-stamp: 0.61.1.0 -->-<!-- gbrain-plugin-tree-stamp: 0.60.52.0 -->++<!-- gbrain-plugin-tree-stamp: 0.60.57.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --cc plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 69048d7d96,5698c8dcbf..a74cd69ab2--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@@ -1,6 -1,6 +1,6 @@@{"name": "gbrain-daily",- "version": "0.61.1.0",- "version": "0.60.52.0",++ "version": "0.60.57.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --cc plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 7ff77df272,a65b2b39eb..2439f33ac6--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@@ -1,6 -1,6 +1,6 @@@{"name": "gbrain-daily",- "version": "0.61.1.0",- "version": "0.60.52.0",++ "version": "0.60.57.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --cc plugin-variants/gbrain-daily/README.mdindex 094b7a9a8a,45310f7183..29722f1bb2--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@@ -1,4 -1,4 +1,4 @@@- <!-- gbrain-plugin-tree-stamp: 0.61.1.0 -->-<!-- gbrain-plugin-tree-stamp: 0.60.52.0 -->++<!-- gbrain-plugin-tree-stamp: 0.60.57.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --cc plugin/README.mdindex 736e438114,25dc09133e..66e5b64f5f--- a/plugin/README.md+++ b/plugin/README.md@@@ -1,4 -1,4 +1,4 @@@- <!-- gbrain-plugin-tree-stamp: 0.61.1.0 -->-<!-- gbrain-plugin-tree-stamp: 0.60.52.0 -->++<!-- gbrain-plugin-tree-stamp: 0.60.57.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --cc scripts/e2e-test-map.tsindex f9b77b0ae1,2f1ae8bb76..f1dae9529f--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@@ -23,10 -23,15 +23,18 @@@ const MIGRATION_WAVE_TESTS ="test/e2e/migration-wave-provider-outcomes.test.ts",];+ const GRADUATION_E2E_TESTS = [+ "test/e2e/graduation-cli.test.ts",+ "test/e2e/graduation-clients.test.ts",+ "test/e2e/graduation-crash.test.ts",+ "test/e2e/graduation-faults.test.ts",+ "test/e2e/graduation-legacy-copy.test.ts",+ ];+export const E2E_TEST_MAP: Record<string, string[]> = {+ // Entity mention index: pass, aliases, referrer query and coverage on Postgres.+ "src/core/mentions/**": ["test/e2e/mentions-parity.test.ts"],+ "src/core/ops/backlinks-paged.ts": ["test/e2e/mentions-parity.test.ts"],// #5984: the env-gated wire-level SQL trace for the managed-sync catch-up bench."src/core/sql-trace.ts": ["test/e2e/sql-trace-postgres.test.ts"],// Fix wave 8, Lane G: reindex auto-concurrency sizing (#5181).diff --cc scripts/module-size-limits.tsvindex ec3131c79f,a5363702a5..25ebdf9d2d--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@@ -3,18 -3,18 +3,18 @@@# 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 3201 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); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage-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 3209 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); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge: master v0.60.52.0 growth re-summed with the wave (3209 measured)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.tssrc/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/extract.ts 2541 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); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/)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/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 3297 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)+ 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/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@@@ -36,7 -36,7 +36,7 @@@ src/core/embedding-migration.ts 1569 rasrc/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 refreshsrc/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 readsrc/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 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.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 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge: both +2 rows compose (1842 measured)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 envsrc/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 optionsrc/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.57.0.mdindex 683f9d7930,0000000000..f2de0dc240mode 100644,000000..100644--- a/skills/migrations/v0.60.57.0.md+++ b/skills/migrations/v0.60.57.0.md@@@ -1,49 -1,0 +1,49 @@@- # Upgrade to v0.61.1.0: the brain links every page that names an entity++# Upgrade to v0.60.57.0: the brain links every page that names an entity++`gbrain extract --stale` now links every page that names a person, company or+account (by title, record-title subject, frontmatter alias or a declared code+such as `Account code: ACMX`) to that page. The `entity` card lists those pages+by type (`referenced_by`) with a `coverage` state, and `get_backlinks` pages+through them (`group: "page"`). `gbrain-base-v2` gains an `account` page type+(alias `crm`). Linking is free: no model calls.++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 adds columns to `page_aliases` and three small tables; no++ Migration v202 adds columns to `page_aliases` and three small tables; no+ existing row is rewritten. Restart every `gbrain serve`, autopilot and+ worker.++2. **Run the first mention pass.** `gbrain post-upgrade` prints an `[AGENT]`+ line with the page count and an estimate while pages are due. Run it now+ (free, resumable):+ ```bash+ gbrain extract --stale --catch-up+ ```+ Without it, autopilot cycles do the same work over several runs, and entity+ cards report `coverage.state: "pending"` until then.++3. **Verify.**+ ```bash+ gbrain extract --stale --dry-run --json # mention_due_pages: 0+ gbrain entity "<an account or person name>"+ ```++4. **Tell the user about the off switch only if they ask, or if a name links+ wrongly.** `gbrain extract mentions --explain <name> --page <slug>` says why+ a name links or not. A wrong link is fixed by `mentions.ignore` (a name) or+ frontmatter `mention_ignore` (one page); `gbrain config set+ mentions.auto_link false` turns linking off and removes mention links on the+ next sweep. These change the user's brain: ask before setting them.++5. **Know the behavior changes.**+ - `extract --stale` JSON adds `mention_*` fields; `stale_remaining` counts+ link-stale pages plus mention-due pages.+ - A derived alias (record-title subject or declared code) never answers for+ another page's exact title, so `entity("Acme Example")` stays the company+ page beside a `CRM record: Acme Example` page.+ - Search's alias hop also resolves declared codes.++Guide: `docs/guides/entity-recall.md`.diff --cc skills/skills.lock.jsonindex 34edd5f86b,a54625edd5..8c54f8107d--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@@ -164,8 -164,8 +164,9 @@@"migrations/v0.60.45.0.md": "ed92f7b642f1e84e6381ef9e7e855db1ac7d20abd9b79a7bb359c707a04b8b9d","migrations/v0.60.47.0.md": "91a6015e3b85c6f2c8048680ee5873895ae2b1948bad8ba6cebce679c3ec7085","migrations/v0.60.5.0.md": "0d3ee19359a2740de08ac9ec388ddc15e7c72d663afe33832e1e54170528acab",+ "migrations/v0.60.52.0.md": "ae49b2f51ba6288e4883d8bfda9f494f821e160e227164aa065a645d4e9ae87b",++ "migrations/v0.60.57.0.md": "d34f9a7daf2101962d320db4b79c797325cc86d4200c39b3aaea9fff57c46d69","migrations/v0.60.6.0.md": "1cbfca2c899e1348acbd61f0baa4c8e723b5283ff868c710c74e116c0cb6726e",- "migrations/v0.61.1.0.md": "e38f36739d1a704bb15cb2bcabfda420248d98dd78be42ad9f9102003554ffa7","migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a","migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a","migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a",diff --cc src/core/by-mention.tsindex 51042dbd49,558187c62b..36d04a6357--- a/src/core/by-mention.ts+++ b/src/core/by-mention.ts@@@ -78,13 -71,8 +78,15 @@@ export interface GazetteerEntrytitle: string;/** Lowercase title tokens in order. Length 1 = single-word entity. */tokens: string[];+ /** Absent on hand-built entries: a title. */+ origin?: GazetteerOrigin;+ /**+ * Set on case-sensitive entries (single-token declared aliases): the tokens+ * as written, NFC. A body token matches only when its original text equals.+ */+ caseTokens?: string[];+ /** Spelling being matched (the alias, not the display title, for aliases). */+ matchText?: string;}/**@@@ -105,33 -93,12 +107,34 @@@ export type Gazetteer = Map<string, Gazexport function hashGazetteer(gazetteer: Gazetteer): string {const entries: string[] = [];for (const bucket of gazetteer.values()) {- for (const e of bucket) entries.push(`${e.source_id}\0${e.slug}\0${e.title}\0${e.tokens.join(' ')}${e.caseTokens ? `\0${e.caseTokens.join(' ')}` : ''}`);- for (const e of bucket) entries.push(`${e.source_id}\0${e.slug}\0${e.title}\0${e.tokens.join(' ')}\0${e.matchText ?? ''}`);++ for (const e of bucket) entries.push(`${e.source_id}\0${e.slug}\0${e.title}\0${e.tokens.join(' ')}\0${e.matchText ?? ''}${e.caseTokens ? `\0${e.caseTokens.join(' ')}` : ''}`);}- return createHash('sha256').update(entries.sort().join('\n')).digest('hex').slice(0, 8);+ // Matching semantics are part of the resume identity, not just DB contents.+ return createHash('sha256').update('hangul-boundaries-v1\n').update(entries.sort().join('\n')).digest('hex').slice(0, 8);}+/** One row of the saved entry set the mention pass diffs (mention_gazetteer_entries). */+export interface GazetteerEntryKey {+ source_id: string;+ name_norm: string;+ target_slug: string;+ case_sensitive: boolean;+}++/** The gazetteer's entries as (source, normalized name, target, case flag), deduped and sorted. */+export function gazetteerEntryKeys(gazetteer: Gazetteer): GazetteerEntryKey[] {+ const out = new Map<string, GazetteerEntryKey>();+ for (const bucket of gazetteer.values()) {+ for (const e of bucket) {+ const name_norm = (e.caseTokens ?? e.tokens).join(' ');+ const key: GazetteerEntryKey = { source_id: e.source_id, name_norm, target_slug: e.slug, case_sensitive: !!e.caseTokens };+ out.set(`${key.source_id}\0${key.name_norm}\0${key.target_slug}\0${key.case_sensitive}`, key);+ }+ }+ return [...out.values()].sort((x, y) => x.source_id.localeCompare(y.source_id) || x.name_norm.localeCompare(y.name_norm)+ || x.target_slug.localeCompare(y.target_slug) || Number(x.case_sensitive) - Number(y.case_sensitive));+}+export interface Mention {/** Target page slug (the entity being mentioned). */slug: string;@@@ -527,51 -434,91 +531,51 @@@ export async function buildGazetteerconst tokens = tokenizeTitle(row.title);if (tokens.length === 0) continue;- if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1) continue;+ if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1) { drop({ ...base, reason: 'below_min_length' }); continue; }+ if (userIgnore.has(tokens.join(' '))) { drop({ ...base, reason: 'ignored' }); continue; }// #4222: a single-generic-token PERSON title ("Will", "Chief") is a// junk-hub magnet — every prose occurrence of the word would accrete- // another mention edge onto a near-empty page. Dropped from the- // gazetteer even though the page exists (unlike the CK12 ignore-list- // rule above, which trusts user-created pages: these titles are- // overwhelmingly extractor-minted, and the page itself stays intact —- // only the auto-link accretion stops). Multi-token titles ("Will- // Smith") and non-person types are unaffected.- if (tokens.length === 1 && row.type === 'person' && isGenericEntityToken(tokens[0]!)) continue;-- const entry: GazetteerEntry = {- slug: row.slug,- source_id: row.source_id ?? 'default',- title: row.title,- tokens,- matchText: row.title,- };- const key = tokens[0]!;- const bucket = gazetteer.get(key);- if (bucket) bucket.push(entry);- else gazetteer.set(key, [entry]);+ // another mention edge onto a near-empty page. Dropped from the gazetteer+ // even though the page exists (unlike the CK12 ignore-list rule above,+ // which trusts user-created pages: these titles are overwhelmingly+ // extractor-minted, and the page itself stays intact — only the+ // auto-link accretion stops). Multi-token titles ("Will Smith") and+ // non-person titles are unaffected; aliases of every type are checked+ // below.+ if (tokens.length === 1 && row.type === 'person' && isGenericEntityToken(tokens[0]!)) { drop({ ...base, reason: 'generic_token' }); continue; }+ noteFirstWord(src, tokens);- add({ slug: row.slug, source_id: src, title: row.title, tokens, origin: 'title' });++ add({ slug: row.slug, source_id: src, title: row.title, tokens, origin: 'title', matchText: row.title });}- // ── Alias entries (v0.46.15 identity wave, #3801) ────────────────────────- // page_aliases rows joined to LIVE entity-typed pages become additional+ // ── Alias entries ────────────────────────────────────────────────────────+ // page_aliases rows joined to LIVE linkable entity pages become additional// gazetteer entries, so a body mention of "saoirse" links to- // people/saoirse-x. Guards (stricter than titles — aliases are not- // user-created pages):+ // people/saoirse-x and "QUCO" links to the account that declares it.+ // Guards (stricter than titles — aliases are not user-created pages):+ // - one row per (source, alias, page) with origin precedence+ // frontmatter > declared > subject// - ignore-list applies CASE-INSENSITIVELY with NO existing-page escape// (aliases store normalized lowercase; DEFAULT_IGNORE_LIST is cased)- // - aliases mapping to >1 slug within a source are skipped (ambiguous)+ // - an alias claimed by >1 page at its best origin within a source is+ // dropped (ambiguous); a lower-precedence claim yields// - aliases colliding with any existing page TITLE in the SAME source// are skipped (the title entry wins; per-source scoping per R2-9)- // - MIN_NAME_LENGTH applies to the alias string+ // - MIN_NAME_LENGTH and the generic-token list apply to the alias string+ // - a single-token alias equal to the first word of a multi-word entity+ // name in the same source is dropped+ // - a case-sensitive row (a single-token declared alias) matches only+ // the original-case text+ let aliasRows: Array<{ alias_norm: string; slug: string; source_id: string | null; title: string | null; type: string | null;+ origin: string | null; case_sensitive: boolean | null; alias_text: string | null }> = [];try {- const aliasRows = await engine.executeRaw<{- alias_norm: string;- slug: string;- source_id: string | null;- title: string | null;- }>(- `SELECT pa.alias_norm, pa.slug, pa.source_id, p.title+ aliasRows = (await engine.executeRaw<typeof aliasRows[number]>(+ `SELECT pa.alias_norm, pa.slug, pa.source_id, p.title, p.type, pa.origin, pa.case_sensitive, pa.alias_textFROM page_aliases paJOIN pages p ON p.slug = pa.slug AND p.source_id = pa.source_id- WHERE p.type IN (${typeList})+ WHERE p.type = ANY($1::text[])AND p.deleted_at IS NULL`,- [],- );- const ignoreLc = new Set(Array.from(ignoreSet, (s) => s.toLowerCase()));- // Per-source title index for alias-vs-title collision checks.- const titleBySource = new Set<string>();- for (const r of rows) {- if (r.title) titleBySource.add(`${r.source_id ?? 'default'}- }- // Ambiguity: same (source, alias) → multiple slugs.- const bySourceAlias = new Map<string, Set<string>>();- for (const a of aliasRows) {- const k = `${a.source_id ?? 'default'}- const set = bySourceAlias.get(k) ?? new Set<string>();- set.add(a.slug);- bySourceAlias.set(k, set);- }- const seenAliasEntry = new Set<string>();- for (const a of aliasRows) {- const alias = a.alias_norm?.trim();- if (!alias || !a.title) continue;- const src = a.source_id ?? 'default';- if (alias.length < MIN_NAME_LENGTH && !hasCJK(alias)) continue;- if (hasCJK(alias) && cjkCharCount(alias) < MIN_CJK_NAME_LENGTH) continue;- if (ignoreLc.has(alias.toLowerCase())) continue;- if ((bySourceAlias.get(`${src}- if (titleBySource.has(`${src}- const dedupeKey = `${src}- if (seenAliasEntry.has(dedupeKey)) continue;- seenAliasEntry.add(dedupeKey);- const tokens = tokenizeTitle(alias);- if (tokens.length === 0) continue;- if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1) continue;- const entry: GazetteerEntry = { slug: a.slug, source_id: src, title: a.title, tokens, matchText: alias };- const key = tokens[0]!;- const bucket = gazetteer.get(key);- if (bucket) bucket.push(entry);- else gazetteer.set(key, [entry]);- }+ [allTypes],+ )).filter(r => linkable(r.source_id, r.type));} catch (err) {// pre-v110 brains: no page_aliases table — titles-only gazetteer.// Any OTHER failure (connection blip, permission) warns once per process@@@ -585,61 -529,6 +589,61 @@@console.error(`[gbrain] gazetteer alias load degraded (titles-only): ${err instanceof Error ? err.message : String(err)}`);}}+ const ignoreLc = new Set(Array.from(ignoreSet, (n) => n.toLowerCase()));+ // Per-source title index for alias-vs-title collision checks.+ const titleBySource = new Set<string>();+ for (const r of rows) {+ if (r.title) titleBySource.add(`${r.source_id ?? 'default'} ${r.title.toLowerCase()}`);+ }+ const rank = (origin: string | null) => origin === 'subject' ? 2 : origin === 'declared' ? 1 : 0;+ // Best (lowest) origin rank per (source, alias, slug), then per (source, alias).+ const bestPerPage = new Map<string, typeof aliasRows[number]>();+ for (const a of aliasRows) {+ const k = `${a.source_id ?? 'default'} ${a.alias_norm} ${a.slug}`;+ const prev = bestPerPage.get(k);+ if (!prev || rank(a.origin) < rank(prev.origin)) bestPerPage.set(k, a);+ }+ const claims = new Map<string, { rank: number; slugs: Set<string> }>();+ for (const a of bestPerPage.values()) {+ const k = `${a.source_id ?? 'default'} ${a.alias_norm}`;+ const r = rank(a.origin);+ const c = claims.get(k);+ if (!c || r < c.rank) claims.set(k, { rank: r, slugs: new Set([a.slug]) });+ else if (r === c.rank) c.slugs.add(a.slug);+ }+ const aliasEntries: Array<{ entry: GazetteerEntry; base: Omit<DroppedName, 'reason'> }> = [];+ for (const a of bestPerPage.values()) {+ const alias = a.alias_norm?.trim();+ if (!alias || !a.title) continue;+ const src = a.source_id ?? 'default';+ const origin = (a.origin ?? 'frontmatter') as GazetteerOrigin;+ const written = a.case_sensitive && a.alias_text ? a.alias_text : alias;+ const base = { source_id: src, slug: a.slug, name: written, origin };+ const claim = claims.get(`${src} ${alias}`)!;+ if (rank(a.origin) > claim.rank) continue;+ if (claim.slugs.size > 1) { drop({ ...base, reason: 'alias_collision' }); continue; }+ if (alias.length < MIN_NAME_LENGTH && !hasCJK(alias)) { drop({ ...base, reason: 'below_min_length' }); continue; }+ if (hasCJK(alias) && cjkCharCount(alias) < MIN_CJK_NAME_LENGTH) { drop({ ...base, reason: 'below_min_length' }); continue; }+ if (ignoreLc.has(alias.toLowerCase())) { drop({ ...base, reason: 'ignored' }); continue; }+ if (titleBySource.has(`${src} ${alias.toLowerCase()}`)) { drop({ ...base, reason: 'title_wins' }); continue; }+ const tokens = tokenizeTitle(alias);+ if (tokens.length === 0) continue;+ if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1) { drop({ ...base, reason: 'below_min_length' }); continue; }+ if (userIgnore.has(tokens.join(' '))) { drop({ ...base, reason: 'ignored' }); continue; }+ if (tokens.length === 1 && isGenericEntityToken(tokens[0]!)) { drop({ ...base, reason: 'generic_token' }); continue; }+ const caseTokens = a.case_sensitive && a.alias_text ? caseTokensOf(a.alias_text) : undefined;- const entry: GazetteerEntry = { slug: a.slug, source_id: src, title: a.title, tokens, origin,++ const entry: GazetteerEntry = { slug: a.slug, source_id: src, title: a.title, tokens, origin, matchText: alias,+ ...(caseTokens && caseTokens.length === tokens.length ? { caseTokens } : {}) };+ noteFirstWord(src, tokens);+ aliasEntries.push({ entry, base });+ }+ for (const { entry, base } of aliasEntries) {+ if (entry.tokens.length === 1 && firstWords.get(entry.source_id)?.has(entry.tokens[0]!)) {+ drop({ ...base, reason: 'ambiguous_first_word' });+ continue;+ }+ add(entry);+ }// Sort each bucket by token-count DESC so maximal-munch walks longest-first;// ties break on (source_id, slug) so the pick among same-name entries is@@@ -722,7 -617,8 +743,9 @@@ export function findMentionedEntitieslet matched: GazetteerEntry | null = null;let matchedTokens = 0;for (const entry of bucket) {+ if (i + entry.tokens.length > tokens.length) continue;+ if (!hasHangulMatchBoundary(stripped, tokens, i, entry)) continue;+ if (!caseMatches(entry, i)) continue;if (entry.tokens.length === 1) {matched = entry;matchedTokens = 1;@@@ -758,7 -654,7 +781,8 @@@e => e.source_id === opts.fromSourceId&& e.tokens.length === want.length&& e.tokens.every((t, k) => t === want[k])- && caseMatches(e, i),++ && caseMatches(e, i)+ && hasHangulMatchBoundary(stripped, tokens, i, e),);if (own) matched = own;}diff --cc src/core/cli-flag-registry.generated.tsindex 99c784c586,7ddecc3473..c9ce2b54c5--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@@ -76,9 -76,9 +76,9 @@@ export const CLI_FLAG_REGISTRY: Record<'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', '--page', '--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', '--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'],++ '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', '--page', '--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'],- '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', '--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'],@@@ -120,9 -120,9 +120,9 @@@'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'],'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', '--page', '--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', '--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', '--page', '--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'],'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/persistence/graduation-inventory.tsindex 0000000000,7b25e6b470..c6f202b2f7mode 000000,100644..100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@@ -1,0 -1,277 +1,280 @@@+ /**+ * Engine graduation state inventory: every relation of the public schema on+ * either engine maps to exactly one class (deny by default). The relation set,+ * the copy order and the FK closure are read from the live catalog, never+ * hand-maintained; test/graduation-inventory.test.ts fails when a migration+ * adds a relation without a row here.+ */+ import type { BrainEngine } from '../engine.ts';+ import { opError } from '../ops/contract.ts';+ import { LATEST_VERSION } from '../migrate.ts';+ import type { ColumnTransform, Inventory, InventoryClass, InventoryEntry, LossKind } from './engine-graduation.types.ts';++ type EngineKind = 'pglite' | 'postgres';++ const BOTH = { pglite: true, postgres: true } as const;++ function entry(relation: string, cls: InventoryClass, lossKind: LossKind, reason: string,+ extra: { kind?: 'table' | 'view'; engines?: { pglite: boolean; postgres: boolean }; transforms?: ColumnTransform[]; rowFilter?: string } = {}): InventoryEntry {+ return {+ relation, kind: extra.kind ?? 'table', class: cls, engines: extra.engines ?? BOTH, lossKind,+ transforms: extra.transforms ?? [], ...(extra.rowFilter ? { rowFilter: extra.rowFilter } : {}), reason,+ };+ }+ const carry = (relation: string, lossKind: LossKind, reason: string, extra?: Parameters<typeof entry>[4]) => entry(relation, 'carry', lossKind, reason, extra);++ const ACTIVE_JOB = "status = 'active'";+ const ORPHAN_EFFECT = "state IN ('queued','running','failed')";++ export const GRADUATION_INVENTORY: Inventory = {+ version: 1,+ entries: [+ carry('access_tokens', 'security', 'Legacy bearer tokens and their unified grant columns; token hashes keep authorizing on the target.'),+ carry('budget_ledger', 'operational', 'Daily resolver spend totals; admission keeps counting today\'s spend.'),+ carry('calibration_profiles', 'user_data', 'Published calibration profiles per holder.'),+ carry('chat_usage_log', 'operational', 'Chat model usage and cost log.'),+ carry('chronicle_judge_reservations', 'operational', 'Rolling 24-hour paid judge-call counter; dropping it would reopen the daily cap.'),+ carry('chronicle_page_state', 'user_data', 'Chronicle extraction ledger: paid work already done per page revision.'),+ carry('code_edges_chunk', 'user_data', 'Code graph edges between chunks (keyed by chunk id, which carries).'),+ carry('code_edges_symbol', 'user_data', 'Code graph edges to unresolved symbols.'),+ carry('config', 'user_data', 'Brain settings, including the embedding column registry; the engine name and schema version stay each engine\'s own.',+ { rowFilter: "key NOT IN ('engine','version','graduation.deferred_indexes')" }),+ carry('content_chunks', 'user_data', 'Chunks with embeddings (paid work), vectors carried as text at the source typmod.'),+ carry('context_volunteer_events', 'operational', 'Push-context telemetry.'),+ carry('conversation_parser_llm_cache', 'operational', 'Paid LLM parse cache; rebuilding spends money.'),+ carry('decide_calibrations', 'user_data', 'System One slot qualifications (paid calibration results).'),+ carry('decide_proposals', 'user_data', 'Supersession proposals and the user\'s decisions on them.'),+ carry('decide_spend', 'operational', 'System One spend log.'),+ carry('decide_state', 'operational', 'System One sweep cursors and slot state.'),+ carry('decide_sweep_deferred', 'operational', 'Deferred System One sweep work with its schedule.'),+ carry('decision_receipts', 'user_data', 'Durable System One decision receipts.'),+ carry('dream_synthesis_completions', 'user_data', 'Dream synthesis idempotency ledger.'),+ carry('dream_verdicts', 'operational', 'Paid dream triage verdict cache.'),+ carry('drift_decisions', 'user_data', 'Take drift decisions and when they were applied.'),+ carry('entity_identities', 'user_data', 'Established entity identities.'),+ carry('eval_candidates', 'operational', 'Captured retrieval eval candidates.'),+ carry('eval_capture_failures', 'operational', 'Eval capture failure log.'),+ carry('eval_contradictions_cache', 'operational', 'Paid contradiction judge cache; rebuilding spends money.'),+ carry('eval_contradictions_runs', 'operational', 'Contradiction eval run history.'),+ carry('eval_takes_quality_runs', 'operational', 'Takes quality eval run history.'),+ carry('extract_atoms_page_state', 'user_data', 'Atom extraction ledger per page.'),+ carry('extract_atoms_transcript_state', 'user_data', 'Atom extraction ledger per transcript file.'),+ carry('extract_rollup_7d', 'operational', 'Seven-day extraction rollup counters.'),+ carry('fact_relink_attempts', 'operational', 'Fact relink attempt log.'),+ carry('fact_withdrawals', 'user_data', 'Fact withdrawal ledger (forget); must never be lost.'),+ carry('facts', 'user_data', 'Facts with attribution columns and the superseded_by self-FK.'),+ carry('files', 'user_data', 'File metadata; object bytes stay in the storage backend.'),+ carry('ingest_log', 'operational', 'Ingestion log.'),+ carry('links', 'user_data', 'Page graph links.'),+ carry('loop_suppressions', 'user_data', 'Open-loop mutes the user chose.'),+ carry('mcp_request_log', 'operational', 'MCP request log.'),+ carry('mcp_spend_log', 'operational', 'MCP spend log.'),+ carry('mcp_spend_reservations', 'operational', 'Pending and unresolved MCP charges; admission counts them and late settlement needs them.'),++ carry('mention_gazetteer_entries', 'operational', 'Entity mention index: the linkable names the last mention pass used per source; a name change rescans only affected pages.'),++ carry('mention_index_status', 'operational', 'Entity mention index: per-source pass state, generation and coverage the entity card reports.'),+ carry('migration_impact_log', 'operational', 'Remediation impact log.'),+ carry('minion_attachments', 'operational', 'Job attachments.'),+ carry('minion_budget_log', 'operational', 'Job budget events.'),+ carry('minion_inbox', 'operational', 'Job inbox messages.'),+ carry('minion_jobs', 'operational', 'Job queue; orphaned leases reset under the kernel lock so the target worker runs each job once.', {+ transforms: [+ { column: 'status', rule: "active -> waiting", expression: `CASE WHEN ${ACTIVE_JOB} THEN 'waiting' ELSE status END` },+ { column: 'lock_token', rule: 'cleared on active jobs', expression: `CASE WHEN ${ACTIVE_JOB} THEN NULL ELSE lock_token END` },+ { column: 'lock_until', rule: 'cleared on active jobs', expression: `CASE WHEN ${ACTIVE_JOB} THEN NULL ELSE lock_until END` },+ { column: 'timeout_at', rule: 'cleared on active jobs', expression: `CASE WHEN ${ACTIVE_JOB} THEN NULL ELSE timeout_at END` },+ { column: 'started_at', rule: 'cleared on active jobs', expression: `CASE WHEN ${ACTIVE_JOB} THEN NULL ELSE started_at END` },+ ],+ }),+ carry('minion_lease_pressure_log', 'operational', 'Lease pressure log.'),+ carry('minion_self_fix_log', 'operational', 'Self-fix log.'),+ carry('oauth_clients', 'security', 'OAuth clients and their grants; client secrets stay valid.'),+ carry('oauth_grant_audit', 'security', 'OAuth grant change audit trail.'),+ carry('oauth_tokens', 'security', 'Issued OAuth access and refresh token hashes.'),+ carry('op_checkpoint_paths', 'operational', 'Resumable operation checkpoints.'),+ carry('op_checkpoints', 'operational', 'Resumable operation checkpoints.'),+ carry('open_loops', 'user_data', 'Open loops and their status.'),+ carry('page_aliases', 'user_data', 'Page aliases.'),+ carry('page_generation_clock', 'operational', 'Page generation clock (derived side table, verified equal).'),++ carry('page_mention_state', 'operational', 'Entity mention index: per-page mention watermark; without it every page is due for a rescan.'),+ carry('page_projection_jobs', 'operational', 'Pending page projection work (derived side table, verified equal).'),+ carry('page_versions', 'user_data', 'Page revision history with attribution.'),+ carry('page_write_guards', 'user_data', 'Page write guards per source incarnation and slug.'),+ carry('pages', 'user_data', 'Pages with ids, knowledge_revision, revision attribution and timestamps.'),+ carry('persistence_counters', 'operational', 'Request admission counters; carried and recomputable from the carried requests.'),+ carry('persistence_effects', 'operational', 'Postcommit outbox; orphaned claims reset so the target worker can claim them, delayed effects keep next_attempt_at.', {+ transforms: [+ { column: 'state', rule: 'running -> queued', expression: "CASE WHEN state = 'running' THEN 'queued' ELSE state END" },+ { column: 'execution_token', rule: 'cleared on queued, running and failed effects', expression: `CASE WHEN ${ORPHAN_EFFECT} THEN NULL ELSE execution_token END` },+ { column: 'claim_expires_at', rule: 'cleared on queued, running and failed effects', expression: `CASE WHEN ${ORPHAN_EFFECT} THEN NULL ELSE claim_expires_at END` },+ ],+ }),+ carry('persistence_local_writers', 'security', 'Local writer credentials (cli/stdio) and revocations.'),+ carry('persistence_requests', 'user_data', 'Write requests: idempotency records and outcomes, so replays return the stored outcome.'),+ carry('persistence_source_bindings', 'user_data', 'Source to worktree bindings.'),+ carry('persistence_topology_changes', 'user_data', 'Topology change journal.'),+ carry('persistence_worktree_refreshes', 'user_data', 'Worktree refresh journal.'),+ carry('persistence_worktrees', 'user_data', 'Managed worktrees; heartbeats reset.', {+ transforms: [{ column: 'heartbeat_at', rule: 'cleared', expression: 'NULL' }],+ }),+ carry('persistence_writer_protocols', 'operational', 'Writer protocol registrations per worktree owner.'),+ carry('raw_data', 'user_data', 'Raw source payloads per page.'),+ carry('search_telemetry', 'operational', 'Search telemetry rollups.'),+ carry('session_context_state', 'operational', 'Ambient recall session state.'),+ carry('shared_skill_delivery_batches', 'operational', 'Shared-skill delivery batches and acknowledgments.'),+ carry('shared_skill_heads', 'user_data', 'Shared-skill heads.'),+ carry('shared_skill_members', 'user_data', 'Shared-skill installations.'),+ carry('shared_skill_packs', 'user_data', 'Shared-skill packs.'),+ carry('shared_skill_policies', 'user_data', 'Shared-skill policies.'),+ carry('shared_skill_policy_audit', 'user_data', 'Shared-skill policy audit trail.'),+ carry('shared_skill_revision_leases', 'user_data', 'User pins and delivery retention promises with their expiries (not process leases).'),+ carry('shared_skill_revisions', 'user_data', 'Shared-skill revisions; stored_bytes is generated and never inserted.'),+ carry('shared_skill_state', 'security', 'Shared-skill serving epoch and delivery token secret.'),+ carry('slug_aliases', 'user_data', 'Slug aliases.'),+ carry('source_ingestion_receipts', 'user_data', 'Source ingestion receipts.'),+ carry('sources', 'user_data', 'Sources with incarnations and archive state.'),+ carry('subagent_messages', 'operational', 'Subagent job transcripts.'),+ carry('subagent_tool_executions', 'operational', 'Subagent tool execution log.'),+ carry('synthesis_evidence', 'user_data', 'Synthesis citations.'),+ carry('tags', 'user_data', 'Page tags.'),+ carry('take_domain_assignments', 'user_data', 'Take domain assignments.'),+ carry('take_grade_cache', 'operational', 'Paid take grading cache; rebuilding spends money.'),+ carry('take_nudge_log', 'operational', 'Take nudge log.'),+ carry('take_proposals', 'user_data', 'Take proposals and their status.'),+ carry('takes', 'user_data', 'Takes with attribution and supersession.'),+ carry('think_ab_results', 'operational', 'Think A/B eval results.'),+ carry('timeline_entries', 'user_data', 'Timeline entries with attribution.'),++ entry('persistence_brain', 'rebind', 'user_data', 'Brain identity and flags carry (brain_id keeps every identity file valid); enabled is set on the target only at cutover.', {+ transforms: [{ column: 'enabled', rule: 'false until cutover', expression: 'false' }],+ }),+ entry('persistence_host_bindings', 'rebind', 'user_data', 'Host bindings carry only when host_id is this host and local_path passes the physical-root check.'),++ entry('query_cache', 'rebuild', 'operational', 'Query result cache; regenerated on the target.'),+ entry('code_traversal_cache', 'rebuild', 'operational', 'Code traversal cache; regenerated on the target.'),++ entry('planner_stats_deltas', 'discard', 'operational', 'PGLite-only planner accounting.', { engines: { pglite: true, postgres: false } }),+ entry('planner_stats_state', 'discard', 'operational', 'PGLite-only planner accounting.', { engines: { pglite: true, postgres: false } }),+ entry('gbrain_cycle_locks', 'discard', 'operational', 'TTL run locks; every row is an orphan under the kernel lock.'),+ entry('budget_reservations', 'discard', 'operational', 'No runtime reader or writer; only migrations reference it.'),+ entry('subagent_rate_leases', 'discard', 'operational', 'Job-owned concurrency leases that expire.'),+ entry('oauth_codes', 'discard', 'security', 'One-time authorization codes; an in-flight OAuth handshake restarts.'),++ entry('page_links', 'schema_owned', 'operational', 'View over links; each engine\'s schema defines it.', { kind: 'view' }),+ entry('file_migration_ledger', 'schema_owned', 'operational', 'Postgres-only file storage migration ledger written by the target initSchema.', { engines: { pglite: false, postgres: true } }),+ entry('persistence_graduation', 'schema_owned', 'operational', 'Each engine\'s own graduation custody row (source: quiesced/cutover; target: copying..authoritative); never copied, digested or compared.'),+ ],+ };++ export function expectedRelations(engine: EngineKind, inv: Inventory = GRADUATION_INVENTORY): readonly string[] {+ return inv.entries.filter(e => e.engines[engine]).map(e => e.relation).sort();+ }++ /** Tables, partitioned tables, views, materialized views and foreign tables in the current schema. */+ export async function listRelations(engine: BrainEngine): Promise<readonly { relation: string; kind: 'table' | 'view' }[]> {+ const rows = await engine.executeRaw<{ relname: string; relkind: string }>(`SELECT c.relname, c.relkind::text AS relkind FROM pg_class c+ JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() AND c.relkind IN ('r','p','v','m','f') AND NOT c.relispartition+ ORDER BY c.relname COLLATE "C"`);+ return rows.map(r => ({ relation: r.relname, kind: r.relkind === 'v' || r.relkind === 'm' ? 'view' : 'table' }));+ }++ async function schemaVersion(engine: BrainEngine): Promise<number | null> {+ try {+ const [row] = await engine.executeRaw<{ value: string }>("SELECT value FROM config WHERE key='version'");+ return row ? Number(row.value) : null;+ } catch { return null; }+ }++ /** Throws graduation_unclassified_table when the live relation set differs from the inventory for this engine. */+ export async function assertRelationSet(engine: BrainEngine, kind: EngineKind, inv: Inventory = GRADUATION_INVENTORY): Promise<void> {+ const live = await listRelations(engine);+ const expected = new Map(inv.entries.filter(e => e.engines[kind]).map(e => [e.relation, e]));+ const liveNames = new Set(live.map(r => r.relation));+ const unclassified = live.filter(r => !expected.has(r.relation)).map(r => r.relation);+ const missing = [...expected.keys()].filter(name => !liveNames.has(name)).sort();+ const wrongKind = live.filter(r => expected.has(r.relation) && expected.get(r.relation)!.kind !== r.kind).map(r => r.relation);+ if (!unclassified.length && !missing.length && !wrongKind.length) return;+ const version = await schemaVersion(engine);+ const newer = version !== null && version > LATEST_VERSION;+ const parts = [+ unclassified.length ? `unclassified: ${unclassified.join(', ')}` : '',+ missing.length ? `missing: ${missing.join(', ')}` : '',+ wrongKind.length ? `wrong kind: ${wrongKind.join(', ')}` : '',+ ].filter(Boolean).join('; ');+ const verify = { argv: ['gbrain', 'migrate', '--to', 'postgres', '--plan', '--url-env', 'GBRAIN_TARGET_URL', '--json'] };+ throw opError('graduation_unclassified_table',+ `The ${kind} schema does not match this gbrain's graduation inventory (${parts}).`,+ newer+ ? `The ${kind} brain is at schema v${version}, newer than this gbrain (v${LATEST_VERSION}). Ask the user to upgrade gbrain on this machine (gbrain upgrade), then plan the move again. --force never bypasses this.`+ : 'A relation this gbrain\'s own migrations create has no graduation inventory row, so nothing was copied. Report this as a gbrain bug with the relation names; --force never bypasses this.',+ {+ why: newer+ ? 'Graduation copies only relations it knows how to classify; a newer schema may hold state this binary would silently drop.'+ : 'Every relation must be classified carry, rebind, rebuild, discard or schema-owned before a copy, so no state is lost by omission.',+ fix: newer+ ? { argv: ['gbrain', 'upgrade'], consent: [], actor: 'user', why: 'A newer gbrain knows the newer schema\'s relations.', requires_exclusive: false,+ user_message: 'This brain was written by a newer gbrain. Please run `gbrain upgrade` on this machine, then I can plan the move again.', verify }+ : { consent: [], actor: 'agent', why: 'An inventory row is missing in this gbrain release; a maintainer must add it.', requires_exclusive: false, verify },+ reason: newer ? 'newer_schema' : 'missing_inventory_row',+ });+ }++ interface ForeignKey { name: string; child: string; parent: string; childColumns: string[]; parentColumns: string[] }++ /** Every FK constraint in the current schema, read from pg_constraint. */+ export async function foreignKeys(engine: BrainEngine): Promise<readonly ForeignKey[]> {+ const rows = await engine.executeRaw<{ name: string; child: string; parent: string; child_cols: string; parent_cols: string }>(`SELECT c.conname AS name,+ ch.relname AS child, pa.relname AS parent,+ (SELECT json_agg(a.attname ORDER BY k.ord) FROM unnest(c.conkey) WITH ORDINALITY k(n,ord) JOIN pg_attribute a ON a.attrelid=c.conrelid AND a.attnum=k.n)::text AS child_cols,+ (SELECT json_agg(a.attname ORDER BY k.ord) FROM unnest(c.confkey) WITH ORDINALITY k(n,ord) JOIN pg_attribute a ON a.attrelid=c.confrelid AND a.attnum=k.n)::text AS parent_cols+ FROM pg_constraint c JOIN pg_class ch ON ch.oid=c.conrelid JOIN pg_class pa ON pa.oid=c.confrelid+ JOIN pg_namespace n ON n.oid=c.connamespace+ WHERE c.contype='f' AND n.nspname=current_schema()+ ORDER BY ch.relname COLLATE "C", c.conname COLLATE "C"`);+ return rows.map(r => ({ name: r.name, child: r.child, parent: r.parent, childColumns: JSON.parse(r.child_cols), parentColumns: JSON.parse(r.parent_cols) }));+ }++ /** Kahn's algorithm over parent -> child edges (self-FKs ignored), ties broken by name; throws on a cycle. */+ export function topologicalOrder(nodes: readonly string[], edges: readonly { parent: string; child: string }[]): string[] {+ const set = new Set(nodes);+ const indegree = new Map(nodes.map(n => [n, 0]));+ const children = new Map<string, Set<string>>(nodes.map(n => [n, new Set()]));+ for (const { parent, child } of edges) {+ if (parent === child || !set.has(parent) || !set.has(child) || children.get(parent)!.has(child)) continue;+ children.get(parent)!.add(child);+ indegree.set(child, indegree.get(child)! + 1);+ }+ const ready = nodes.filter(n => indegree.get(n) === 0).sort();+ const order: string[] = [];+ while (ready.length) {+ const next = ready.shift()!;+ order.push(next);+ for (const child of children.get(next)!) {+ indegree.set(child, indegree.get(child)! - 1);+ if (indegree.get(child) === 0) { ready.push(child); ready.sort(); }+ }+ }+ if (order.length !== nodes.length) {+ const cyclic = nodes.filter(n => !order.includes(n)).sort();+ throw new Error(`Foreign-key cycle among ${cyclic.join(', ')}: graduation needs an acyclic FK graph apart from self-references.`);+ }+ return order;+ }++ /** Carry and rebind entries present on this engine, parents before children. */+ export async function copyOrder(engine: BrainEngine, inv: Inventory = GRADUATION_INVENTORY): Promise<readonly InventoryEntry[]> {+ const live = new Set((await listRelations(engine)).map(r => r.relation));+ const copied = inv.entries.filter(e => (e.class === 'carry' || e.class === 'rebind') && live.has(e.relation));+ const byName = new Map(copied.map(e => [e.relation, e]));+ return topologicalOrder([...byName.keys()], await foreignKeys(engine)).map(name => byName.get(name)!);+ }++ /** The relation and every table that references it transitively, in topological order (the re-copy closure). */+ export async function fkClosure(engine: BrainEngine, relation: string): Promise<readonly string[]> {+ const fks = await foreignKeys(engine);+ const closure = new Set([relation]);+ for (let grew = true; grew;) {+ grew = false;+ for (const fk of fks) if (closure.has(fk.parent) && !closure.has(fk.child)) { closure.add(fk.child); grew = true; }+ }+ return topologicalOrder([...closure], fks);+ }diff --cc src/core/schema-migrations/registry.generated.tsindex 864ddb20fc,36586eea84..438e42e06e--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@@ -201,7 -201,7 +201,8 @@@ import { v197 } from './v197-managed-guimport { 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-entity-mention-index.ts';+ import { v201 } from './v201-persistence-graduation.ts';++import { v202 } from './v202-entity-mention-index.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@@ -402,4 -402,4 +403,5 @@@ export const MIGRATIONS: Migration[] =v199,v200,v201,++ v202,];diff --cc src/core/schema-migrations/v202-entity-mention-index.tsindex f4428b394d,0000000000..ee62fa9d11mode 100644,000000..100644--- a/src/core/schema-migrations/v202-entity-mention-index.ts+++ b/src/core/schema-migrations/v202-entity-mention-index.ts@@@ -1,76 -1,0 +1,76 @@@+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.+//+// Entity mention index (src/core/mentions/). Additive only; no existing row+// is rewritten:+// - page_aliases gains `origin` (frontmatter | declared | subject; existing+// rows read as frontmatter), `case_sensitive` and `alias_text` (the alias+// as written, for case-sensitive matching). The unique key widens to+// include origin, so a frontmatter alias and the same derived alias of one+// page coexist and readers apply precedence frontmatter > declared > subject.+// - page_mention_state: per page, the content revision, mention extractor+// version and source generation its mention links were published at, and+// the revision its derived aliases were refreshed at.+// - mention_gazetteer_entries: the last saved gazetteer entry set per source,+// diffed on the next pass to mark only affected pages due.+// - mention_index_status: one row per source (generation, state, pending+// count, last pass), read by entity cards and get_backlinks as `coverage`.+// page_aliases carries the managed-writer guard; ALTER TABLE fires no row+// trigger, so the column adds need no coordinated write.- export const v201: Migration = {- version: 201,++export const v202: Migration = {++ version: 202,+ name: 'entity_mention_index',+ idempotent: true,+ sql: `+ ALTER TABLE page_aliases ADD COLUMN IF NOT EXISTS origin TEXT NOT NULL DEFAULT 'frontmatter'+ CHECK (origin IN ('frontmatter','declared','subject'));+ ALTER TABLE page_aliases ADD COLUMN IF NOT EXISTS case_sensitive BOOLEAN NOT NULL DEFAULT false;+ ALTER TABLE page_aliases ADD COLUMN IF NOT EXISTS alias_text TEXT;+ DO $alias_origin$+ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'page_aliases_origin_uniq' AND conrelid = 'page_aliases'::regclass) THEN+ ALTER TABLE page_aliases ADD CONSTRAINT page_aliases_origin_uniq UNIQUE (source_id, alias_norm, slug, origin);+ END IF;+ ALTER TABLE page_aliases DROP CONSTRAINT IF EXISTS page_aliases_uniq;+ END $alias_origin$;+ CREATE TABLE IF NOT EXISTS page_mention_state (+ page_id INTEGER PRIMARY KEY REFERENCES pages(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ mention_revision UUID,+ mention_version INTEGER,+ mention_generation BIGINT,+ mentions_scanned_at TIMESTAMPTZ,+ alias_revision UUID,+ alias_version INTEGER,+ aliases_refreshed_at TIMESTAMPTZ+ );+ CREATE INDEX IF NOT EXISTS page_mention_state_source_idx ON page_mention_state (source_id, mention_version);+ CREATE TABLE IF NOT EXISTS mention_gazetteer_entries (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ name_norm TEXT NOT NULL,+ target_slug TEXT NOT NULL,+ case_sensitive BOOLEAN NOT NULL DEFAULT false,+ PRIMARY KEY (source_id, name_norm, target_slug, case_sensitive)+ );+ CREATE TABLE IF NOT EXISTS mention_index_status (+ source_id TEXT PRIMARY KEY REFERENCES sources(id) ON DELETE CASCADE,+ generation BIGINT NOT NULL DEFAULT 0,+ state TEXT NOT NULL DEFAULT 'pending' CHECK (state IN ('complete','pending','disabled','failed')),+ pending INTEGER NOT NULL DEFAULT 0,+ counted_at TIMESTAMPTZ,+ last_pass_at TIMESTAMPTZ,+ policy_fingerprint TEXT,+ error TEXT,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+ );+ DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname=current_user AND rolbypassrls) THEN+ ALTER TABLE page_mention_state ENABLE ROW LEVEL SECURITY;+ ALTER TABLE mention_gazetteer_entries ENABLE ROW LEVEL SECURITY;+ ALTER TABLE mention_index_status ENABLE ROW LEVEL SECURITY;+ END IF;+ END $rls$;+ `,+};diff --cc src/core/verbs.tsindex 92d907cf04,1cd8c68b92..db0ac1e800--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@@ -168,7 -168,7 +168,7 @@@ const entity: Operation =mutating: false,idempotent: true,outputRedaction: 'retrieval',- description: 'MEMORY VERB (v1): person/company/account card, zero LLM. referenced_by: every page linking here, by type, newest first (backlink_count excludes mentions); a group\'s `next` pages the rest. Previews are not evidence: fetch the page before stating status or dates. Miss: found:false with near matches and create_safety. Facts: recall.',- description: 'MEMORY VERB (v1): one known person/company/project card, zero LLM. A miss returns found:false with near matches and create_safety, so you do not duplicate a page. Facts: recall.',++ description: 'MEMORY VERB (v1): person/company/account card, zero LLM. referenced_by: every page linking here, by type, newest first; a group\'s `next` pages the rest. Previews are not evidence: fetch the page before stating status or dates. Miss: found:false with near matches and create_safety. Facts: recall.',params: {name: { type: 'string', required: true, description: 'Name, alias or slug (e.g. "Alice Example").' },},diff --cc templates/bootstrap/template-repo/README.mdindex 68ab81bc09,0e239d5943..92188ba622--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@@ -1,6 -1,6 +1,6 @@@# gbrain agent workspace — template- <!-- gbrain-template-stamp: 0.61.1.0 -->-<!-- gbrain-template-stamp: 0.60.52.0 -->++<!-- gbrain-template-stamp: 0.60.57.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --cc test/e2e/mentions-parity.test.tsindex 3e33e57f7a,0000000000..931c4bb14fmode 100644,000000..100644--- a/test/e2e/mentions-parity.test.ts+++ b/test/e2e/mentions-parity.test.ts@@@ -1,105 -1,0 +1,105 @@@+/**+ * Entity mention index: PGLite and Postgres parity.+ *- * Protects: the v201 migration shape (origin-aware page_aliases, mention++ * Protects: the v202 migration shape (origin-aware page_aliases, mention+ * state, entry and status tables) and the pass, alias writes, entity card+ * and get_backlinks paging producing the same rows on both engines. Bound+ * `text[]` parameters, the JSONB-free status writes and the conditional+ * publish's `FOR SHARE` reads run on real Postgres here, which PGLite cannot+ * prove. Regression: an engine-specific SQL difference in the pass or the+ * referrer query.+ *+ * Gated by DATABASE_URL (skips without it); the PGLite half always runs.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { setCliOptions } from '../../src/core/cli-options.ts';+import { extractStaleFromDB } from '../../src/commands/extract.ts';+import { buildEntityCard } from '../../src/core/verbs/entity-card.ts';+import { readReferrerPage } from '../../src/core/mentions/referrers.ts';+import { loadSourcePack } from '../../src/core/mentions/policy.ts';+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';++const SKIP_PG = !hasDatabase();+const describeBoth = SKIP_PG ? describe.skip : describe;++async function seed(engine: BrainEngine): Promise<void> {+ await engine.setConfig('schema_pack', 'gbrain-base-v2');+ const put = (slug: string, type: string, title: string, body: string) =>+ engine.putPage(slug, { type: type as never, title, compiled_truth: body, timeline: '', frontmatter: {} }, { sourceId: 'default' });+ await put('crm/123', 'crm', 'CRM record: Quormiro Capital', 'Account code: QUCO\nOwner: Dana Example');+ await put('crm/124', 'crm', 'CRM record: Quormiro Labs', 'Account code: QULA');+ await put('people/dana', 'person', 'Dana Example', 'Account owner.');+ for (let i = 0; i < 14; i++) await put(`tickets/t${String(i).padStart(2, '0')}`, 'ticket', `Ticket ${i}`, `Customer: QUCO\nStatus: ${i === 3 ? 'Open' : 'Closed'}`);+ await put('meetings/m1', 'meeting', 'Meeting: QULA renewal prep', 'Quormiro asked about Dana Example.');+ await put('notes/lower', 'note', 'Lowercase', 'quco is not a code here');+ // Distinct referrer dates: both engines order the newest-first page identically,+ // independent of how many writes share one clock tick.+ await engine.executeRaw(+ `UPDATE pages SET effective_date = TIMESTAMPTZ '2026-01-01T00:00:00Z' + (substring(slug from 10)::int * INTERVAL '1 day')+ WHERE slug LIKE 'tickets/t%'`);+}++async function snapshot(engine: BrainEngine) {+ setCliOptions({ quiet: true, progressJson: false, progressInterval: 1000, explain: false, timeoutMs: null, brain: null });+ const sweep = await extractStaleFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, catchUp: true });+ const links = await engine.executeRaw<{ f: string; t: string }>(+ `SELECT f.slug AS f, t.slug AS t FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id+ WHERE l.link_source = 'mentions' ORDER BY 1, 2`);+ const aliases = await engine.executeRaw<{ slug: string; alias_norm: string; origin: string; case_sensitive: boolean }>(+ 'SELECT slug, alias_norm, origin, case_sensitive FROM page_aliases ORDER BY slug, origin, alias_norm');+ const card = (await buildEntityCard(engine, 'default', 'QUCO', { remote: true, includeReferences: true })).card!;+ const pack = await loadSourcePack(engine, 'default');+ const scope = { slug: 'crm/123', sourceId: 'default', referrerSources: ['default'], excludePrivate: true, pack, keepVisibility: ['world' as const] };+ const first = await readReferrerPage(engine as never, scope, { type: 'ticket', limit: 5 });+ const columns = await engine.executeRaw<{ column_name: string }>(+ `SELECT column_name FROM information_schema.columns WHERE table_name = 'page_aliases' ORDER BY column_name`);+ return {+ mentions: { state: sweep.mentions?.state, remaining: sweep.mentions?.remaining },+ links: links.map(r => `${r.f}->${r.t}`),+ aliases: aliases.map(r => `${r.slug}:${r.origin}:${r.alias_norm}:${r.case_sensitive}`),+ card: { slug: card.entity.slug, count: card.referenced_by_count, groups: card.referenced_by!.map(g => `${g.canonical_type}:${g.total}:${g.rows.length}`),+ coverage: card.coverage!.state },+ page: { total: first.total, truncated: first.truncated, rows: first.rows.map(r => r.slug) },+ columns: columns.map(r => r.column_name),+ };+}++let pglite: PGLiteEngine;+let pgliteSnap: Awaited<ReturnType<typeof snapshot>>;+beforeAll(async () => {+ pglite = new PGLiteEngine();+ await pglite.connect({});+ await pglite.initSchema();+ await seed(pglite);+ pgliteSnap = await snapshot(pglite);+}, 180_000);+afterAll(async () => { await pglite.disconnect(); });++describe('entity mention index (PGLite half)', () => {+ test('the pass, aliases, card and paging produce the expected rows', () => {+ expect(pgliteSnap.mentions).toEqual({ state: 'complete', remaining: 0 });+ expect(pgliteSnap.links).toContain('meetings/m1->crm/124');+ expect(pgliteSnap.links).not.toContain('notes/lower->crm/123');+ expect(pgliteSnap.card).toEqual({ slug: 'crm/123', count: 14, groups: ['ticket:14:10'], coverage: 'complete' });+ expect(pgliteSnap.page).toMatchObject({ total: 14, truncated: true });+ expect(pgliteSnap.columns).toEqual(expect.arrayContaining(['origin', 'case_sensitive', 'alias_text']));+ });+});++describeBoth('entity mention index (Postgres parity)', () => {+ let pgSnap: Awaited<ReturnType<typeof snapshot>>;+ beforeAll(async () => {+ const pg = await setupDB();+ // setupDB truncates page-keyed tables only; alias rows and mention state from earlier files would leak in.+ for (const table of ['page_aliases', 'page_mention_state', 'mention_gazetteer_entries', 'mention_index_status']) await pg.executeRaw(`DELETE FROM ${table}`);+ await seed(pg);+ pgSnap = await snapshot(pg);+ }, 180_000);+ afterAll(async () => { await teardownDB(); });++ test('Postgres produces the same links, alias rows, card and page as PGLite', () => {+ expect(pgSnap).toEqual(pgliteSnap);+ });+});diff --cc test/fixtures/goldens/cli/tools-json.jsonindex 0f20ccd0b7,5e17c00079..f425105724--- 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": 197371,- "stdoutSha256": "aa63485c6fdaab8f7ec2fd5f61167df74d3a74468e1e5f54b59e04c146224962",- "stdoutBytes": 196986,- "stdoutSha256": "a94ef05467e333a594813f1214c3c3d5d17174ebf09c587a357b40fde49c668e",++ "stdoutBytes": 197487,++ "stdoutSha256": "14108588a0d85afb59f67fd2d9053e666c379a40bed191c4361d344cf79385cb","toolNames": ["remember","entity",@@@ -250,7 -250,7 +250,7 @@@"scope": "write"},{- "description": "MEMORY VERB (v1): person/company/account card, zero LLM. referenced_by: every page linking here, by type, newest first (backlink_count excludes mentions); a group's `next` pages the rest. Previews are not evidence: fetch the page before stating status or dates. Miss: found:false with near matches and create_safety. Facts: recall.",- "description": "MEMORY VERB (v1): one known person/company/project card, zero LLM. A miss returns found:false with near matches and create_safety, so you do not duplicate a page. Facts: recall.",++ "description": "MEMORY VERB (v1): person/company/account card, zero LLM. referenced_by: every page linking here, by type, newest first; a group's `next` pages the rest. Previews are not evidence: fetch the page before stating status or dates. Miss: found:false with near matches and create_safety. Facts: recall.","idempotent": true,"local_only": false,"mutating": false,diff --cc test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 8b43c9ce1f,96e9a19b27..6b3bc5a178--- 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 201 (latest: 201)",++ "message": "Version 202 (latest: 202)","name": "schema_version","status": "ok"},diff --cc test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 32a944315b,a93014abc8..471225bca3--- 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 201 (latest: 201)",++ "message": "Version 202 (latest: 202)","name": "schema_version","status": "ok"},diff --cc test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex e87d65a7a2,fec0a85688..1718366f81--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@@ -497,13 -497,13 +497,13 @@@},{"category": "ops",- "message": "RLS enabled on 106/106 public tables",- "message": "RLS enabled on 104/104 public tables",++ "message": "RLS enabled on 107/107 public tables","name": "rls","status": "ok"},{"category": "meta",-- "message": "Version 201 (latest: 201)",++ "message": "Version 202 (latest: 202)","name": "schema_version","status": "ok"},diff --cc test/fixtures/goldens/migrations/records.jsonindex 70f1b94376,3412cdfbaf..f4896195eb--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@@ -1,6 -1,6 +1,6 @@@{"golden": {-- "count": 196,++ "count": 197,"gaps": [17,18,@@@ -28,7 -28,7 +28,7 @@@"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},-- "latest": 201,++ "latest": 202,"records": [{"handler": {@@@ -2969,18 -2969,18 +2969,31 @@@"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": "absent",+ "idempotent": true,+ "name": "entity_mention_index",+ "sql": {+ "length": 2442,+ "sha256": "c76f74797f3bcc52158c7d8be80ab16bbbd2820d1732203aeaa796f4fec339b6"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",- "version": 201++ "version": 202}],"versions": [@@@ -3179,7 -3179,7 +3192,8 @@@198,199,200,-- 201++ 201,++ 202]},"normalizer": "migrations-record-v1"diff --cc test/graduation-inventory.test.tsindex 0000000000,36bbeb86a6..94fa794d15mode 000000,100644..100644--- a/test/graduation-inventory.test.ts+++ b/test/graduation-inventory.test.ts@@@ -1,0 -1,175 +1,175 @@@+ /**+ * Engine graduation state inventory (src/core/persistence/graduation-inventory.ts).+ *+ * Protects: every relation of a fresh schema on each engine has exactly one+ * inventory row (carry, rebind, rebuild, discard or schema-owned) with the+ * right engine-presence flags; graduation_unclassified_table fires on an+ * unclassified or missing relation; the FK graph is acyclic apart from the+ * known self-references, no copied table references a table the copy skips,+ * and the copy order puts every parent before its children.+ * Fails when: a migration adds a table or view without an inventory row (add+ * one to GRADUATION_INVENTORY with its class, loss kind and reason), a+ * migration adds an FK cycle, or a transform names a missing or key column.+ * Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+ import { PGLiteEngine } from '../src/core/pglite-engine.ts';+ import type { BrainEngine } from '../src/core/engine.ts';+ import { OperationError } from '../src/core/ops/contract.ts';+ import {+ assertRelationSet, copyOrder, expectedRelations, fkClosure, foreignKeys, GRADUATION_INVENTORY, listRelations, topologicalOrder,+ } from '../src/core/persistence/graduation-inventory.ts';+ import { primaryKey, tableColumns } from '../src/core/persistence/graduation-digest.ts';+ import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++ const engines: Array<{ kind: 'pglite' | 'postgres'; engine: BrainEngine }> = [];+ let engine: PGLiteEngine;+ let closePostgres: (() => Promise<void>) | undefined;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ engines.push({ kind: 'pglite', engine });+ if (process.env.DATABASE_URL) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);+ engines.push({ kind: 'postgres', engine: pg.engine });+ closePostgres = pg.close;+ }+ }, 120_000);+ afterAll(async () => {+ await engine.disconnect();+ await closePostgres?.();+ });++ /** Self-referencing FKs the copy handles in two passes; any other self-reference or cycle must be designed for first. */+ const KNOWN_SELF_FKS = [+ 'facts(superseded_by)', 'minion_jobs(budget_owner_job_id)', 'minion_jobs(parent_job_id)', 'minion_jobs(private_queue_owner_job_id)',+ ];++ async function expectCode(promise: Promise<unknown>, code: string): Promise<OperationError> {+ const error = await promise.then(() => null, (e: unknown) => e);+ expect(error).toBeInstanceOf(OperationError);+ expect((error as OperationError).code).toBe(code);+ return error as OperationError;+ }++ describe('graduation inventory', () => {+ test('rows are unique, classified once, and match the reviewed class counts', () => {+ const names = GRADUATION_INVENTORY.entries.map(e => e.relation);+ expect(new Set(names).size).toBe(names.length);+ const counts: Record<string, number> = {};+ for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;- expect(counts).toEqual({ carry: 94, rebind: 2, rebuild: 2, discard: 6, schema_owned: 3 });++ expect(counts).toEqual({ carry: 97, rebind: 2, rebuild: 2, discard: 6, schema_owned: 3 });+ for (const e of GRADUATION_INVENTORY.entries) {+ expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })+ .toEqual({ relation: e.relation, reason: true, present: true });+ }+ expect(expectedRelations('pglite').filter(r => !expectedRelations('postgres').includes(r))).toEqual(['planner_stats_deltas', 'planner_stats_state']);+ expect(expectedRelations('postgres').filter(r => !expectedRelations('pglite').includes(r))).toEqual(['file_migration_ledger']);+ expect(GRADUATION_INVENTORY.entries.filter(e => e.lossKind === 'security').map(e => e.relation).sort()).toEqual([+ 'access_tokens', 'oauth_clients', 'oauth_codes', 'oauth_grant_audit', 'oauth_tokens', 'persistence_local_writers', 'shared_skill_state']);+ });++ test('every relation of a fresh schema has a row on each engine', async () => {+ for (const { kind, engine } of engines) {+ expect({ kind, relations: (await listRelations(engine)).map(r => r.relation) }).toEqual({ kind, relations: [...expectedRelations(kind)] });+ await assertRelationSet(engine, kind);+ }+ });++ test('an unclassified or missing relation refuses with graduation_unclassified_table', async () => {+ for (const { kind, engine } of engines) {+ await engine.executeRaw('CREATE TABLE graduation_probe_unlisted (id int PRIMARY KEY)');+ try {+ const error = await expectCode(assertRelationSet(engine, kind), 'graduation_unclassified_table');+ expect(error.message).toContain('graduation_probe_unlisted');+ expect(error.reason).toBe('missing_inventory_row');+ expect(error.fix?.verify?.argv).toEqual(['gbrain', 'migrate', '--to', 'postgres', '--plan', '--url-env', 'GBRAIN_TARGET_URL', '--json']);+ } finally { await engine.executeRaw('DROP TABLE graduation_probe_unlisted'); }+ const extra = { ...GRADUATION_INVENTORY, entries: [...GRADUATION_INVENTORY.entries, { ...GRADUATION_INVENTORY.entries[0]!, relation: 'graduation_probe_absent' }] };+ expect((await expectCode(assertRelationSet(engine, kind, extra), 'graduation_unclassified_table')).message).toContain('missing: graduation_probe_absent');+ }+ });++ test('a schema newer than this binary names the upgrade instead of a maintainer bug', async () => {+ const { kind, engine } = engines[0]!;+ const [version] = await engine.executeRaw<{ value: string }>("SELECT value FROM config WHERE key='version'");+ await engine.executeRaw("UPDATE config SET value='99999' WHERE key='version'");+ await engine.executeRaw('CREATE TABLE graduation_probe_future (id int PRIMARY KEY)');+ try {+ const error = await expectCode(assertRelationSet(engine, kind), 'graduation_unclassified_table');+ expect(error.reason).toBe('newer_schema');+ expect(error.fix?.argv).toEqual(['gbrain', 'upgrade']);+ } finally {+ await engine.executeRaw('DROP TABLE graduation_probe_future');+ await engine.executeRaw("UPDATE config SET value=$1 WHERE key='version'", [version!.value]);+ }+ });++ test('transforms and row filters name real, non-key columns of copied tables', async () => {+ for (const { engine } of engines) {+ for (const entry of GRADUATION_INVENTORY.entries) {+ if (!entry.transforms.length && !entry.rowFilter) continue;+ expect({ relation: entry.relation, copied: entry.class === 'carry' || entry.class === 'rebind' }).toEqual({ relation: entry.relation, copied: true });+ const columns = (await tableColumns(engine, entry.relation)).map(c => c.name);+ const key = (await primaryKey(engine, entry.relation)).map(c => c.name);+ for (const t of entry.transforms) {+ expect({ relation: entry.relation, column: t.column, exists: columns.includes(t.column), key: key.includes(t.column), sql: Boolean(t.expression) })+ .toEqual({ relation: entry.relation, column: t.column, exists: true, key: false, sql: true });+ }+ const filter = entry.rowFilter ? ` WHERE ${entry.rowFilter}` : '';+ await engine.executeRaw(`SELECT ${entry.transforms.map(t => `(${t.expression})::text`).join(', ') || '1'} FROM ${entry.relation}${filter} LIMIT 1`);+ }+ }+ });++ test('every copied table has a primary key', async () => {+ for (const { engine } of engines) {+ for (const entry of await copyOrder(engine)) expect((await primaryKey(engine, entry.relation)).length).toBeGreaterThan(0);+ }+ });++ test('the FK graph is acyclic apart from known self-references, and copied tables reference only copied tables', async () => {+ const copied = new Set(GRADUATION_INVENTORY.entries.filter(e => e.class === 'carry' || e.class === 'rebind').map(e => e.relation));+ for (const { kind, engine } of engines) {+ const fks = await foreignKeys(engine);+ expect({ kind, self: fks.filter(f => f.child === f.parent).map(f => `${f.child}(${f.childColumns.join(',')})`).sort() }).toEqual({ kind, self: KNOWN_SELF_FKS });+ const tables = (await listRelations(engine)).filter(r => r.kind === 'table').map(r => r.relation);+ expect(topologicalOrder(tables, fks)).toHaveLength(tables.length);+ expect({ kind, crossing: fks.filter(f => copied.has(f.child) && !copied.has(f.parent)).map(f => f.name) }).toEqual({ kind, crossing: [] });+ }+ });++ test('copy order holds every carry and rebind table, parents first', async () => {+ for (const { kind, engine } of engines) {+ const order = (await copyOrder(engine)).map(e => e.relation);+ const expected = GRADUATION_INVENTORY.entries.filter(e => (e.class === 'carry' || e.class === 'rebind') && e.engines[kind]).map(e => e.relation).sort();+ expect([...order].sort()).toEqual(expected);+ for (const fk of await foreignKeys(engine)) {+ if (fk.child === fk.parent || !order.includes(fk.child)) continue;+ expect({ fk: fk.name, parentFirst: order.indexOf(fk.parent) < order.indexOf(fk.child) }).toEqual({ fk: fk.name, parentFirst: true });+ }+ }+ });++ test('fkClosure returns the relation and every transitive child in topological order', async () => {+ for (const { engine } of engines) {+ const closure = await fkClosure(engine, 'pages');+ expect(closure[0]).toBe('pages');+ for (const child of ['content_chunks', 'links', 'tags', 'timeline_entries', 'page_versions', 'raw_data']) expect(closure).toContain(child);+ const fks = await foreignKeys(engine);+ for (const fk of fks) {+ if (fk.parent === fk.child || !closure.includes(fk.parent)) continue;+ expect(closure.indexOf(fk.parent)).toBeLessThan(closure.indexOf(fk.child));+ }+ expect(closure).not.toContain('sources');+ expect(await fkClosure(engine, 'config')).toEqual(['config']);+ }+ });++ test('topologicalOrder throws on a cycle and ignores self-references', () => {+ expect(topologicalOrder(['a', 'b'], [{ parent: 'a', child: 'a' }, { parent: 'a', child: 'b' }])).toEqual(['a', 'b']);+ expect(() => topologicalOrder(['a', 'b', 'c'], [{ parent: 'a', child: 'b' }, { parent: 'b', child: 'a' }])).toThrow(/cycle among a, b/);+ });+ });diff --cc test/mcp-schema-budget.test.tsindex 3c80c4fbbb,244ba88ded..7add784fd7--- a/test/mcp-schema-budget.test.ts+++ b/test/mcp-schema-budget.test.ts@@@ -56,11 -50,11 +56,11 @@@ const PARAM_DESCRIPTION_HARD_CAP = 200/** Per-tool budget: JSON.stringify of the served tool definition. */const TOOL_BUDGETS: Record<string, number> = {add_timeline_entry: 640, cancel_job: 270, cancel_write_request: 350, capture: 1250, context_pack: 760,- delete_skill: 810, delta: 830, edit_page: 1090, entity: 460, find_anomalies: 520, forget: 560, get_agent_job: 270,- get_backlinks: 430, get_ingest_log: 280, get_page: 930, get_recent_salience: 660, get_skill: 910,+ delete_skill: 810, delta: 830, edit_page: 1090, entity: 600, find_anomalies: 520, forget: 560, get_agent_job: 270,- get_backlinks: 680, get_ingest_log: 280, get_page: 780, get_recent_salience: 660, get_skill: 910,++ get_backlinks: 680, get_ingest_log: 280, get_page: 930, get_recent_salience: 660, get_skill: 910,get_skill_asset: 790, get_write_request: 330, join_brain: 560, leave_brain: 540, list_brain_skillpack: 230,- list_link_sources: 220, list_pages: 1090, list_skills: 670, list_write_requests: 450, put_page: 1320,- put_skill: 1420, query: 3250, recall: 1590, remember: 1370, request_tools: 560, resolve_slugs: 410, search: 1760,+ list_link_sources: 220, list_pages: 1060, list_skills: 670, list_write_requests: 450, put_page: 1320,+ put_skill: 1420, query: 3100, recall: 1540, remember: 1330, request_tools: 560, resolve_slugs: 410, search: 1670,submit_agent: 750, sync_brain_skills: 770, synthesize: 550, traverse_graph: 680, whoami: 230,};diff --cc test/schema-bootstrap-coverage.test.tsindex ee2f17b457,f3824b72a4..d5c7cd2efd--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@@ -859,13 -859,6 +859,13 @@@ test('every CREATE INDEX column in PGLI// ─────────────────────────────────────────────────────────────────const COLUMN_EXEMPTIONS = new Set<string>([+ // page_aliases origin / case_sensitive / alias_text (entity mention index,- // migration v201): page_aliases is a PGLite bootstrap table and a++ // migration v202): page_aliases is a PGLite bootstrap table and a+ // Postgres migration-only table; no schema blob references these columns+ // (no index or view reads them), so there is nothing to forward-reference.+ 'page_aliases.origin',+ 'page_aliases.case_sensitive',+ 'page_aliases.alias_text',// takes.embedding: the takes table is migration-only (no CREATE TABLE in// PGLITE_SCHEMA_SQL / src/schema.sql), so there is no schema-blob forward// reference for the bootstrap to trip on. The column is created inline in