Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge origin/master (v0.60.164.0) into capy/mpw2-w1-question-recall

garrytane39ceb5adf1c
diff --cc CHANGELOG.md
index 0baf40cf0d,75c65c4f35..9f64a39f77
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -10,28 -10,165 +10,187 @@@ credits are retained; no result has bee
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**`recall` can rank saved facts by a question.** Pass `question` and recall returns the facts most relevant to it, each with a `relevance` score, instead of the newest ones. Facts below the match threshold are left out, so an empty list means nothing saved matches.
+
+Calls without `question` behave as before and return the newest facts; every response now says which order it used in `facts_order`. A call that passes only `query` carries a `recall_hint` notice naming `question` and the exact retry call. `gbrain recall --question "<q>"` works from the CLI, locally or against a remote brain. Ranking uses the same read policy as every other recall: the trust floor, quarantine and rederive hiding, remote world-only facts and the private-page filter all apply. Restart a resident `gbrain serve` after upgrading so agents see the new parameter.
+
+## To take advantage of [Unreleased]
+
- `gbrain upgrade` applies the facts index migration (numbered at stamp time; v233 on this branch) automatically. If `gbrain doctor` warns about a partial migration, run `gbrain apply-migrations --yes`, then restart a resident `gbrain serve`.
++`gbrain upgrade` applies the facts index migration (numbered at stamp time; v236 on this branch) automatically. If `gbrain doctor` warns about a partial migration, run `gbrain apply-migrations --yes`, then restart a resident `gbrain serve`.
+
+### Itemized changes
+
+- **`recall` `question`** (`facts/question-recall.ts`, `ops/facts.ts`). Up to 2,000 characters; refused with `supersessions` or `include_expired`, with the corrected call in the error. Works with `entity`, `session_id`, `since`, `grep` and every other fact filter, which apply before ranking. The question is embedded once through the gateway's query-embedding cache, so a `query` of the same text in the same process costs no second provider call. Without an embedding provider, or with embeddings turned off, facts rank by word match and `facts_degraded.reason` says so; facts without an embedding are counted in `facts_degraded.unembedded`, with a `facts_unembedded` notice whose fix previews `gbrain embed --stale --facts` before any paid run.
+- **Admission rule** (`recall.question_admission`). `reserve` (default) keeps a fact at cosine 0.5 or a third of the question's words; `facts_arm` uses the stricter facts-arm rule.
+- **Shared fact scorer** (`search/fact-relevance.ts`). Recall's `question`, the temporal fact reserve and the facts arm now read one candidate pool and one scorer. Word matches are whole-word, and a very long fact's matches count for less. In `query`, facts of an entity the question names come only from that entity page's own source.
+- **`gbrain recall --question`** reads its value as the question; before, it was taken as an entity name.
- - **Fast on large brains.** On a 100k-fact brain a ranked recall takes 51 ms at p95 on Postgres (65 ms for a remote caller, 10 ms with `entity`) and 152 ms on PGLite (139 ms remote, 54 ms with `entity`). The facts index migration (numbered at stamp time; v233 on this branch) adds a keyword index over active facts (built under `GBRAIN_FTS_LANGUAGE`; `gbrain reindex-search-vector` rebuilds it when the language changes) and two small indexes for the unembedded count; the vector, keyword and entity lookups run concurrently, the vector lookup now uses the facts HNSW index, and the keyword lookup is planned per call. Building the indexes reads each fact once (about 2 seconds per 100k facts) and rewrites none.
++- **Fast on large brains.** On a 100k-fact brain a ranked recall takes 51 ms at p95 on Postgres (65 ms for a remote caller, 10 ms with `entity`) and 152 ms on PGLite (139 ms remote, 54 ms with `entity`). The facts index migration (numbered at stamp time; v236 on this branch) adds a keyword index over active facts (built under `GBRAIN_FTS_LANGUAGE`; `gbrain reindex-search-vector` rebuilds it when the language changes) and two small indexes for the unembedded count; the vector, keyword and entity lookups run concurrently, the vector lookup now uses the facts HNSW index, and the keyword lookup is planned per call. Building the indexes reads each fact once (about 2 seconds per 100k facts) and rewrites none.
+- **Embedding model switches keep fact indexes.** A dimension change rebuilds `facts.embedding` and now re-creates the btree indexes that read it instead of dropping them.
+
+### For contributors
+
+- `test/recall-question.test.ts` covers ranking, the parameter contract, the read policy (local, remote and private-sourced facts), the degraded paths, `recall_hint` and the embedding cache on PGLite, and on Postgres through `test/e2e/recall-question-postgres.test.ts`. `test/fact-relevance.test.ts` pins the scorer; `test/recall-question-cli.test.ts` the CLI.
+ ## [0.60.164.0] - 2026-10-11
+
+ **`query` now answers with the facts you corrected, and gbrain can keep a question answered for you.**
+
+ A fact you save with `remember` used to lose to the stale page text it corrected, because page search never ranked saved facts. `query` now brings matching saved facts in as their own rows, in space the pages left free. Pinned questions are a new opt-in: pin a question once, and gbrain keeps its answer current with a citation behind every sentence.
+
+ ### Itemized changes
+
+ - `query` adds up to 3 saved facts that match the question as rows of their own (`result_type: "fact"`, with `fact_id` and a `follow_up` recall call). They use only rows and tokens the pages left free, so no page is pushed out, and a page row whose claim a newer fact replaced is marked `superseded_claim`. It costs up to three database lookups and no model call. Remote callers see only facts whose source pages they could read. On by default; `gbrain config set search.query_facts_arm false` turns it off.
+ - `remember` takes `valid_from`, so a correction can carry the date it became true instead of the day it was saved.
+ - Fact supersession uses a threshold measured for the brain's embedding model. The default voyage-4 at 1024 dimensions keeps 0.95 and decides as before. Any other model no longer replaces a similar fact by cosine: both stay active and conflict review judges the pair, and exact-text duplicates still merge. Doctor `supersession_calibration` names a command that measures a threshold on synthetic text (about a cent), and `facts.supersession_thresholds` registers one.
+ - Pinned questions: `gbrain questions pin|list|status|refresh|unpin` and MCP `questions_*`. Answers live in their own private tables with per-sentence evidence, never in search results, exports or git. A sentence whose evidence changed is flagged stale when you read it, and `context_pack` gains optional `pinned_questions` and `withheld` fields. A pin made over MCP stays inactive until the owner activates it. The dream cycle's `standing_questions` phase refreshes active pins under `cycle.standing_questions.budget_usd` (default $1.00 per run). Guide: `docs/guides/pinned-questions.md`.
+ - Pinned questions replace `dream.auto_think`. On upgrade, its questions become inactive pins with their budget, cooldown, model and commit setting, so nothing starts spending; `gbrain questions pin --id <id>` turns one on. `gbrain config get|set dream.auto_think.*` names where each key went.
+ - Opt-in retrieval settings, each off by default: `search.evidence_date_header` (each delivered evidence block starts with its observation date), `search.entity_anchoring` (a current-state question that names one entity puts that entity's page and the pages about it first), `search.temporal_fact_reserve` (a question about when things happened reserves part of the token budget for dated facts) and `facts.candidate_fusion interleave` (a keyword arm for supersession candidates).
+ - `GOOGLE_GENERATIVE_AI_BASE_URL` (or `provider_base_urls.google`) routes Gemini chat, expansion and embeddings through a proxy.
+ - Fixes:
+ - `put_pages` accepts a byte-identical repeated slug as one write; differing repeats are refused page by page instead of failing the batch. Slow fenced code no longer stalls a batch.
+ - `query` skips the image arm on brains with no image embeddings.
+ - `query` returning whole pages with a `token_budget` sizes its hit list to the budget instead of stopping at the default row count with budget unused.
+ - `gbrain extract-conversation-facts` reads plain `user:` / `assistant:` transcripts, and exits 0 on partial success with a summary of the pages that failed.
+ - Migration v235 adds the pinned-question tables.
+
+ ## [0.60.163.0] - 2026-10-11
+
+ **A managed brain's Git durability is now a recorded owner setting, and the managed-worktree refusals name the command to run instead of a dead end.**
+
+ On a managed brain the persistence owner commits and pushes page writes through its Git effect, but until now that depended on a post-commit hook the owner probed for on every pass, and nothing told an operator how to turn it on (#5182). `gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>]` records the setting on the host binding (migration v234 adds the nullable `git_durability` column; nothing recorded keeps today's probe), `--enable` runs a read-only push probe first and re-queues the Git effects skipped while it was off, and `--pat-file` wires the repo-scoped push credential and retries the parked pushes. `sources push`, `bootstrap verify`'s `push_probe` and the skill-pack writer guard now name that route on a managed worktree instead of a bare `writer_coordinator_required` (#5606). Doctor's new `foreign_ownership_marker` names the stale ownership stamp that blocks a claim (#5808), `writer activate` on an already-managed brain answers `already_enabled` with the owner process to check (#5514), `gbrain repair managed-sync-orphans` retires sync bookkeeping nothing current can resume (#5459), transcript re-ingest deletes a stale part through the coordinator instead of refusing (#5235), `gbrain sources set-strategy <id> <strategy>` persists a code source's sync strategy and refuses under an unfinished managed run (contributed by @rokas-tarasevicius, supersedes #5955), and `bootstrap status` tells a project-scoped Codex MCP connection you manage yourself apart from "nothing wired" (#4082).
+
+ ### To take advantage of this release
+
+ `gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor`
+ warns about a partial migration:
+
+ ```bash
+ gbrain apply-migrations --yes --no-autopilot-install # v234: persistence_host_bindings.git_durability
+ gbrain doctor --json | grep -E 'schema_version|foreign_ownership_marker|sync_failures'
+ ```
+
+ On a managed brain, `gbrain sources writer status <source> --json` now reports `git_durability` (`on`, `off` or `unknown`); `gbrain sources writer git-durability <source> --enable --dry-run` previews the switch.
+
+ ### Itemized changes
+
+ - **Git durability as an owner setting (#5182, [R7i]/[R7ii]).** `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL) via migration v234 on PGLite, Postgres and PgBouncer transaction mode; `gitDurabilityPolicy` resolves `enabled`/`disabled` from the binding and consults the legacy hook probe only when nothing is recorded (fail-closed on probe error). The effect worker's per-root probe routes through it. New verb `writer git-durability` (`writer_git_durability` admin operation; `--enable`, `--disable`, `--pat-file`, `--dry-run`, the usual `--admin-intent`/`--expected-state`) with error codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`, `pat_file_unreadable`. `writer activate` and `writer status` list `git_durability` per binding. Catch-up re-queues `durability_not_enabled` Git effects without inserting under `UNIQUE(request_id, kind)`.
+ - **Managed-worktree refusals name the route (#5606).** `gbrain sources push` on a managed canonical worktree refuses with the owner's `writer status` and `writer git-durability` commands; `bootstrap verify`'s `push_probe` reports the managed route instead of a failure; the skill-pack writer guard and doctor's skill checks point at `gbrain call --source <source> import_skill_proposal`.
+ - **Doctor `foreign_ownership_marker` (#5808).** A stamp or reservation beside a source checkout whose brain or worktree this brain does not know is listed with its path and the operator step (`docs/guides/write-refusals.md#foreign-ownership-marker`).
+ - **`writer activate` already managed (#5514).** Reason `already_enabled` with a `next_action` naming the owner process to check, instead of a generic refusal.
+ - **`gbrain repair managed-sync-orphans --source <id>` (#5459).** Explicit-only, preview-bound: retires failure rows with no cursor, cursors recorded by a principal that is no longer an active local writer, and superseded pre-options cursors; live pending requests and resumable cursors are kept. Doctor `sync_failures` names it; `docs/guides/repair.md#managed-sync-orphans` and the sync-unblock runbook explain when.
+ - **Transcripts on a managed brain (#5235).** A stale transcript part is deleted through the coordinator (`delete_page` with the expected revision) instead of refusing the re-ingest.
+ - **`gbrain sources set-strategy <id> <markdown|code|auto>` (PR #5955).** Persists the sync strategy on the source; refuses `sync_run_unfinished` (exit 1) while a managed sync run is unfinished, naming the resume and the orphan-repair commands. Contributed by @rokas-tarasevicius.
+ - **`bootstrap status` and Codex project config (#4082).** A `<workspace>/.codex/config.toml` MCP server is reported `partial` (detected, not verified) with an adopt hint; `gbrain bootstrap hooks --adopt --harness codex` records it after a passing verify in the versioned `<home>/bootstrap/adopted-connections.json` sidecar (sha256 over transport, URL and header names; no tokens) and the phase reads `done`; a drifted or removed table reads `partial` again. Nothing is written to the Codex config and no receipt registration is fabricated.
+
+ ### For contributors
+
+ - New modules: `src/core/persistence/git-durability-policy.ts`, `git-durability-administration.ts`, `managed-sync-orphans.ts` (+ `src/core/repair/managed-sync-orphans.ts`), `src/commands/sources-strategy.ts`, `src/core/bootstrap/adopted-connections.ts`, `adopt-connection.ts`, `src/core/schema-migrations/v234-persistence-git-durability.ts`.
+ - Tests (each proven failing on master first): `test/persistence-admin-git-durability.test.ts`, `test/doctor-foreign-ownership-marker.test.ts`, `test/persistence-activation.test.ts`, `test/repair-managed-sync-orphans.test.ts`, `test/transcripts-managed-ingest.test.ts`, `test/managed-push-remedy.serial.test.ts`, `test/doctor-skill-checks.test.ts`, `test/sources-strategy.test.ts`, `test/bootstrap-adopted-connection.serial.test.ts`. Doctor goldens regenerated (new check row; schema column count +1).
+ - Two hunks on wave 13 PR1's files (`effect-git.ts` resolver call, `hardenBrainRepo` managed refusal) ship as patches with the integrator, not in this PR.
+
+ ## [0.60.162.0] - 2026-10-11
+
+ **Dream stops merging facts that only look alike, writes refuse a typo instead of ignoring it, and a dozen smaller wrong answers are fixed.**
+
+ Twenty-one issues and three contributor PRs, mostly about the brain quietly doing the wrong thing. Two facts that said "Invoice A is due Monday" and "Invoice B is due Tuesday" could be merged into one take because their embeddings were close; now a difference in a number, date, amount or negation keeps them apart. A `put_page` or `remember` that misspelled a parameter name was accepted with the typo silently dropped; now every write refuses an unknown parameter and names it. A `remember` of a fact you already stored word for word inserted a second copy on brains without an embedding key; now it returns the existing fact. A fence row that quoted a fence marker became a live marker and the row vanished; the marker is now encoded inside the cell. Health counters follow your schema pack instead of a hardcoded person/company list, `recall` hits say which source they came from, cross-source links your source policy approved are written by every writer, and a question like "what happened in September 2026" bounds `think` to that month on its own.
+
+ ### How to use it
+
+ - `gbrain dream --phase consolidate --dry-run` now lists the clusters it would write under `details.clusters` before you commit to them.
+ - `gbrain config set chronicle.max_events_per_page 40` caps how many chronicle events one page may contribute (default 25).
+ - `gbrain config set dream.attribution_checks true` turns on two optional checks that stop an assistant's proposal from being recorded as the user's decision. Off by default; nothing changes until you opt in.
+ - `gbrain search modes` suggests EmbeddingGemma's query prompt (`task: search result | query: `) when that model is the embedder.
+ - `think` with no `since`/`until` reads the one explicit date the question names (`2026-09-15`, `2026-09`, `September 2026`); the result says `window_source: 'question'`. Caller bounds still win.
+
+ ### What you'd see
+
+ | Before | After |
+ |---|---|
+ | Two untyped event facts with a 0.86 cosine merged into one take and the older one expired | They stay two facts; untyped facts need the 0.95 explicit-duplicate bar and must not differ in a number, date, amount or negation |
+ | `put_page` with `expectedRevision` (typo) committed and ignored the field | `invalid_params` naming the unknown parameter, in every `strict_params` mode |
+ | `put_page` on an existing page with no `expected_revision` → `revision_conflict` | `revision_required`, with `get_page` as the fix; a genuine stale revision is still `revision_conflict` |
+ | `get_health.entity_page_count` 0 on a brain whose pack declares `yc` or `civic` entity pages | Counts the types the active pack declares, per source; a pack that does not load reports `entity_types_status: pack_unavailable` |
+ | A provider 403 "project does not have access to model X" classified `auth` | `model_not_found`, with the model fix |
+
+ ### Itemized changes
+
+ - **Consolidate no longer merges unrelated event facts** (#6023). Untyped facts (no metric claim) cluster only at `max(cycle.consolidate.cluster_threshold, 0.95)` and never when `claimsDiverge` finds a negation, number, date or amount that differs; typed metric facts keep the configured threshold because a metric series is expected to change value. `--dry-run` returns up to 50 clusters in `details.clusters`; private fact text appears only for the local CLI, other callers see ids and visibility. *Things to watch:* fewer takes from untyped event facts; facts an earlier run merged keep the `valid_until` it stamped (`remember … replaces` records a correction).
+ - **Write operations reject unknown parameters** (#5970). Every mutating tool (`put_page`, `remember`, `add_timeline_entry`, …) refuses a parameter it does not declare with `invalid_params` and `suggestion: 'Unknown parameter "<name>".'`, before admission and in every `strict_params` mode. Read tools keep the mode's behavior. The merging page writes (`add_tag`, `remove_tag`, `add_timeline_entry`, `takes_*`) now declare the `expected_revision` and `force` they always honored (full tool surface; the starter schema is unchanged), so a caller that sent them keeps working.
+ - **`writeSingleFact` dedups exact repeats and never mints a fallback entity** (#5152, #5504 part (a), #5275). An exact repeat for the same entity, or with no resolved entity, returns the existing fact (`status: duplicate`) with or without an embedding; a remote or unattributed caller never dedups against a private-sourced fact. An unmanaged write whose entity fell back to slugification stores `entity_slug` NULL instead of a placeholder slug, so the stub guard has nothing to refuse. The legacy backstop's exact check also covers facts with no resolved entity.
+ - **Fence markers written into a cell are encoded, never live** (#5395). A claim quoting a fence marker round-trips as text; the row is no longer lost.
+ - **Dream `synthesize_concepts` writes one page per concept, however the label is spelled** (#5965). Stems that differ only by hyphens, underscores and dots fold onto one page per run: the spelling with a live `concepts/` page wins, otherwise the one most atoms use (ties go to the hyphenated form); the others redirect for that run. Two spellings that both already have live pages are left apart. *Things to watch:* existing duplicate pages are not merged for you; `details.folded_spellings` names each fold.
+ - **Mechanical attribution checks, off by default** (#5425). `dream.attribution_checks true` makes `propose_takes` store a proposal as held by `brain` when its numbers, dates and quotes appear only in assistant turns and no user turn states or accepts them, and quarantines a synthesis sentence a later user turn takes back on the same number or date (`superseded_in_source` in `unverified_claims`). Off, output is byte-identical.
+ - **Chronicle caps events per page** (#5329). `chronicle.max_events_per_page` (default 25, 1..1000) keeps the first N survivors in judge order after the date rules; dropped proposals are counted as `over_cap`.
+ - **Cross-source links the source policy approved are written by every writer** (#4680). A link whose target resolves into another source under `link_resolution.cross_source`, or a `[[source:slug]]` reference from a federated source, is written by `put_page`, `capture`, the managed stale pass and the reconciliation sweep, not only by `extract links`. The write receipt reports drops as `auto_links.skipped_cross_source`; a reader granted one source still never sees the other source's endpoint, and the entity card confines an untrusted caller's outgoing edges to its own source. *Things to watch:* pages that cite another source gain the edges you opted into on their next write or stale pass; the sweep reports an unqualified target that exists only elsewhere as `cross_source` rather than `missing_target`.
+ - **`links.resolution_type` is written** (#4381): `qualified` for a `[[source:slug]]` reference, `unqualified` otherwise; edges no reference derived keep NULL. Existing rows are not backfilled.
+ - **Entity counters follow the active schema pack** (#4772). `get_health` / `gbrain health` (`entity_page_count`, `link_coverage`, `timeline_coverage`, `most_connected`) and doctor's `graph_coverage` / `orphan_ratio` count the page types the pack declares with `primitive: entity`, resolved per source when sources carry their own pack (`schema_pack.source.<id>`). A pack that does not load reports `entity_types_status: pack_unavailable` (0 entities, `null` ratios, a `graph_coverage` warn naming the pack). Helper shape by @Matthieusabourin2. *Things to watch:* on gbrain-base brains `yc`, `civic` and `organization` pages now count, so coverage ratios move and a `graph_coverage` warn can appear where those pages are unlinked; `gbrain schema active` repairs a broken pack.
+ - **`code-callers` lists callers inside top-level `describe`/`it` blocks and other module-level statements** (#5001). A top-level statement containing a call in a JS/TS/TSX/Python/Ruby file is chunked as `module` / `__module__` (`<file-basename>::__module__`), so its calls get edges; both edge writers share `mapCodeEdges`. *Things to watch:* the next `gbrain sync` re-chunks and re-embeds those files once (priced as `grammar_drift`; `CHUNKER_VERSION` stays 8). Attribution follows @nikolai-vysotskyi's suggestion.
+ - **A 403 model-access denial classifies `model_not_found`, not `auth`** (#5394). The model-not-found phrases are tested before the status map; a plain 401/403 stays `auth`.
+ - **A write naming no `expected_revision` for an existing page is `revision_required`** (#5385), with `get_page` as the fix; a wrong revision stays `revision_conflict`; `force` and `revision_backfill_pending` are unchanged. `remember` and `add_tag` on an existing page still converge through the semantic retry.
+ - **`propose_takes` skips atoms and every dream-written page** (#5211). New atoms carry `dream_generated: true` next to `extracted_by`, so facts extraction, the chronicle and transcript discovery skip them like other derived pages; `listCandidatePages` also drops legacy `type: atom` pages that carry neither stamp. The source page an atom was extracted from is still a candidate.
+ - **Every `recall` hit names its `source_id`** (#4830), falling back to the scope's single source; a federated read with no row source leaves it absent rather than guessing.
+ - **`think` bounds its evidence to the one explicit date a question names** when the caller passes no window (PR #5086). ISO day, ISO month or English month + year; a bare year, two distinct dates, an invalid date or a relative phrase leaves the window open. `window_source` and a `WINDOW_FROM_QUESTION` warning say when it applied. Contributed by @tarush1989. Supersedes #5086.
+ - **Matryoshka models that answer at their native width are fitted to the brain's width** (PR #5921). A recipe that declares `matryoshka: { native, prefixes }` for a model (NVIDIA's Nemotron-3-Embed-8B at 4096 with 1024/2048) has its native-width response sliced and L2-normalized before the dimension check; every other vector is untouched. Contributed by @abudhi19. Supersedes #5921.
+ - **Doctor suggests EmbeddingGemma's query task prompt** (PR #6062): `task: search result | query: ` for `embeddinggemma` models in `gbrain search modes`. The document-side formatting stays open (#3783, #5215). Contributed by @xorets. Supersedes #6062.
+
+ ### For contributors
+
+ - Pinned tests that changed with the contracts above: `test/legacy-fact-extraction-dedup.test.ts` and `test/facts-drain-scheduler.test.ts` (#5275: an exact unparented repeat from a second page is a duplicate), `test/write-attribution-facts-takes.test.ts` (#5504 seeds the entity page), `test/denied-after-list.test.ts` (#5970 sends only declared params), `test/managed-phase-matrix.test.ts` (#6023 fixture), `test/cycle-consolidate*.test.ts`, `test/e2e/cycle-consolidate-postgres.test.ts`, `test/managed-maintenance.test.ts`, `test/trust-taint-dream.test.ts`, `test/write-attribution-cycle.test.ts` (#6023 thresholds); `test/facts-fallback-stub-guard.test.ts`, `test/fence-write.test.ts`, `test/memory-verbs-conformance.test.ts` (#5504 NULL entity, #5152 dedup); `test/persistence-reconcile.test.ts` (#5970 refuses before admission); `test/link-preparation-shared-index.test.ts` (#4680 writes the approved edge); `test/capture-op.test.ts`, `test/persistence-revision-conflict-message.test.ts` (#5385 code); `test/evidence-delivery.test.ts` key list (#4830). Each flip carries a comment citing its issue.
+ - Goldens regenerated for the contract changes above: `test/fixtures/goldens/cli/tools-json.json`, `exports/types.json`, `sql-text/links.json`, `evidence-delivery/off-path.json` (recall hits gain `source_id`) and the agent-contract journey `recall-degraded.json`.
+ - New Postgres arms: `test/e2e/consolidate-divergence-postgres.test.ts`, `test/e2e/write-single-dedup-postgres.test.ts`, `test/e2e/chronicle-max-events-5329-postgres.test.ts`.
+ - `docs/architecture/key-files/core-ai.md` split: providers, recipes and the Voyage width plumbing now live in `core-ai-continued.md`.
+
+ ## [0.60.161.0] - 2026-10-11
+
+ **`embed --max-usd` is enforced, a fence write no longer wipes a database-only page, and write-gate overrides and Git child processes are hardened.**
+
+ An approved `gbrain embed --max-usd` cap was never metered, so a run could spend past it; it is now enforced on every paid call, and `--yes` with no cost estimate runs under the default $5.00 cap. A facts fence write to a page with no file wrote a stub that overwrote the stored body (#6398); it is refused now. Which files can carry a write-gate override is hardened, and Git child processes now get a sanitized environment. Nothing needs doing after you upgrade; to let an embed run spend more than $5.00 without an estimate, pass `--max-usd <usd>`.
+
+ ### Itemized changes
+
+ - `gbrain embed` meters an approved `--max-usd` while it spends, for text, `--slugs`, `--images` (multimodal and OCR) and `--background` runs. A run that reaches its cap keeps what it wrote, exits 11 with reason `cost_cap` and prints the shell-quoted resume command; rerun it with `--max-usd <usd>` to raise the cap. `--yes` with no cost estimate is now capped at the default $5.00. Consent counts a paid multimodal or OCR model when `--images` is set, and `--slugs` stops at the next flag.
+ - A facts fence write to a database-only or soft-deleted page is refused with `db_only_page` instead of writing a stub over it (#6398). Doctor `stub_guard_24h` counts these separately and they do not raise its warning.
+ - Hardened which files can carry a write-gate override; sync, import, file repairs and reconcile apply the same rule.
+ - Git child processes now get a sanitized environment, checkout discovery is stricter, gbrain's hardened Git calls accept a narrower set of arguments, and `eval drift-watch` runs Git without a shell.
+ - `pollCommand` output is shell-quoted and `LLMS_REPO_BASE` is normalized; the paid-consent skill lint says it is a documentation check, not enforcement.
+
+ ### For contributors
+
+ - Flake fixes: the facts drain scheduler returns its tick promise (#6348); the capture-log weight fixture hand-shakes with its artifact (#6312); connector tests run on the production wait budget, with `withPausedOwnerBudget` where a test expects `writer_pending`.
+ - Failure-only diagnostics, issues left open: the write-gate p95 check dumps every round's raw samples (#6430); the history fixture dumps effect, lock and request state (#6345); a shared source-row dump wraps managed connector recovery and every managed-extract-atoms scenario (#6427).
+ - The shard-weight miner fetches unit capture artifacts and serial job logs per job; shard weights refreshed.
+ - `bun run release:restamp` stamps a branch entry headed `## [Unreleased]` to the target version instead of throwing, and `--dry-run` runs the same CHANGELOG rebuild.
+ - The doctor hot-check goldens normalize the UTC day buckets their fixture records at capture time, so they no longer fail after midnight UTC.
+ - Takes test fixtures use placeholder holder names; assertions unchanged.
+ - `test/git-env-guard.test.ts` fails on a new Git spawn that inherits `process.env` unfiltered.
+ - New probes: `test/quarantine-override-tier.test.ts`, `test/quarantine-override-repair-reconcile.test.ts`, `test/fence-write-db-only.test.ts`, `test/doctor-stub-guard.test.ts`, `test/embed-max-usd-metered.serial.test.ts`, `test/embed-consent-multimodal.test.ts`, `test/gateway-ocr-reserve.test.ts`, `test/e2e/embed-background-cap.test.ts`, `test/persistence-effect-git-env.test.ts`, `test/drift-watch-args.test.ts`, `test/w13-small-hardening.test.ts`.
+
+ ## [0.60.160.0] - 2026-10-10
+
+ **Keyword search finds words glued to Chinese, Japanese or Korean text, and you choose which source a self-registered agent writes to when you approve it.**
+
+ A note titled `升级PostgreSQL17` used to be invisible to a keyword search for `PostgreSQL17`, because the index stored the whole glued run as one word. The index now splits wherever CJK text meets Latin letters or digits, and upgrading rebuilds only the pages and chunks that contain such a boundary. When an agent registers itself over OAuth and asks to connect, the approval page now has a "Write source" picker, so you decide which source it reads and writes before it gets a token. On a classic self-hosted Postgres brain, an agent whose page write is refused stops retrying and tells you the real fix: write the file, commit it and run `gbrain sync`. After you upgrade, run `gbrain reindex-search-vector` only if you changed `GBRAIN_FTS_LANGUAGE`; it now rebuilds page vectors too.
+
+ ### Itemized changes
+
+ - **CJK/Latin boundaries in keyword search** (#6370). Every indexing `to_tsvector` and the title query read through a new `gbrain_fts_input()` that inserts a space at each CJK↔ASCII letter or digit boundary; text without CJK is unchanged byte for byte. The upgrade migration rebuilds only rows containing a boundary, in checkpointed batches.
+ - **`gbrain reindex-search-vector` rebuilds page vectors** (#6374). Pages now get the same vector the write path builds, so a language change reaches titles and timelines, not only chunks. A page edited during the rebuild is skipped and reindexed by its own save, and facts you withdrew stay out of the index.
+ - **Choose a self-registered client's source at first consent** (#6202). Clients that registered themselves through dynamic client registration show a "Write source" picker on their first approval, listing your active sources. Approving with or without a change counts as the client's one first consent; later changes go through the Agents page or `gbrain auth rescope --client`. Clients registered before this release keep read-only consent. A migration adds the `oauth_clients.registered_via` marker.
+ - **Classic Postgres write refusals ask instead of retrying** (#6277). `owner_unavailable` with `detail: unbound_source` now renders `retryable: false` and `fix.next: ask_user`, and its guidance says write, commit, `gbrain sync --source <id>`. The guide in [write-refusals](docs/guides/write-refusals.md#unbound-sources-on-postgres) and six skills cover the classic path.
+ - **One JSON document on stdout** (#6386): `gbrain sync status --json`, `gbrain sync unblock --json` and `gbrain embed --facts --json` write their JSON to stdout, not stderr.
+ - **Bootstrap verify waits like a normal write** (#6356): `gbrain bootstrap verify` uses the CLI write wait instead of a fixed 5 seconds, and a write still pending names its next step.
+ - **Local reranker setup** (#6381): the llama-server reranker guide points at the llama.cpp maintainers' model file, the recipe's default names the `qwen3-reranker-0.6b` alias the guide uses, and `gbrain models doctor` reports `config` when the server scores a relevant and an unrelated passage the same.
+ - **Codex session hooks** (#6399): a Codex rollout that has only a header ends as `empty_session`, not `parser_drift`.
+ - **Link validation** (#6266): the link validator resolves relative links from the page's own directory, the same way link extraction does.
+ - **Search latency budget** (#6400): the query-embedding deadline starts at the first embed request, so time spent before it no longer eats the vector search's budget.
+
+ ### For contributors
+
+ - CONTRIBUTING warns before the `git reset --hard` in the line-ending refresh.
+ - Every pglite-snapshot cache key in `e2e.yml`, `test.yml` and `stress.yml` also hashes `src/core/audit/redact-connection-info.ts`, which the schema closure now imports.
+
+ Contributed by @dovstern, @javieraldape, @daveove, @benswinney and @dhruvatr.
## [0.60.159.0] - 2026-10-10
diff --cc docs/architecture/key-files/commands-4-continued.md
index b3381ef049,1dd51a0b5b..b57fa98512
--- a/docs/architecture/key-files/commands-4-continued.md
+++ b/docs/architecture/key-files/commands-4-continued.md
@@@ -25,7 -25,7 +25,7 @@@ Current behavior and load-bearing invar
- `src/commands/reindex-vectors.ts` — `gbrain reindex --vectors [--dry-run] [--json]` (dispatched from cli.ts beside `--aliases`). Lists every HNSW index in the current schema from `pg_indexes` and runs `REINDEX INDEX` on each (`REINDEX INDEX CONCURRENTLY` on Postgres), rebuilding the ANN index from stored vectors with no re-embedding; each rebuild runs inside `withHnswBuildMemory` (vector-index.ts), which sizes PGLite's `maintenance_work_mem` to the graph or refuses with `pglite_vector_index_too_large`. The PGLite WAL-repair notice (`buildWalRepairNotice`) and `gbrain pglite-repair` name it, because a WAL reset does not rebuild indexes (#4616). Tests: `test/embedding-zero-norm-4616.serial.test.ts` on both engines.
- - `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language — bodies mirror the migration's and KEEP the `SET search_path = pg_catalog, public` hardening (CREATE OR REPLACE resets proconfig) — then backfills `pages` (UPDATE-to-self re-fires the trigger) and `content_chunks` (direct vector recompute) in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000) via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`, and rebuilds `idx_facts_fts` (v233) under the language, streaming phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Consent gate (agent operator wave C2): `requireConsent` (effect `destructive`, not plan-bound: derived index, the undo is a re-run under the previous language) — `--yes` or a TTY prompt; `--json` never implies it, and a refusal changes nothing, returns `status: 'confirmation_required'` and exits 3 with the consent payload. Interrupted-run safety: stamps `fts.reindex_in_progress` (= target language, key exported as `FTS_REINDEX_MARKER_KEY` from `fts-language.ts`) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under `backfill.fts_pages.last_id` / `backfill.fts_content_chunks.last_id` (the `checkpointKey` convention from `backfill-base.ts`), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one `engine.transaction()` (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts`.
-- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language through `pageSearchVectorTriggerFnSql`/`chunkSearchVectorTriggerFnSql` (`fts-language.ts`; they KEEP the `SET search_path = pg_catalog, public` hardening, which CREATE OR REPLACE resets) — then backfills `pages` and `content_chunks` through `src/core/search-vector-backfill.ts` in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000). Pages: an UPDATE-to-self of `id` reads each batch (`RETURNING id, timeline, knowledge_revision`; row locks only for that statement), the timeline is sanitized with `sanitizeRemoteBody` as the seal does, and one `UPDATE … FROM unnest(…)` writes `search_vector` through `pageSearchVectorSql` (the seal's own expression), guarded by the revision read, so a page edited in between is skipped (its seal reindexes it) and private, withdrawn, takes or malformed fence text never enters the vector. Chunks: direct vector recompute via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`. Both stream phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Consent gate (agent operator wave C2): `requireConsent` (effect `destructive`, not plan-bound: derived index, the undo is a re-run under the previous language) — `--yes` or a TTY prompt; `--json` never implies it, and a refusal changes nothing, returns `status: 'confirmation_required'` and exits 3 with the consent payload. Interrupted-run safety: stamps `fts.reindex_in_progress` (= target language, key exported as `FTS_REINDEX_MARKER_KEY` from `fts-language.ts`) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under `backfill.fts_pages.last_id` / `backfill.fts_content_chunks.last_id` (the `checkpointKey` convention from `backfill-base.ts`), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one `engine.transaction()` (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts` and `test/reindex-search-vector-pages.serial.test.ts`.
++- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language through `pageSearchVectorTriggerFnSql`/`chunkSearchVectorTriggerFnSql` (`fts-language.ts`; they KEEP the `SET search_path = pg_catalog, public` hardening, which CREATE OR REPLACE resets) — then backfills `pages` and `content_chunks` through `src/core/search-vector-backfill.ts` in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000). Pages: an UPDATE-to-self of `id` reads each batch (`RETURNING id, timeline, knowledge_revision`; row locks only for that statement), the timeline is sanitized with `sanitizeRemoteBody` as the seal does, and one `UPDATE … FROM unnest(…)` writes `search_vector` through `pageSearchVectorSql` (the seal's own expression), guarded by the revision read, so a page edited in between is skipped (its seal reindexes it) and private, withdrawn, takes or malformed fence text never enters the vector. Chunks: direct vector recompute via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`. It then rebuilds `idx_facts_fts` (v236) under the language (an index build, no row rewrite). Both stream phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Consent gate (agent operator wave C2): `requireConsent` (effect `destructive`, not plan-bound: derived index, the undo is a re-run under the previous language) — `--yes` or a TTY prompt; `--json` never implies it, and a refusal changes nothing, returns `status: 'confirmation_required'` and exits 3 with the consent payload. Interrupted-run safety: stamps `fts.reindex_in_progress` (= target language, key exported as `FTS_REINDEX_MARKER_KEY` from `fts-language.ts`) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under `backfill.fts_pages.last_id` / `backfill.fts_content_chunks.last_id` (the `checkpointKey` convention from `backfill-base.ts`), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one `engine.transaction()` (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts` and `test/reindex-search-vector-pages.serial.test.ts`.
- `src/commands/init-mode-picker.ts` — install-time mode recommendation, downstream-input cost matrix, and mandatory operator choice. Mode summaries describe payload knobs only. Expansion follows the command (`query` on unless opted out; `search` and memory verbs off), not the chosen mode; provider charges and downstream prompt caching are disclosed separately from GBrain result caching.
diff --cc docs/architecture/key-files/core-utilities-1.md
index 3121ffc362,bccaab2dc5..9a95738226
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@@ -44,7 -44,7 +44,7 @@@ The `src/core/cycle.ts` entry is on it
- `src/core/filing-audit.ts` + `skills/_brain-filing-rules.json` — Check 6 of `check-resolvable`. Parses `writes_pages:` / `writes_to:` frontmatter on skills and audits their filing claims against the filing-rules JSON (error severity). Internal `parseFrontmatter` is a thin wrapper over the shared `src/core/skill-frontmatter.ts` parser so both filing-audit and skill-brain-first read the same shape (`tools?`, `triggers?`, `brain_first?: 'exempt'`, typed `brain_first_typo`) from one source of truth.
- - `src/core/fts-language.ts` — Single source for the Postgres text-search configuration name. `getFtsLanguage()` resolves `GBRAIN_FTS_LANGUAGE` (default `english`), validates against `/^[a-z][a-z0-9_]*$/` (tsvector config names can't be bound as parameters, so the value is interpolated into raw SQL — the allowlist regex is the injection guard; invalid values warn once and fall back to `english`), cached on first read (`resetFtsLanguageCache()` is test-only). Used by both engines' keyword search, the `configurable_fts_language` migration and `reindex-search-vector`; `factsFtsDocument`/`factsFtsIndexSql` build the facts keyword document and `idx_facts_fts` (v233). Pinned by `test/fts-language.serial.test.ts` + `test/fts-language-migration.serial.test.ts` (includes the `'; DROP TABLE pages; --` injection cases).
-- `src/core/fts-language.ts` — Single source for the FTS configuration name (write side, #6370: `engines-2.md`). `getFtsLanguage()` resolves `GBRAIN_FTS_LANGUAGE` (default `english`), validates against `/^[a-z][a-z0-9_]*$/` (tsvector config names can't be bound as parameters, so the value is interpolated into raw SQL — the allowlist regex is the injection guard; invalid values warn once and fall back to `english`), and caches on first read (`resetFtsLanguageCache()` is test-only). Consumed by both engines' `searchKeyword`/`searchKeywordChunks` (`websearch_to_tsquery` query side), the `configurable_fts_language` migration, and `reindex-search-vector` (write-side trigger functions). Pinned by `test/fts-language.serial.test.ts` + `test/fts-language-migration.serial.test.ts` (includes the `'; DROP TABLE pages; --` injection cases).
++- `src/core/fts-language.ts` — Single source for the FTS configuration name (write side, #6370: `engines-2.md`). `getFtsLanguage()` resolves `GBRAIN_FTS_LANGUAGE` (default `english`), validates against `/^[a-z][a-z0-9_]*$/` (tsvector config names can't be bound as parameters, so the value is interpolated into raw SQL — the allowlist regex is the injection guard; invalid values warn once and fall back to `english`), and caches on first read (`resetFtsLanguageCache()` is test-only). Consumed by both engines' `searchKeyword`/`searchKeywordChunks` (`websearch_to_tsquery` query side), the `configurable_fts_language` migration, and `reindex-search-vector` (write-side trigger functions). `factsFtsDocument`/`factsFtsIndexSql` build the facts keyword document and `idx_facts_fts` (v236). Pinned by `test/fts-language.serial.test.ts` + `test/fts-language-migration.serial.test.ts` (includes the `'; DROP TABLE pages; --` injection cases).
- `src/core/latin-fold.ts` — leaf text primitive (no engine/graph imports): `NON_DECOMPOSING_LATIN`, the lowercase-keyed table of the eleven Latin stroke/bar/ligature letters Unicode gives no decomposition (đ ð ø ł ħ ŧ ı ß æ œ þ), + `foldNonDecomposingLatin(s)`. Call it AFTER lowercasing and AFTER the combining-mark strip so composed forms reduce in one pass (ǿ → ø → o). Consumers: `entities/resolve.ts:slugify` (entity fallback slugs — pre-fold `Đăng Example` collided onto `ang-example` and an all-stroke name slugged to empty) and `link-extraction.ts:normalizeBasename` (basename-index keys + dir-hint candidates). Deliberately NOT applied to `sync.ts:slugifySegment` — the page-slug grammar keeps these letters (#3417) — so the dir-hint candidate step in `makeResolver` / the FS resolver tries both forms.
diff --cc docs/protocol/MEMORY_VERBS_v1.md
index 6453b311f6,e61f0c07a7..7fb7001e4f
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@@ -181,11 -166,8 +181,11 @@@ Response — an additive SUPERSET of th
| `protocol_version` | int | always present (every verb, every call) |
| `facts[]` | array | the base fact fields, PLUS per fact: `fact_id` (opaque STRING — the value `forget` accepts; the numeric `id` remains alongside it for compatibility) and `provenance` (the stored source attribution) |
| `total` | int | count of facts returned |
- | `results[]` | array | search arm only: `slug`, `title`, `chunk`, `evidence`, `create_safety`, `provenance` (origin page slug) |
+ | `results[]` | array | search arm only: `slug`, `title`, `chunk`, `evidence`, `create_safety`, `provenance` (origin page slug), `source_id` (additive since #4830: the source the hit came from; on a federated read each hit names its own source, and a hit that carries none is labeled only when the read's scope is a single source, never a blind `default`) |
| `search_degraded` | string? | present when keyword-only fallback fired |
+| `facts_order` | string | `relevance` (question passed) or `newest` |
+| `facts[].relevance` | number? | question calls only: the ranking score (about 0 to 2.1); not a probability and not comparable across calls |
+| `facts_degraded` | object? | question calls only: `reason` (`keyword_only_no_embedding_provider`, `keyword_only_embedding_disabled`, `embed_timeout`, `embed_unavailable`, `no_query_terms`, `facts_embedding_column_missing`) and `unembedded` (facts in scope without a comparable embedding; the `facts_unembedded` notice carries the `gbrain embed --stale --facts` preview) |
| `budget_tokens` / `budget_used` / `dropped_count` | int? | present for a positive finite numeric budget, including when its floor is zero |
| `budget_packing` | object? | present only when a valid `budget_policy` is supplied; effective policy and per-arm accounting |
diff --cc llms-full.txt
index 34d5a0d853,602c171e61..24e8cc8d16
--- a/llms-full.txt
+++ b/llms-full.txt
@@@ -8698,11 -8733,8 +8748,11 @@@ Response — an additive SUPERSET of th
| `protocol_version` | int | always present (every verb, every call) |
| `facts[]` | array | the base fact fields, PLUS per fact: `fact_id` (opaque STRING — the value `forget` accepts; the numeric `id` remains alongside it for compatibility) and `provenance` (the stored source attribution) |
| `total` | int | count of facts returned |
- | `results[]` | array | search arm only: `slug`, `title`, `chunk`, `evidence`, `create_safety`, `provenance` (origin page slug) |
+ | `results[]` | array | search arm only: `slug`, `title`, `chunk`, `evidence`, `create_safety`, `provenance` (origin page slug), `source_id` (additive since #4830: the source the hit came from; on a federated read each hit names its own source, and a hit that carries none is labeled only when the read's scope is a single source, never a blind `default`) |
| `search_degraded` | string? | present when keyword-only fallback fired |
+| `facts_order` | string | `relevance` (question passed) or `newest` |
+| `facts[].relevance` | number? | question calls only: the ranking score (about 0 to 2.1); not a probability and not comparable across calls |
+| `facts_degraded` | object? | question calls only: `reason` (`keyword_only_no_embedding_provider`, `keyword_only_embedding_disabled`, `embed_timeout`, `embed_unavailable`, `no_query_terms`, `facts_embedding_column_missing`) and `unembedded` (facts in scope without a comparable embedding; the `facts_unembedded` notice carries the `gbrain embed --stale --facts` preview) |
| `budget_tokens` / `budget_used` / `dropped_count` | int? | present for a positive finite numeric budget, including when its floor is zero |
| `budget_packing` | object? | present only when a valid `budget_policy` is supplied; effective policy and per-arm accounting |
diff --cc scripts/module-size-limits.tsv
index 4f7077c1fe,0c2619fbf7..673a372826
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@@ -28,15 -28,15 +28,15 @@@ src/core/minions/queue.ts 2528 ratchet
src/commands/init.ts 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
- src/commands/bootstrap.ts 2134 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)
+ src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)
src/core/minions/worker.ts 1774 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler)
- src/commands/sources.ts 2054 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row
- src/core/link-extraction.ts 2358 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass)
+ src/commands/sources.ts 2059 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row
+ src/core/link-extraction.ts 2379 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator
src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
- src/commands/hook.ts 1926 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import
+ src/commands/hook.ts 1928 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift
src/core/chunkers/code.ts 1602 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); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
- src/core/config.ts 1940 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +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); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts)
-src/core/config.ts 1940 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +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); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts)
++src/core/config.ts 1941 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +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); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts)
src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 683 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)
diff --cc skills/skills.lock.json
index 78d2654ab4,d1765e0ea1..69794209ef
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@@ -44,7 -44,7 +44,7 @@@
"concept-synthesis/routing-eval.jsonl": "96dbd7d9c1b606e9e06262d0c06282399741e2bccb8eeb7b9ca88c20f44cda0e",
"context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207",
"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",
- "conventions/agent-operator-protocol.md": "e061724e481af6bb22ea8253ff927816865e8f4095a3eef93fced18ec499e9f2",
- "conventions/agent-operator-protocol.md": "c9865fa1b903edfdf445c0723c2f9c62d91aa9d0f9b21264788f02ae6b42967c",
++ "conventions/agent-operator-protocol.md": "d22b616c90d84d7035cf2c56ed2c59d361b06a0499f548ae21e81bd23823efce",
"conventions/brain-first.md": "d9b18321150830d38586f5bd23ce9de735f08ac3b54d7ac63bc3184a61e17ef1",
"conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6",
"conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",
diff --cc src/commands/reindex-search-vector.ts
index 1de754f6f7,faab842cc8..8cd1ef31f1
--- a/src/commands/reindex-search-vector.ts
+++ b/src/commands/reindex-search-vector.ts
@@@ -1,7 -1,6 +1,7 @@@
/**
- * `gbrain reindex-search-vector` — recreate FTS trigger functions and
- * backfill existing rows under the language configured via
+ * `gbrain reindex-search-vector` — recreate FTS trigger functions,
+ * backfill existing rows and rebuild the facts keyword index
- * (`idx_facts_fts`, migration v233) under the language configured via
++ * (`idx_facts_fts`, migration v236) under the language configured via
* GBRAIN_FTS_LANGUAGE.
*
* Why this command exists: schema migration v123 (configurable_fts_language)
@@@ -47,7 -46,7 +47,7 @@@
*/
import type { BrainEngine } from '../core/engine.ts';
- import { getFtsLanguage, factsFtsIndexSql, FTS_REINDEX_MARKER_KEY } from '../core/fts-language.ts';
-import { getFtsLanguage, FTS_REINDEX_MARKER_KEY, pageSearchVectorTriggerFnSql, chunkSearchVectorTriggerFnSql } from '../core/fts-language.ts';
++import { getFtsLanguage, factsFtsIndexSql, FTS_REINDEX_MARKER_KEY, pageSearchVectorTriggerFnSql, chunkSearchVectorTriggerFnSql } from '../core/fts-language.ts';
import { checkpointKey } from '../core/backfill-base.ts';
import { consentGate } from '../core/consent-cli.ts';
import type { ConsentEnv } from '../core/consent.ts';
@@@ -264,20 -190,9 +191,12 @@@ export async function runReindexSearchV
progress.finish();
progress.start('reindex_search_vector.chunks', chunksCount);
- await batchedBackfill(
- engine,
- 'content_chunks',
- `search_vector =
- setweight(to_tsvector('${lang}', COALESCE(doc_comment, '')), 'A') ||
- setweight(to_tsvector('${lang}', COALESCE(symbol_name_qualified, '')), 'A') ||
- setweight(to_tsvector('${lang}', COALESCE(chunk_text, '')), 'B')`,
- n => progress.tick(n)
- );
+ await backfillChunkVectors(engine, { lang, checkpoint: CHECKPOINT_NAME.content_chunks, tick: n => progress.tick(n) });
progress.finish();
+ // The facts keyword index is an expression index under a literal language: rebuild it (no row rewrite).
+ for (const sql of factsFtsIndexSql(lang)) await engine.executeRaw(sql);
+
// Both backfills returned: the index is whole again under `lang`.
await engine.unsetConfig(checkpointKey(CHECKPOINT_NAME.pages));
await engine.unsetConfig(checkpointKey(CHECKPOINT_NAME.content_chunks));
diff --cc src/core/behavior-change-notice.ts
index 7b7d35b545,3485c1b1e5..3f24a75e7f
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@@ -380,8 -383,25 +383,27 @@@ export const BEHAVIOR_CHANGES: Readonly
{ since: '0.60.159.0', text: 'Captured session files (compaction segments, Stop-hook turns and SessionEnd transcripts) now record the source their session started under and are filed there, in a `sourced/` folder of the corpus directory, instead of under whatever source the sweep runs for. Files written before this upgrade on a brain with more than one source are held until you say where they belong: `gbrain doctor` names them, `gbrain sweep --assign-corpus <source>` previews and `--apply` maps them. A serve asked to file a session under another source refuses instead of rerouting it.' },
{ since: '0.60.159.0', text: 'On OpenClaw 2026.9.x, which no longer passes a session file to the context engine, compaction now banks a gbrain checkpoint segment again by reading the transcript through the host\'s session-transcript runtime. Each compaction leaves an `openclaw-compact` entry in the hooks heartbeat, and `gbrain doctor` warns when a week of compactions banked nothing.' },
{ since: '0.60.159.0', text: 'Transcript pages now keep every message whole: a message longer than 4,000 characters was cut there, and now continues in the next block under the same speaker. Re-ingesting a transcript or export re-imports the pages that had long messages (and re-extracts their facts if fact extraction is on). Chat connector syncs also keep retrying a conversation that failed until it imports and report `partial` with `unresolved` meanwhile (`gbrain doctor` warns the archive is incomplete). Conversations synced earlier are not repaired on their own: after asking the user, run `gbrain connectors sync <provider> --full` once.' },
+ // Fix wave 13 PR1.
+ { since: '0.60.161.0', text: '`gbrain embed --max-usd <usd>` is now enforced while the run spends, for text, `--slugs`, `--images` (multimodal and OCR) and `--background` runs; before, an approved cap was never metered. A run approved with `--yes` and no cost estimate now runs under the default $5.00 cap instead of none. A run that reaches its cap keeps the embeddings already written, exits 11 with reason `cost_cap` and prints the command that resumes; raise the cap by rerunning it with `--max-usd <usd>`.' },
+ { since: '0.60.161.0', text: 'A facts fence write to a page that exists only in the database (no file, or a soft-deleted page) is now refused with `db_only_page` instead of writing a stub file that then overwrote the stored body and timeline (#6398). Doctor `stub_guard_24h` counts these refusals separately and they do not raise its warning.' },
+ { since: '0.60.161.0', text: 'Hardened which files can carry a write-gate override: an override in a file is kept only for an owner-tier source (operator_curated or above), on sync, import, file repairs and reconcile alike; otherwise the content gate decides, and a file repair of such a file refuses as an overlay.' },
+ { since: '0.60.161.0', text: 'Git child processes gbrain runs now get a sanitized environment, checkout discovery is stricter, and gbrain\'s hardened Git calls accept a narrower set of arguments.' },
+ // Wave 14 PR3 (GBRA-79); `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.162.0', text: 'Dream `propose_takes` no longer proposes takes from atom pages (`type: atom`) or from any page the dream cycle wrote and stamped `dream_generated`; the source page an atom was extracted from is still a candidate, so nothing a person wrote stops being graded. New atoms now carry `dream_generated: true`, so facts extraction, the chronicle and transcript discovery skip them like other derived pages. Expect fewer proposals per cycle on brains with many atoms.' },
+ { since: '0.60.162.0', text: 'The dream `consolidate` phase no longer merges two facts that differ in a negation, number, date or amount ("Invoice A due Monday" and "Invoice B due Tuesday" stay two facts), and facts without a typed metric now need a 0.95 embedding match (the explicit-duplicate bar) instead of the 0.85 `cycle.consolidate.cluster_threshold`, which keeps governing typed metric facts. Expect fewer takes from untyped event facts. `gbrain dream --phase consolidate --dry-run` lists the clusters it would write under `details.clusters`. Facts an earlier run wrongly merged keep the `valid_until` that run stamped: previous intervals were not retained, so there is no exact undo; `gbrain recall` still returns the facts, and `remember … replaces` records a correction.' },
+ { since: '0.60.162.0', text: 'A write tool call (`add_timeline_entry`, `put_page`, `remember`, every tool marked mutating) that names a parameter the tool does not declare is now refused `invalid_params` with nothing written, in every `mcp.strict_params` mode; the suggestion names the submitted key and the declared one (`content` → `detail` on `add_timeline_entry`). Before, the default warn mode committed the row with the misnamed field dropped. Reads keep the warn grace period.' },
+ { since: '0.60.162.0', text: 'A `remember` (or any single-fact write) that repeats a fact already stored word for word for the same entity, or with no resolved entity at all, now returns the existing fact (`status: duplicate`) instead of inserting a second row, including on brains without an embedding key; a remote or unattributed caller never dedups against a fact that came from a private source. A write whose entity could not be resolved and fell back to slugifying the name now stores the fact with no entity instead of minting a placeholder entity slug, so the stub guard no longer refuses later writes about that name; search and `recall` still find the fact by its text.' },
+ { since: '0.60.162.0', text: 'A top-level call statement in a JavaScript, TypeScript, TSX, Python or Ruby file (a `describe(...)` / `it(...)` block, `app.use(...)`, `print(helper())`, `RSpec.describe ... do`) is now its own chunk, `symbol_type` `module` and `symbol_name` `__module__`, so the calls inside it get edges: `code-callers helper` lists the test body as `<file-basename>::__module__`. Files with such statements gain chunks, so the next `gbrain sync` walks each source once and re-chunks and re-embeds only its files in those five languages (priced by the cost gate as `grammar_drift`); `gbrain reindex-code` does the same now. Definition-only files keep their chunks and vectors.' },
+ { since: '0.60.162.0', text: 'The entity counters in `get_health` / `gbrain health` (`entity_page_count`, `link_coverage`, `timeline_coverage`, `most_connected`) and doctor\'s `graph_coverage` and `orphan_ratio` gates now count the page types the active schema pack declares with `primitive: entity` (`yc`, `civic` and `organization` included on gbrain-base; a custom pack\'s own entity types; `person` or `company` only while the pack does not reclassify them), resolved per source when sources carry their own pack. Brains whose entities are pack types move from 0 entities and `null` ratios to real numbers, and a doctor score can drop where coverage is low. A pack that does not load now reports `entity_types_status: pack_unavailable` with 0 entities and a `graph_coverage` warn instead of counting the old hardcoded list.' },
+ { since: '0.60.162.0', text: 'Dream `synthesize_concepts` now writes one concept page for spellings of a label that differ only by hyphens, underscores or dots (`network-effects`, `network_effects`, `networkeffects`): the spelling that already has a live `concepts/` page wins, otherwise the one most atoms use (a tie goes to the hyphenated form), and the other spellings redirect to it for that run without any page write. Two spellings that both already have live pages (`re-sign` / `resign`, `co-op` / `coop`) are kept apart; merging those stays the human redirect path (`merged_into` / `aliases`). Existing duplicate pages are not merged for you: `details.folded_spellings` on the phase receipt names each fold.' },
+ { since: '0.60.162.0', text: 'A `put_page` (or `gbrain put`) of a page that already exists, sent without `expected_revision` or `force`, is now refused with its own code `revision_required` instead of `revision_conflict`; the message, the refusal and the fix (read the page, resend with its revision) are unchanged. A stale `expected_revision` is still `revision_conflict`. A client that switched on `revision_conflict` to decide between "re-read and merge" and "I forgot the precondition" can now branch on the code (#5385).' },
+ { since: '0.60.162.0', text: 'A wikilink or markdown link whose target the source policy resolved into another source (`link_resolution.cross_source` on, or a `[[source:slug]]` reference from a federated source) is now written by `put_page`, `capture`, the managed stale pass and the source reconciliation sweep, the way `extract links --source db` already wrote it; before, those writers dropped the approved edge and the next pass deleted the rows the extractor had admitted. With the flag off and a non-federated source nothing changes, and the write receipt now counts the drops as `auto_links.skipped_cross_source`. A reader granted one source still never sees the other source\'s endpoint. Watch `gbrain get-links` on pages that cite another source: the edges you opted into now appear.' },
+ // Memory proof wave (#6066).
+ { since: '0.60.164.0', text: '`query` now adds saved facts that match the question as rows of their own, at most 3, only in row and token capacity the pages left free, so no page row is pushed out. A fact row has `result_type: "fact"`, `fact_id` and a `follow_up` recall call, and never a page slug or id; a page row whose claim a newer saved fact replaced carries `superseded_claim`. It adds up to three database lookups per query and no model call. Remote callers see only facts whose source pages they could read. `gbrain config set search.query_facts_arm false` restores the previous results.' },
+ { since: '0.60.164.0', text: 'A saved fact now replaces a similar older fact by embedding similarity only when the brain\'s embedding model has a measured threshold. The default voyage-4 at 1024 dimensions keeps 0.95 and decides as before. With any other model, both facts stay active and the conflict review sweep judges the pair where it is on; exact-text duplicates are still merged. Doctor `supersession_calibration` names the command that measures a threshold (about a cent of synthetic text, no brain content), and `gbrain config set facts.supersession_thresholds \'{"<provider:model@dims>": <threshold>}\'` registers one.' },
+ { since: '0.60.164.0', text: 'Pinned questions replace `dream.auto_think`, which never ran in the dream cycle. On upgrade, each question in `dream.auto_think.questions` becomes an inactive pinned question that keeps its cooldown, model and commit setting, and a positive `dream.auto_think.budget` becomes `cycle.standing_questions.budget_usd`; nothing refreshes or spends until you activate a pin. `gbrain questions list` shows the ids, and `gbrain questions pin --id <id>` activates one, after which the dream cycle\'s `standing_questions` phase refreshes it under that budget. `gbrain dream --phase auto_think` now exits with a usage error naming the replacement.' },
+ // Memory proof wave 2 W1 (question-ranked recall); `since` is a placeholder equal to the branch's VERSION (it must not exceed it) until the merge-slot stamp.
- { since: '0.60.159.0', text: '`recall` takes an optional `question` and returns saved facts ranked by relevance to it (facts below the match threshold are left out); calls without it still return the newest facts, every response now says `facts_order`, and a call that passes only `query` carries a `recall_hint` notice. `gbrain recall --question` passes the question instead of reading its value as an entity name. In `query`, the facts of an entity the question names come only from that entity page\'s own source, and the temporal fact reserve (`search.temporal_fact_reserve`, off by default) scores with the same question scorer: whole-word matches, and a long fact\'s word matches count for less.' },
++ { since: '0.60.164.0', text: '`recall` takes an optional `question` and returns saved facts ranked by relevance to it (facts below the match threshold are left out); calls without it still return the newest facts, every response now says `facts_order`, and a call that passes only `query` carries a `recall_hint` notice. `gbrain recall --question` passes the question instead of reading its value as an entity name. In `query`, the facts of an entity the question names come only from that entity page\'s own source, and the temporal fact reserve (`search.temporal_fact_reserve`, off by default) scores with the same question scorer: whole-word matches, and a long fact\'s word matches count for less.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --cc src/core/cli-flag-registry.generated.ts
index a86305945b,31e4fc1acc..8d906ad80e
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@@ -47,7 -47,7 +47,7 @@@ export const CLI_FLAG_REGISTRY: Record<
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
++ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@@ -70,9 -70,9 +70,9 @@@
'frontmatter': ['--allow-catch-all', '--batch', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--full-name', '--get', '--git-common-dir', '--help', '--importable', '--include-ambiguous', '--include-catch-all', '--json', '--literal-pathspecs', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],
'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
- 'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
+ 'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--content-root', '--db-only', '--dest', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--fix', '--force', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--show-toplevel', '--skip-embed-check', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
- 'init': ['--access', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
++ 'init': ['--access', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
diff --cc src/core/embedding-migration.ts
index e1572adc38,956aa1d0b6..b2763b0168
--- a/src/core/embedding-migration.ts
+++ b/src/core/embedding-migration.ts
@@@ -304,9 -309,6 +304,9 @@@ async function transitionDimPinnedColum
const columnType: 'vector' | 'halfvec' = udt.toLowerCase() === 'halfvec' ? 'halfvec' : 'vector';
const opclass = columnType === 'halfvec' ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
+ // #4252: the DROP COLUMN cascade also takes every btree/partial index that
- // reads the column (facts' idx_facts_unembedded, v233); replayed after the rebuild.
++ // reads the column (facts' idx_facts_unembedded, v236); replayed after the rebuild.
+ const dependents = await embeddingDependentIndexes(tx, table);
await tx.executeRaw(`DROP INDEX IF EXISTS ${indexName}`);
await tx.executeRaw(`ALTER TABLE ${table} DROP COLUMN IF EXISTS embedding`);
await tx.executeRaw(`ALTER TABLE ${table} ADD COLUMN embedding ${columnType}(${targetDim})`);
diff --cc src/core/fts-language.ts
index 2c9b04f5ea,087baddb25..6247d40e91
--- a/src/core/fts-language.ts
+++ b/src/core/fts-language.ts
@@@ -107,22 -109,83 +109,103 @@@ export function applyFtsLanguagePolicy(
return sql.replaceAll(`to_tsvector('${DEFAULT_LANGUAGE}',`, `to_tsvector('${lang}',`);
}
+/**
+ * The facts keyword document: fact text plus the entity slug's words, under
+ * a literal text search configuration so `idx_facts_fts` can serve it (an
+ * expression index matches only the same literal configuration, never a
+ * bound parameter). The migration, `gbrain reindex-search-vector` and the
+ * question-recall keyword arm all build it here.
+ */
+export function factsFtsDocument(alias: string | null, lang: string = getFtsLanguage()): string {
+ const col = (c: string) => alias ? `${alias}.${c}` : c;
+ return `to_tsvector('${lang}'::regconfig, ${col('fact')} || ' ' || replace(COALESCE(${col('entity_slug')}, ''), '-', ' '))`;
+}
+
+/** Recreate `idx_facts_fts` (GIN over active facts) under `lang`; an index build, no row rewrite. */
+export function factsFtsIndexSql(lang: string = getFtsLanguage()): string[] {
+ return [
+ 'DROP INDEX IF EXISTS idx_facts_fts',
+ `CREATE INDEX idx_facts_fts ON facts USING gin (${factsFtsDocument(null, lang)}) WHERE expired_at IS NULL`,
+ ];
+}
++
+ const CJK_CLASS = `[${CJK_SLUG_CHARS}]`;
+
+ /**
+ * `gbrain_fts_input(text)`: the text every indexing `to_tsvector` and the
+ * title query's `websearch_to_tsquery` read (#6370). Postgres' default parser
+ * treats Han, Kana and Hangul as letters, so `升级PostgreSQL17后查询Redis7`
+ * is one lexeme and keyword search for `Redis7` misses it. Two passes insert
+ * a space at every CJK→ASCII-alnum and ASCII-alnum→CJK boundary (two passes,
+ * not lookbehind, so both engines run the same regex). A byte-for-byte no-op
+ * on text without CJK, and idempotent. One copy of this DDL: the schema
+ * build splices it into src/schema.sql and the fts-cjk-boundary migration
+ * applies it.
+ */
+ export const FTS_INPUT_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_fts_input(t text) RETURNS text
+ LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE SET search_path = pg_catalog
+ AS $fn$
+ SELECT regexp_replace(regexp_replace(t, '(${CJK_CLASS})([A-Za-z0-9])', '\\1 \\2', 'g'), '([A-Za-z0-9])(${CJK_CLASS})', '\\1 \\2', 'g')
+ $fn$;`;
+
+ /** POSIX regex (SQL `~`) matching text that holds a CJK/ASCII-alnum boundary `gbrain_fts_input` splits. */
+ export const FTS_CJK_BOUNDARY_REGEX = `${CJK_CLASS}[A-Za-z0-9]|[A-Za-z0-9]${CJK_CLASS}`;
+
+ /**
+ * The page keyword vector every sealed writer stores: the title (weight A) and
+ * the SANITIZED timeline (weight C, bound by the caller; never the raw column,
+ * which can hold private or withdrawn fence text). `title` and `timeline` are
+ * SQL expressions. Shared by the seal, the import seal,
+ * `reindex-search-vector` and the fts-cjk-boundary migration, so they cannot
+ * drift.
+ */
+ export function pageSearchVectorSql(title: string, timeline: string, lang: string = getFtsLanguage()): string {
+ return `setweight(to_tsvector('${lang}',gbrain_fts_input(COALESCE(${title},''))),'A') || setweight(to_tsvector('${lang}',gbrain_fts_input(${timeline}::text)),'C')`;
+ }
+
+ /** The chunk keyword vector, over a row's own columns (`NEW.` in the trigger, bare in a backfill). */
+ export function chunkSearchVectorSql(lang: string, row = ''): string {
+ return `setweight(to_tsvector('${lang}', gbrain_fts_input(COALESCE(${row}doc_comment, ''))), 'A') ||
+ setweight(to_tsvector('${lang}', gbrain_fts_input(COALESCE(${row}symbol_name_qualified, ''))), 'A') ||
+ setweight(to_tsvector('${lang}', gbrain_fts_input(COALESCE(${row}chunk_text, ''))), 'B')`;
+ }
+
+ /**
+ * The two search_vector trigger functions under `lang`, for every runtime
+ * rewrite (`reindex-search-vector`, the fts-cjk-boundary migration). Their
+ * bodies are byte-identical to src/schema.sql's for 'english' (pinned by
+ * test/fts-cjk-boundary.test.ts), so the blob replay that every boot runs
+ * after a migration leaves the catalog unchanged. #2704: compiled_truth is not
+ * indexed (it overflows the 1MB tsvector cap). `SET search_path = pg_catalog,
+ * public` keeps the v120/#1647 hardening, which CREATE OR REPLACE would
+ * otherwise reset.
+ */
+ export function pageSearchVectorTriggerFnSql(lang: string): string {
+ return `CREATE OR REPLACE FUNCTION update_page_search_vector() RETURNS trigger SET search_path = pg_catalog, public AS $$
+ DECLARE
+ timeline_text TEXT;
+ BEGIN
+ SELECT coalesce(string_agg(summary || ' ' || detail, ' '), '')
+ INTO timeline_text
+ FROM timeline_entries
+ WHERE page_id = NEW.id;
+
+ NEW.search_vector :=
+ setweight(to_tsvector('${lang}', gbrain_fts_input(coalesce(NEW.title, ''))), 'A') ||
+ setweight(to_tsvector('${lang}', gbrain_fts_input(coalesce(NEW.timeline, ''))), 'C') ||
+ setweight(to_tsvector('${lang}', gbrain_fts_input(coalesce(timeline_text, ''))), 'C');
+
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;`;
+ }
+
+ export function chunkSearchVectorTriggerFnSql(lang: string): string {
+ return `CREATE OR REPLACE FUNCTION update_chunk_search_vector() RETURNS TRIGGER SET search_path = pg_catalog, public AS $fn$
+ BEGIN
+ NEW.search_vector :=
+ ${chunkSearchVectorSql(lang, 'NEW.')};
+ RETURN NEW;
+ END;
+ $fn$ LANGUAGE plpgsql;`;
+ }
diff --cc src/core/schema-migrations/latest.generated.ts
index 7cdcfafcf0,d98387962c..697e00869b
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@@ -4,4 -4,4 +4,4 @@@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
- export const LATEST_SCHEMA_VERSION = 233;
-export const LATEST_SCHEMA_VERSION = 235;
++export const LATEST_SCHEMA_VERSION = 236;
diff --cc src/core/schema-migrations/registry.generated.ts
index 5612e410b9,89a9ca545c..0530d9b1e8
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@@ -232,8 -232,10 +232,11 @@@ import { v228 } from './v228-memory-pur
import { v229 } from './v229-trust-allow-rules.ts';
import { v230 } from './v230-trust-generation.ts';
import { v231 } from './v231-fact-purge-lookup-indexes.ts';
- import { v232 } from './v232-pinned-questions.ts';
- import { v233 } from './v233-facts-question-recall-indexes.ts';
+ import { v232 } from './v232-fts-cjk-boundary.ts';
+ import { v233 } from './v233-oauth-client-registered-via.ts';
+ import { v234 } from './v234-persistence-git-durability.ts';
+ import { v235 } from './v235-pinned-questions.ts';
++import { v236 } from './v236-facts-question-recall-indexes.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@@ -466,4 -468,6 +469,7 @@@ export const MIGRATIONS: Migration[] =
v231,
v232,
v233,
+ v234,
+ v235,
++ v236,
];
diff --cc src/core/schema-migrations/v236-facts-question-recall-indexes.ts
index 136a0e9339,0000000000..daa5819a11
mode 100644,000000..100644
--- a/src/core/schema-migrations/v236-facts-question-recall-indexes.ts
+++ b/src/core/schema-migrations/v236-facts-question-recall-indexes.ts
@@@ -1,35 -1,0 +1,35 @@@
+import type { Migration } from './types.ts';
+import { factsFtsIndexSql, getFtsLanguage } from '../fts-language.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.
- export const v233: Migration = {
- version: 233,
++export const v236: Migration = {
++ version: 236,
+ name: 'facts_question_recall_indexes',
+ // recall `question` (src/core/search/fact-relevance.ts) on a large brain.
+ //
+ // idx_facts_fts: the keyword arm matches every active fact's text and
+ // entity words; unindexed it is a to_tsvector scan of the whole source
+ // (about 450 ms at 100k facts on Postgres). The text search configuration
+ // must be a literal for the planner to match an expression index, so the
+ // handler builds it under GBRAIN_FTS_LANGUAGE, as v123 does for the trigger
+ // functions, and `gbrain reindex-search-vector` rebuilds it when the
+ // language changes. An expression index, not a stored tsvector column: a
+ // column backfill rewrites every fact row and its HNSW entry (about 7
+ // minutes at 100k facts); the index build reads the rows once (about 2 s).
+ //
+ // idx_facts_unembedded + idx_facts_embedding_model: `facts_degraded.unembedded`
+ // counts the active facts the cosine arm cannot compare (no vector or a
+ // stale text hash; another embedding model) on every call; unindexed it is
+ // an md5 scan of the whole source (about 130 ms at 100k facts).
+ //
+ // Re-running drops and rebuilds idx_facts_fts and skips the others: safe.
+ idempotent: true,
+ sql: '',
+ handler: async (engine) => {
+ for (const sql of factsFtsIndexSql(getFtsLanguage())) await engine.executeRaw(sql);
+ await engine.executeRaw(`CREATE INDEX IF NOT EXISTS idx_facts_unembedded ON facts (source_id)
+ WHERE expired_at IS NULL AND (embedding IS NULL OR embedded_text_hash IS DISTINCT FROM md5(fact))`);
+ await engine.executeRaw(`CREATE INDEX IF NOT EXISTS idx_facts_embedding_model ON facts (source_id, embedding_model) WHERE expired_at IS NULL`);
+ },
+};
diff --cc test/embedding-migration.test.ts
index fa7ed44193,dc436aadab..34b2b49a4d
--- a/test/embedding-migration.test.ts
+++ b/test/embedding-migration.test.ts
@@@ -383,17 -383,6 +383,17 @@@ describe('applyEmbeddingMigration', ()
expect(await embeddingColWidth('facts')).toBe(target);
});
- test('#4252: a dim change keeps the facts btree indexes that read the embedding column (v233 idx_facts_unembedded)', async () => {
++ test('#4252: a dim change keeps the facts btree indexes that read the embedding column (v236 idx_facts_unembedded)', async () => {
+ const target = colDim === 512 ? 256 : 512;
+ const factIndexes = async () => (await engine.executeRaw<{ indexname: string }>(
+ `SELECT indexname FROM pg_indexes WHERE tablename = 'facts' AND indexname = 'idx_facts_unembedded'`)).map(r => r.indexname);
+ expect(await factIndexes()).toEqual(['idx_facts_unembedded']);
+ const plan = await planEmbeddingMigration(engine, { to: 'openai:text-embedding-3-small', dim: target });
+ expect((await applyEmbeddingMigration(engine, plan)).status).toBe('applied');
+ expect(await embeddingColWidth('facts')).toBe(target);
+ expect(await factIndexes()).toEqual(['idx_facts_unembedded']);
+ });
+
test('post-transition the query cache can actually STORE a row at the new width', async () => {
const target = colDim === 512 ? 256 : 512;
const plan = await planEmbeddingMigration(engine, {
diff --cc test/fixtures/goldens/cli/tools-json.json
index 0cf3a09798,498bba1064..0e23c5c296
--- 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": 227725,
- "stdoutSha256": "24cb0e080443004b0f3ff1da85ceba65b562d28c79c0cedd6bf4cb3943f68a7e",
- "stdoutBytes": 230356,
- "stdoutSha256": "053248a9f24a3417e826c0985c79f12d11381b60bc50b1e26ab51e5e6929f1cc",
++ "stdoutBytes": 230438,
++ "stdoutSha256": "9a3dc5c29fd6080932aa7461f7ca2e9f2579a917182e92565c312b781c99fc10",
"toolNames": [
"remember",
"entity",
diff --cc test/fixtures/goldens/migrations/records.json
index 09fb0ecc8c,ec4f85dd59..044505f621
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@@ -1,6 -1,6 +1,6 @@@
{
"golden": {
- "count": 228,
- "count": 230,
++ "count": 231,
"gaps": [
17,
18,
@@@ -23,10 -26,13 +26,14 @@@
"PERSISTENCE_SYNC_WATERMARK_INDEX": "93523954a30e8483717f07ec97a3e0cd062b15d8a60cc759281054b06c23bb40",
"TOKEN_TTL_MAX_SECONDS": "f4a45bec6ec0bacc859dc57732ceb76cec7eb72f242b5a6c89d47190d0525ab4",
"TOKEN_TTL_MIN_SECONDS": "441d8ce6bd21f753de90abd3013eaa9992a469ea60c590f1005533618199aa25",
+ "backfillChunkVectors": "1c8cc09a28aa3e906fe2f112b71cd3aa61f750a99984e35a029cff9458272aa1",
+ "backfillPageVectors": "a325a5eee3bab49723af311f21b38a1ee4a0eaff1fb3c7e1539aa4dcb287ed66",
"buildIndexOnline": "ed5378b90f24f7d662e02865cf73af4248e348002661f8fbfd8ee1087c60a3e5",
+ "checkpointKey": "337ef776b18f428542093e27c4d570249d6a5856e5a17e4499d26a22877af34b",
+ "chunkSearchVectorTriggerFnSql": "93ed4e29aa058949621b4198fe1ec317218f4b9ec0db0626ec6dc7001032047d",
"clampOAuthTokenTtls": "b1e94ea8f5b3c3870a56b0f6d00d0a274c2e9dcad912b828848aec250732645f",
"dropInvalidConcurrentIndex": "6864d844b7dfb2fbecdd0fb9c73e06248473376feb794b3fe58f036c70d2d44c",
+ "factsFtsIndexSql": "2bfacc9979a0962b592b2edd3541508259e21f42156fb94d042566461925286c",
"getFtsLanguage": "0d790b4c4af1f67a2a1bbd59470beb13f434917b381931baf8404a41c5d903db",
"grantFromRow": "2d0603bb0f964d7e45e04aa76bac54cd4f6f63c91a8d9f028b60b4792bc1695e",
"hnswMaxDimsForType": "a187cdcc520f813b7c39da97ce53da58509232ed9f851627ef41abfe1b68bd26",
@@@ -43,7 -50,7 +51,7 @@@
"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5",
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"
},
- "latest": 233,
- "latest": 235,
++ "latest": 236,
"records": [
{
"handler": {
@@@ -3475,27 -3547,7 +3548,27 @@@
"sqlFor": "absent",
"transaction": "absent",
"verify": "absent",
- "version": 232
+ "version": 235
+ },
+ {
+ "handler": {
+ "form": "arrow",
+ "helpers": [
+ "factsFtsIndexSql",
+ "getFtsLanguage"
+ ],
+ "sha256": "264dd41685abb98743d788ee00d1c0467d29c85989c95156bd54ea0dd0421a08"
+ },
+ "idempotent": true,
+ "name": "facts_question_recall_indexes",
+ "sql": {
+ "length": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
- "version": 233
++ "version": 236
}
],
"versions": [
@@@ -3726,7 -3778,9 +3799,10 @@@
230,
231,
232,
- 233
+ 233,
+ 234,
- 235
++ 235,
++ 236
]
},
"normalizer": "migrations-record-v1"
diff --cc test/recall-question.test.ts
index 46a20e3ed1,0000000000..1523fde9d8
mode 100644,000000..100644
--- a/test/recall-question.test.ts
+++ b/test/recall-question.test.ts
@@@ -1,377 -1,0 +1,377 @@@
+/**
+ * recall `question` (memory proof wave 2, W1): active facts ranked by
+ * relevance to the question instead of recency, under recall's unchanged read
+ * policy. Pins the ranking, the empty answer, every row of the parameter
+ * contract, the read-policy composition (trust floor, quarantine and rederive
+ * hiding, remote world-only, the private-provenance filter and its operator
+ * opt-out), row-shape parity with the newest path, the degraded paths, the
+ * recall_hint notice, and that the question's embedding goes through the
+ * gateway's query-embedding cache.
+ *
+ * The embedder is a deterministic bag-of-words transport ($0, no keys) shared
+ * by the stored fact vectors and the question.
+ *
+ * Both engines: PGLite always, Postgres through
+ * test/e2e/recall-question-postgres.test.ts.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import type { Notice } from '../src/core/agent-output.ts';
+import { configureGateway, getEmbeddingModel, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { REMOTE_PRIVATE_PAGES_KEY, __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { QUESTION_ADMISSION_KEY, QUESTION_MAX_CHARS } from '../src/core/facts/question-recall.ts';
+import { recallInteropNotices } from '../src/core/interop-notices.ts';
+import { factsFtsDocument, getFtsLanguage } from '../src/core/fts-language.ts';
+import { withTrustPromotion } from '../src/core/persistence/context.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type R = Record<string, any>;
+const ENTITY = 'people/alice-example';
+const OTHER = 'people/charlie-example';
+const SESSION = 'sess-question';
+const COFFEE = 'Does Alice Example drink dark roast coffee in the morning?';
+const noopLogger = { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} };
+
+function bagOfWords(text: string, dims: number): number[] {
+ const v = new Array<number>(dims).fill(0);
+ for (const token of text.toLowerCase().split(/[^a-z0-9]+/).filter(t => t.length >= 3)) {
+ let h = 2166136261;
+ for (const ch of token) h = Math.imul(h ^ ch.charCodeAt(0), 16777619) >>> 0;
+ v[h % dims]! += 1;
+ }
+ const norm = Math.hypot(...v) || 1;
+ return v.map(x => x / norm);
+}
+
+/** Fact markers in a payload, in order of appearance (every fact text starts with one). */
+const markers = (facts: R[]) => facts.map(f => String(f.fact).split(' ')[0]);
+
+for (const kind of testBackends()) {
+ describe(`recall question ranking (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let dims = 1536;
+ let providerCalls: string[] = [];
+ const ids: Record<string, number> = {};
+ let notices: Notice[] = [];
+
+ const ctxOf = (remote: boolean | undefined): OperationContext => ({
+ engine, config: {} as GBrainConfig, logger: noopLogger, dryRun: false, remote: remote as boolean,
+ transport: 'stdio', sourceId: 'default', emitNotice: (n: Notice) => notices.push(n),
+ } as OperationContext);
+ const local = () => ctxOf(false);
+ const untrusted = () => [ctxOf(true), ctxOf(undefined)];
+ const recall = async (ctx: OperationContext, p: R) => (await operationsByName.recall.handler(ctx, p)) as R;
+
+ function keyed(): void {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: dims, env: { OPENAI_API_KEY: 'sk-fake' } });
+ __setEmbedTransportForTests((async (args: { values: string[] }) => {
+ providerCalls.push(...args.values);
+ return { embeddings: args.values.map(v => bagOfWords(v, dims)) };
+ }) as never);
+ providerCalls = [];
+ }
+ function keyless(): void {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ }
+
+ async function fact(name: string, f: {
+ text: string; entity?: string | null; visibility?: 'world' | 'private'; provenance?: string; daysAgo: number; embed?: boolean; session?: string;
+ }): Promise<void> {
+ const vec = f.embed === false ? null : `[${bagOfWords(f.text, dims).join(',')}]`;
+ const [row] = await engine.executeRaw<{ id: string | number }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, valid_from, created_at, source, source_session, source_markdown_slug,
+ embedding, embedding_model, embedded_text_hash, embedded_at)
+ VALUES ('default', $1, $2, 'fact', $3, now() - ($4 || ' days')::interval, now() - ($4 || ' days')::interval, 'test', $5, $6,
+ $7::text::vector, CASE WHEN $7::text IS NULL THEN NULL ELSE $8 END, CASE WHEN $7::text IS NULL THEN NULL ELSE md5($2) END,
+ CASE WHEN $7::text IS NULL THEN NULL ELSE now() END)
+ RETURNING id`,
+ [f.entity === undefined ? ENTITY : f.entity, f.text, f.visibility ?? 'world', String(f.daysAgo), f.session ?? null, f.provenance ?? 'meetings/open-sync', vec, getEmbeddingModel()]);
+ ids[name] = Number(row.id);
+ }
+
+ beforeAll(async () => {
+ if (kind === 'postgres') {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ } else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ const [col] = await engine.executeRaw<{ dims: number }>(`SELECT a.atttypmod AS dims FROM pg_attribute a WHERE a.attrelid = to_regclass('facts') AND a.attname = 'embedding'`);
+ dims = Number(col!.dims);
+ keyed();
+ await engine.putPage(ENTITY, { type: 'person', title: 'Alice Example', compiled_truth: 'Alice is a founder.' });
+ await engine.putPage(OTHER, { type: 'person', title: 'Charlie Example', compiled_truth: 'Charlie is an engineer.' });
+ await engine.putPage('meetings/open-sync', { type: 'meeting', title: 'open sync', compiled_truth: 'An open meeting.' });
+ await engine.putPage('meetings/secret-sync', { type: 'meeting', title: 'secret sync', compiled_truth: 'A private meeting.', frontmatter: { visibility: 'private' } });
+ await engine.putPage('notes/scraped', { type: 'note', title: 'scraped listing', compiled_truth: 'Scraped listing.' });
+ await fact('roast', { text: 'ROAST Alice Example drinks dark roast coffee every morning', daysAgo: 30, session: SESSION });
+ await fact('tea', { text: 'TEA Alice Example switched her afternoon coffee for green tea', daysAgo: 20 });
+ await fact('secret', { text: 'SECRETPROV Alice Example coffee roast supplier is a private contract', provenance: 'meetings/secret-sync', daysAgo: 25 });
+ await fact('private', { text: 'PRIVVIS Alice Example coffee roast budget', visibility: 'private', daysAgo: 26 });
+ await fact('scraped', { text: 'SCRAPED Alice Example coffee roast review', provenance: 'notes/scraped', daysAgo: 27 });
+ await fact('unembedded', { text: 'NOVEC Alice Example roast coffee grinder', daysAgo: 28, embed: false });
+ await fact('offsite', { text: 'OFFSITE The quarterly offsite moved to Denver', entity: null, daysAgo: 1 });
+ await fact('hiring', { text: 'HIRING Charlie Example opened two backend roles', entity: OTHER, daysAgo: 2 });
+ await fact('stuffed', {
+ text: `STUFFED alice example drink dark roast coffee morning ${Array.from({ length: 120 }, (_, i) => `filler${i.toString(36)}word`).join(' ')}`,
+ entity: null, daysAgo: 3, embed: false,
+ });
+ }, 180_000);
+ afterAll(async () => { keyless(); await close?.(); });
+ beforeEach(() => { notices = []; __resetPrivateVisibilityCacheForTests(); keyed(); });
+
+ test('without question: facts stay newest first and facts_order says so', async () => {
+ const r = await recall(local(), {});
+ expect(r.facts_order).toBe('newest');
+ expect(markers(r.facts).slice(0, 2)).toEqual(['OFFSITE', 'HIRING']);
+ expect(r.facts.every((f: R) => !('relevance' in f))).toBe(true);
+ });
+
+ test('with question: relevant facts first, irrelevant newer facts left out, each row carries relevance (descending)', async () => {
+ const r = await recall(local(), { question: COFFEE });
+ expect(r.facts_order).toBe('relevance');
+ const got = markers(r.facts);
+ expect(got[0]).toBe('ROAST');
+ expect(got).not.toContain('OFFSITE');
+ expect(got).not.toContain('HIRING');
+ const scores = r.facts.map((f: R) => f.relevance);
+ expect(scores.every((s: unknown) => typeof s === 'number' && s > 0)).toBe(true);
+ expect([...scores].sort((a, b) => b - a)).toEqual(scores);
+ });
+
+ test('a below-threshold question returns an empty list, not the newest facts', async () => {
+ const r = await recall(local(), { question: 'zymurgy xylophone quokka' });
+ expect(r.facts).toEqual([]);
+ expect(r.total).toBe(0);
+ expect(r.facts_order).toBe('relevance');
+ });
+
+ test('limit caps the ranked list at the top rows', async () => {
+ const r = await recall(local(), { question: COFFEE, limit: 1 });
+ expect(markers(r.facts)).toEqual(['ROAST']);
+ });
+
+ test('read policy: local sees private-provenance and private facts; remote (true and unset) hides both', async () => {
+ const localGot = markers((await recall(local(), { question: COFFEE })).facts);
+ expect(localGot).toEqual(expect.arrayContaining(['SECRETPROV', 'PRIVVIS']));
+ for (const c of untrusted()) {
+ const remote = markers((await recall(c, { question: COFFEE })).facts);
+ expect(remote).toContain('ROAST');
+ expect(remote).not.toContain('SECRETPROV');
+ expect(remote).not.toContain('PRIVVIS');
+ }
+ });
+
+ test('read policy: the operator opt-out (search.remote_private_pages=visible) shows the private-sourced world fact remotely, never the private fact', async () => {
+ await engine.setConfig(REMOTE_PRIVATE_PAGES_KEY, 'visible');
+ __resetPrivateVisibilityCacheForTests();
+ try {
+ for (const c of untrusted()) {
+ const remote = markers((await recall(c, { question: COFFEE })).facts);
+ expect(remote).toContain('SECRETPROV');
+ expect(remote).not.toContain('PRIVVIS');
+ }
+ } finally {
+ await engine.executeRaw('DELETE FROM config WHERE key = $1', [REMOTE_PRIVATE_PAGES_KEY]);
+ __resetPrivateVisibilityCacheForTests();
+ }
+ });
+
+ test('read policy: a quarantined provenance page hides its fact, local and remote', async () => {
+ await engine.executeRaw(`UPDATE pages SET frontmatter = COALESCE(frontmatter, '{}'::jsonb) || '{"quarantine": {"reason": "junk_pattern", "detail": "test"}}'::jsonb WHERE slug = 'notes/scraped'`);
+ try {
+ expect(markers((await recall(local(), { question: COFFEE })).facts)).not.toContain('SCRAPED');
+ for (const c of untrusted()) expect(markers((await recall(c, { question: COFFEE })).facts)).not.toContain('SCRAPED');
+ } finally {
+ await engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter - 'quarantine' WHERE slug = 'notes/scraped'`);
+ }
+ expect(markers((await recall(local(), { question: COFFEE })).facts)).toContain('SCRAPED');
+ });
+
+ test('read policy: the trust floor (min_trust) and the rederive hold apply to the ranked list', async () => {
+ await engine.transaction(tx => withTrustPromotion(tx, 'user_confirmed', () => tx.executeRaw('UPDATE facts SET trust_tier = $1 WHERE id = $2', ['external_untrusted', ids.tea])));
+ await engine.executeRaw(`INSERT INTO needs_rederive (derived_table, derived_id, source_id, reason) VALUES ('facts', $1, 'default', 'test')`, [String(ids.scraped)]);
+ try {
+ const all = markers((await recall(local(), { question: COFFEE })).facts);
+ expect(all).toContain('TEA');
+ expect(all).not.toContain('SCRAPED');
+ const floored = markers((await recall(local(), { question: COFFEE, min_trust: 'unknown' })).facts);
+ expect(floored).not.toContain('TEA');
+ expect(floored).toContain('ROAST');
+ } finally {
+ await engine.executeRaw(`DELETE FROM needs_rederive WHERE derived_table = 'facts' AND derived_id = $1`, [String(ids.scraped)]);
+ await engine.transaction(tx => withTrustPromotion(tx, 'user_confirmed', () => tx.executeRaw('UPDATE facts SET trust_tier = $1 WHERE id = $2', ['agent_written', ids.tea])));
+ }
+ });
+
+ test('the question path returns a subset of the newest path under the same filters, local and remote', async () => {
+ for (const ctx of [local(), ...untrusted()]) {
+ const newest = new Set((await recall(ctx, { entity: ENTITY, limit: 100 })).facts.map((f: R) => f.id));
+ const ranked = (await recall(ctx, { entity: ENTITY, question: COFFEE, limit: 100 })).facts.map((f: R) => f.id);
+ expect(ranked.length).toBeGreaterThan(0);
+ for (const id of ranked) expect(newest.has(id)).toBe(true);
+ }
+ });
+
+ test('row shape: question rows carry every newest-path key plus relevance, with the same normalized timestamps', async () => {
+ const newest = (await recall(local(), { limit: 100 })).facts as R[];
+ const ranked = (await recall(local(), { question: COFFEE })).facts as R[];
+ const byId = new Map(newest.map(f => [f.id, f]));
+ for (const row of ranked) {
+ const twin = byId.get(row.id)!;
+ expect(Object.keys(row).filter(k => k !== 'relevance').sort()).toEqual(Object.keys(twin).sort());
+ const { relevance: _r, ...rest } = row;
+ expect(rest).toEqual(twin);
+ }
+ });
+
+ test('filters compose inside the pool: entity, session_id, since and grep rank within the filtered set', async () => {
+ expect(markers((await recall(local(), { question: 'backend roles', entity: OTHER })).facts)).toEqual(['HIRING']);
+ expect(markers((await recall(local(), { question: 'backend roles', entity: ENTITY })).facts)).toEqual([]);
+ expect(markers((await recall(local(), { question: COFFEE, session_id: SESSION })).facts)).toEqual(['ROAST']);
+ const since = markers((await recall(local(), { question: COFFEE, since: '22d' })).facts);
+ expect(since).toContain('TEA');
+ expect(since).not.toContain('ROAST');
+ expect(markers((await recall(local(), { question: COFFEE, grep: 'green tea' })).facts)).toEqual(['TEA']);
+ });
+
+ test('invalid combinations refuse with the corrected call as fix.mcp', async () => {
+ const refusal = async (p: R) => {
+ try { await recall(local(), p); } catch (e) { return e as OperationError; }
+ throw new Error('expected a refusal');
+ };
+ const sup = await refusal({ question: COFFEE, supersessions: true });
+ expect(sup.code).toBe('invalid_params');
+ expect(sup.fix?.mcp).toEqual({ tool: 'recall', arguments: { question: COFFEE } });
+ const exp = await refusal({ question: COFFEE, include_expired: true, entity: ENTITY });
+ expect(exp.code).toBe('invalid_params');
+ expect(exp.fix?.mcp).toEqual({ tool: 'recall', arguments: { question: COFFEE, entity: ENTITY } });
+ const long = await refusal({ question: 'coffee '.repeat(400) });
+ expect(long.code).toBe('invalid_params');
+ expect(String((long.fix?.mcp?.arguments as R).question).length).toBe(QUESTION_MAX_CHARS);
+ });
+
+ test('the admission rule is configurable between the two preregistered rule sets', async () => {
+ await engine.setConfig(QUESTION_ADMISSION_KEY, 'facts_arm');
+ try {
+ const r = await recall(local(), { question: COFFEE });
+ expect(r.facts_order).toBe('relevance');
+ expect(markers(r.facts)).toContain('ROAST');
+ expect(markers(r.facts)).not.toContain('OFFSITE');
+ } finally {
+ await engine.executeRaw('DELETE FROM config WHERE key = $1', [QUESTION_ADMISSION_KEY]);
+ }
+ });
+
+ test('term stuffing: a fact holding every question word plus many others does not pass on term share', async () => {
+ keyless();
+ const r = await recall(local(), { question: COFFEE });
+ expect(markers(r.facts)).toContain('ROAST');
+ expect(markers(r.facts)).not.toContain('STUFFED');
+ });
+
+ test('keyless: term-share ranking with facts_degraded naming the reason; a stopword-only question returns no_query_terms', async () => {
+ keyless();
+ const r = await recall(local(), { question: COFFEE });
+ expect(r.facts_order).toBe('relevance');
+ expect(r.facts_degraded).toEqual({ reason: 'keyword_only_no_embedding_provider' });
+ expect(markers(r.facts)).toContain('ROAST');
+ const none = await recall(local(), { question: 'what is the' });
+ expect(none.facts).toEqual([]);
+ expect(none.facts_degraded).toEqual({ reason: 'no_query_terms' });
+ const stages = recallInteropNotices('recall', none, {}, { question: 'what is the' }, { transport: 'stdio' });
+ expect(stages.find(n => n.code === 'degraded_recall')?.why).toContain('no_query_terms');
+ });
+
+ test('unembedded facts are counted over the authorized pool and come with the preview-then-approve embed fix', async () => {
+ const r = await recall(local(), { question: COFFEE });
+ expect(r.facts_degraded?.unembedded).toBe(2);
+ const notice = notices.find(n => n.code === 'facts_unembedded')!;
+ expect(notice.fix?.argv).toEqual(['gbrain', 'embed', '--stale', '--facts', '--source', 'default', '--dry-run']);
+ expect(notice.fix?.then?.consent).toEqual(['paid']);
+ await fact('privnovec', { text: 'PRIVNOVEC Alice Example coffee note', visibility: 'private', daysAgo: 29, embed: false });
+ try {
+ expect((await recall(local(), { question: COFFEE })).facts_degraded?.unembedded).toBe(3);
+ for (const c of untrusted()) expect((await recall(c, { question: COFFEE })).facts_degraded?.unembedded).toBe(2);
+ } finally {
+ await engine.executeRaw('DELETE FROM facts WHERE id = $1', [ids.privnovec]);
+ }
+ });
+
- test('unembedded also counts another embedding model and a stale text hash, through the v233 indexes', async () => {
++ test('unembedded also counts another embedding model and a stale text hash, through the v236 indexes', async () => {
+ await fact('othermodel', { text: 'OTHERMODEL Alice Example coffee roast', daysAgo: 31 });
+ await fact('stalehash', { text: 'STALEHASH Alice Example coffee roast', daysAgo: 32 });
+ await engine.executeRaw(`UPDATE facts SET embedding_model = 'other:model' WHERE id = $1`, [ids.othermodel]);
+ await engine.executeRaw(`UPDATE facts SET fact = fact || ' edited' WHERE id = $1`, [ids.stalehash]);
+ try {
+ expect((await recall(local(), { question: COFFEE })).facts_degraded?.unembedded).toBe(4);
+ } finally {
+ await engine.executeRaw('DELETE FROM facts WHERE id = ANY($1::bigint[])', [[ids.othermodel, ids.stalehash]]);
+ }
+ });
+
- test('v233: the keyword document matches idx_facts_fts and the uncomparable probes have their indexes', async () => {
++ test('v236: the keyword document matches idx_facts_fts and the uncomparable probes have their indexes', async () => {
+ const names = (await engine.executeRaw<{ indexname: string }>(
+ `SELECT indexname FROM pg_indexes WHERE tablename = 'facts' AND indexname IN ('idx_facts_fts', 'idx_facts_unembedded', 'idx_facts_embedding_model') ORDER BY indexname`)).map(r => r.indexname);
+ expect(names).toEqual(['idx_facts_embedding_model', 'idx_facts_fts', 'idx_facts_unembedded']);
+ // The planner matches an expression index structurally; the deparsed query expression must equal the index's.
+ const plan = (await engine.executeRaw<Record<string, string>>(
+ `EXPLAIN SELECT f.id FROM facts f WHERE ${factsFtsDocument('f')} @@ plainto_tsquery('${getFtsLanguage()}'::regconfig, 'coffee')`)).map(r => Object.values(r)[0]).join('\n');
+ const queried = /to_tsvector\(.*\)\) @@/.exec(plan)?.[0].replace(/ @@$/, '');
+ const [{ def }] = await engine.executeRaw<{ def: string }>(`SELECT pg_get_indexdef('idx_facts_fts'::regclass) AS def`);
+ expect(queried).toBeTruthy();
+ expect(def).toContain(`gin (${queried})`);
+ expect(def).toContain('WHERE (expired_at IS NULL)');
+ const sent: string[] = [];
+ const real = engine.executeRaw;
+ engine.executeRaw = function (this: BrainEngine, sql: string, params?: unknown[]) { sent.push(sql); return real.call(this, sql, params); } as typeof real;
+ try {
+ await recall(local(), { question: COFFEE });
+ } finally {
+ engine.executeRaw = real;
+ }
+ expect(sent.find(q => q.includes('plainto_tsquery'))).toContain(`${factsFtsDocument('f')} @@ `);
+ // The keyword arm and the uncomparable count each run under a per-call custom plan (cached generic plans nest the policy joins).
+ expect(sent.filter(q => q === 'SET LOCAL plan_cache_mode = force_custom_plan')).toHaveLength(2);
+ });
+
+ test('the question embedding goes through the gateway cache: a repeat recall, a query+question recall and a query followed by recall embed once', async () => {
+ await recall(local(), { question: COFFEE });
+ await recall(local(), { question: COFFEE });
+ expect(providerCalls.filter(v => v.includes(COFFEE))).toHaveLength(1);
+ keyed();
+ await recall(local(), { question: COFFEE, query: COFFEE });
+ expect(providerCalls.filter(v => v.includes(COFFEE))).toHaveLength(1);
+ keyed();
+ await operationsByName.query.handler(local(), { query: COFFEE });
+ expect(providerCalls.filter(v => v.includes(COFFEE))).toHaveLength(1);
+ const ranked = await recall(local(), { question: COFFEE });
+ expect(providerCalls.filter(v => v.includes(COFFEE))).toHaveLength(1);
+ expect(ranked.facts_order).toBe('relevance');
+ expect(ranked.facts_degraded?.reason).toBeUndefined();
+ });
+
+ test('recall_hint: query without question or fact filter names question and carries the retry call; otherwise no hint', async () => {
+ const r = await recall(local(), { query: COFFEE });
+ expect(r.facts_order).toBe('newest');
+ const hint = notices.find(n => n.code === 'recall_hint')!;
+ expect(hint.kind).toBe('info');
+ expect(hint.fix?.mcp).toEqual({ tool: 'recall', arguments: { query: COFFEE, question: COFFEE } });
+ for (const p of [{ query: COFFEE, question: COFFEE }, { query: COFFEE, entity: ENTITY }, { query: COFFEE, since: '30d' }, {}]) {
+ notices = [];
+ await recall(local(), p);
+ expect(notices.some(n => n.code === 'recall_hint')).toBe(false);
+ }
+ });
+ });
+}
diff --cc test/reindex-search-vector.serial.test.ts
index 08c911f3c4,773f586210..b2886b80d8
--- a/test/reindex-search-vector.serial.test.ts
+++ b/test/reindex-search-vector.serial.test.ts
@@@ -121,9 -121,8 +121,9 @@@ describe('runReindexSearchVector', () =
expect(result.chunksUpdated).toBe(200);
// 1 inventory + 2 CREATE + 2 backfill batches (mock returns no rows, so
- // the keyset loop terminates after the first batch per table) = 5 calls
- expect(state.calls.length).toBe(5);
+ // the keyset loop terminates after the first batch per table) + the facts
- // keyword index drop and rebuild (v233) = 7 calls
++ // keyword index drop and rebuild (v236) = 7 calls
+ expect(state.calls.length).toBe(7);
expect(state.calls[1]).toContain('CREATE OR REPLACE FUNCTION update_page_search_vector');
expect(state.calls[1]).toContain("to_tsvector('pt_br'");
expect(state.calls[2]).toContain('CREATE OR REPLACE FUNCTION update_chunk_search_vector');
diff --cc test/schema-catalog-golden.test.ts
index 0c7da1863d,75eab87c67..c3e9b24bd0
--- a/test/schema-catalog-golden.test.ts
+++ b/test/schema-catalog-golden.test.ts
@@@ -108,9 -108,7 +108,9 @@@ describe('PGLite catalog goldens (E4)'
for (const path of ['engine', 'blob'] as const) {
const diff = diffCatalogSnapshots(requireCaptured(`${path}:default`), requireCaptured(`${path}:fts-portuguese`));
expect(diff.length).toBeGreaterThan(0);
- // The facts table (and its v233 index) comes from migrations, so only engine init has it.
- expect([...new Set(diff.map((d) => d.section))]).toEqual(['functions']);
++ // The facts table (and its v236 index) comes from migrations, so only engine init has it.
+ expect([...new Set(diff.map((d) => d.section))].sort()).toEqual(path === 'engine' ? ['functions', 'indexes'] : ['functions']);
+ expect(diff.filter((d) => d.section === 'indexes').map((d) => d.key)).toEqual(path === 'engine' ? ['idx_facts_fts'] : []);
expect(diff.every((d) => d.kind === 'changed')).toBe(true);
}
});