Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(recall): question-ranked recall — shared fact scorer, recall_hint, v233 fact indexes
garrytan29656cbdf1e0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a6b34fd988..1a0abbd76c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,29 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.154.0] - 2026-10-10++**`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 v0.60.154.0++`gbrain upgrade` applies migration v233 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 Postgres brain a ranked recall takes 122 ms at p95 (115 ms for a remote caller, 13 ms with `entity`). Migration v233 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, and the vector lookup now uses the facts HNSW index. 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.153.0] - 2026-10-10**A repeated query in a long-running `gbrain serve` no longer waits on the embedding provider: about 110–150 ms faster per repeat, and 75 of 100 provider embed calls avoided on a realistic mix. Cold `search`, `query` and `stats` start 100–175 ms faster on both engines. Doctor's `eval_drift` stops paying 0.2–0.4 s per run on a freshly cloned or just-pulled source checkout. Rankings and output are unchanged.**diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 8c446885b1..b6e144c47c 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -20,7 +20,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `test/cli-contract.test.ts` — D5: `--help` contract for every command-table record (exit 0, non-stub, curated flags only, `--yes` shown where parsed) against the shrink-only `test/fixtures/cli-contract/help-baseline.json`, and one success + one failure row per `json`-declared record.- `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook. The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.test.ts`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.test.ts`) has one row per declaration, `<command> <sub>` included.- `scripts/check-agent-contract.ts` — syntax-only AST scanner (≈2 s) in `bun run verify` and `guards-manifest.tsv` (fixtures `test/fixtures/guards/check-agent-contract.ts/`). Rules: suggestion-less `OperationError`, `throw new Error` in ops/mcp/handlers, hand-built `fix`/`next_action` command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside `interaction.ts`/`consent.ts`, raw "re-run with --yes" strings outside `consent.ts`, `stdio: 'inherit'` outside `spawnCliChild`, marker literals outside `agent-output.ts`/`agent-markers.ts`, `verify.argv` naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Two more never-baselined rules keep every refusal's next step site-specific: `defaulted-suggestion` (a function that builds an error through `opError`, `new OperationError`, `usageError`, `invalidParam` or `hostOnlyError` from a `*suggestion`/`*hint` parameter with a default, an optional marker or a `??` fallback) and `generic-suggestion` (a suggestion whose whole text is a denylisted phrase such as "see --help", "check your input" or "try again", at a constructor or at a call site of a file-local funnel). `funnelSites(files?)` lists every funnel call site (`invalid`, `fail`, `usage`, `deny`, …) with its literal suggestion texts, resolving file-level string constants; `test/helpers/agent-envelope.ts` (`expectFunnelSuggestions`, `envelopeFor`, `caught`) drives the per-funnel table tests in each module's owner test. Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.-- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`.+- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled` in `search_degraded` or `facts_degraded.reason`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallStagesFor` maps recall's `search_degraded` and `facts_degraded.reason` (question ranking) to stages. `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`.- `src/mcp/status-mode.ts` + `src/commands/serve-status.ts` + `src/commands/serve-http-status.ts` + `src/core/serve-http-status-marker.ts` — F4 status-only serve, stdio and `--http`. cli.ts hands over a host-brain `serve` (not `--fail-fast`/`GBRAIN_SERVE_FAIL_FAST=1`) with no config, an unreadable config, a missing or repair-failed brain, or a PGLite lock held by a live holder; `runStatusModeServe` is the one entry point for both transports and logs `serve_status_mode_enter` / `serve_status_mode_recovered` (`reason`, `transport`, `elapsed_ms`) as one-line JSON on stderr. `probeStatus` reads config + `peekLock` only; `reprobe(state, connect)` is the one re-probe (no lock attempt while blocked, `resetReadinessMemo()` before the throw-only connect from `src/core/engine-connect.ts`); a check that must run on every re-probe hooks the `probeAgain` wrapper in `runStatusModeServe`. stdio: a gated lazy engine (`createDegradedEngine` with the configured `kind`, reconnect `statusReconnect`, ≤1 attempt / 5 s inside tool calls) marked with `StatusModeState`; `statusPayload` → `{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}`. `--http`: `runHttpStatusServe` binds one `node:http` listener with a mutable handler (`/health` 503 + `Retry-After: 5` + `instance`; `/mcp` stateless SDK server with only `gbrain_status`; every other route a 503 `serve_status_only` envelope), each response built from the allowlist in `httpStatusPayload`/`httpStatusEnvelope` with `reason` collapsed to `unavailable`; a single-flight chained 5 s tick runs the re-probe, and on a connect `runServe(..., { adoptServer })` builds the full app and swaps the handler on the same listener; a failed build disconnects the engine and stays status-only (`brain_unopenable`); SIGINT/SIGTERM during a recovery waits for it, then closes once. The marker `GBRAIN_HOME/serve-http-status-<port>.json` `{pid, instance_nonce, brain_id, bind, port, reason, since}` is removed only by its own instance; live = PID alive and written after the last boot (readiness), plus `/health` 503 with the nonce within 500 ms (`verifiedStatusMarkers`, doctor, which deletes dead markers). `statusFix(state, transport)` words the fix for how the server re-checks. A recovered HTTP server answers authenticated `gbrain_status` (read scope, never listed) with `status: recovered`. Tests: `test/serve-status-mode.serial.test.ts` (stdio recover → recall; shared `serve --http`; no brain → init; `--fail-fast`; stdio transition lines; Postgres `--http` keeps the degraded path), `test/serve-http-status-mode.serial.test.ts` (HTTP journey, doctor, thin client, recovery with re-auth, `serve_port_in_use`, no-config recovery, stale marker, single-flight tick, failed build, shutdown during recovery, two-port markers).- `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming itself and its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`). Where `request_tools` is callable and session widening is on, the fix is `request_tools {surface:'full'}` (`next: run`, argv kept); otherwise the CLI equivalent with actor `user` and a `user_message`; `why` names the lasting route (`GBRAIN_SURFACE=full` in the harness's per-server env, or a `--surface full` re-registration) and that an inherited `GBRAIN_SURFACE` overrides a pinned `--surface`. Read-only access never offers a widen. HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills. Test: `test/hidden-tool-hint.test.ts`.diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.mdindex 2b3e0986f3..b3381ef049 100644--- a/docs/architecture/key-files/commands-4-continued.md+++ b/docs/architecture/key-files/commands-4-continued.md@@ -12,7 +12,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/trust.ts` — `gbrain trust review|confirm|release|drop|revert|explain|allow|disable` (#5575 DX-7; `backfill` is dispatched by `src/cli/commands/trust.ts`). `runOwnerAction` previews, asks for the typed token when the action raises trust, then applies bound to the preview; `review --accept-all` needs a filter and takes one confirmation (DX-15). The backend is the local engine, or `maybeDelegateTrust` (called from `src/cli.ts` before connecting) routes through a resident PGLite owner's administration socket with the prompt in the invoking CLI (DX-2). `confirmTierCrossingAccepts` puts tier-crossing `decide proposals accept` through the same rule; `quarantine release|drop` are aliases (`src/cli/commands/quarantine.ts`). Refusals render through `writeCliError` (exit 3 for consent refusals).- `src/commands/quarantine.ts` — `gbrain quarantine <list|clear|scan>` operator surface for the content-quality gate. `list [--json] [--include-flagged]` paginates `listPages` and reports quarantined (HIDDEN) pages, optionally also `content_flag` (FLAGGED, searchable) pages. `clear <slug> [--force] [--no-embed] [--json]` drops both markers and re-imports through the normal pipeline so the page re-chunks + re-embeds and becomes searchable; the gate re-runs on import so genuinely-junk pages re-quarantine (exit 1) unless `--force` sets `GBRAIN_NO_SANITY=1` for that one import. `scan [--limit N] [--apply] [--no-embed] [--json]` re-assesses already-ingested pages so junk predating the gate gets marked (unchanged content short-circuits normal sync, so it never re-assesses otherwise); dry-run uses the SAME effective `content_sanity` config thresholds `--apply` will use, idempotent (skips already-marked pages), `--apply` re-imports with `forceRechunk` to set markers + (for quarantine) drop chunks. Dispatched in `cli.ts`. Pinned by `test/quarantine-cli.test.ts`. #6259: `clear` reads one snapshot (page, tags, revision) and, on a managed brain, publishes through `submitPageMutation` with that `expected_revision` (a concurrent edit is a `revision_conflict`, a pending receipt is reported as pending); `--force` writes a `quarantine_override` (see `src/core/quarantine-override.ts`) instead of disabling the gate, never mutation `force`. `scan --apply` refuses `writer_coordinator_required` on a managed brain. It is a router (`QUARANTINE_SUBCOMMANDS`, `printUsage`). Tests: `test/quarantine-override.serial.test.ts`, `test/quarantine-cli.test.ts`.-- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first by default; local engine or thin-client). A malformed `--limit` (not a positive safe integer, or missing) throws `invalid_params` from `parseFlags`, so the CLI exits 2 through `renderCliError`: the v1 envelope under `--json` with `why` and a `fix` that reruns the same argv with `--limit 50`, and the Error/Fix/Why lines otherwise (`test/recall-limit-envelope.test.ts`). Optional `--budget-policy facts_first|query_first` routes a one-shot read through the shared operation, forwarding fact filters and using remote recall on thin clients. Enum validation uses the shared operation definition; option order does not affect budget parsing. Only query-first with a nonblank query preserves numeric fractions until server packing; omitted/explicit facts-first keeps legacy integer parsing. The new option rejects watch/cursor/rollup/as-context combinations rather than silently ignoring them. Opt-in selector failures use stamped v1 errors; JSON mode emits structured local and remote errors on stdout with a nonzero exit, preserving remote read-error details without requiring a mutation receipt. Omitted-policy validation and fallback remain unchanged. Entity→text fallback: a bare positional without verb options is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read), the query retries as SQL-level fact-text grep with a stderr note. One predicate and note formatter are shared by the local path and thin-client mirror; explicit grep callers keep exact semantics. `--since` composes with entity and session in one query before LIMIT, on event time unless `--since-last-run`. Local `--grep` is passed to every engine arm (ILIKE with escaped metacharacters, before LIMIT); only `--supersessions` keeps the client-side filter. Pinned by `test/recall-grep-local-cli.test.ts`. Pinned by `test/facts-recall-since-composition.test.ts`, `test/recall-budget-policy-transports.test.ts`, `test/recall-budget-policy-thin-cli.test.ts`, and `test/recall-budget-policy-thin.serial.test.ts`.+- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first by default; local engine or thin-client). `--question <q>` (or `--question=<q>`) is the question, never an entity: it routes through the recall op like `--budget-policy` (thin clients call the remote recall, an answer without `facts_order` prints a not-ranked note; it refuses the watch, cursor, rollup and context renders), and the renderer shows the ranking, each `relevance` and `facts_degraded` (`test/recall-question-cli.test.ts`). A malformed `--limit` (not a positive safe integer, or missing) throws `invalid_params` from `parseFlags`, so the CLI exits 2 through `renderCliError`: the v1 envelope under `--json` with `why` and a `fix` that reruns the same argv with `--limit 50`, and the Error/Fix/Why lines otherwise (`test/recall-limit-envelope.test.ts`). Optional `--budget-policy facts_first|query_first` routes a one-shot read through the shared operation, forwarding fact filters and using remote recall on thin clients. Enum validation uses the shared operation definition; option order does not affect budget parsing. Only query-first with a nonblank query preserves numeric fractions until server packing; omitted/explicit facts-first keeps legacy integer parsing. The new option rejects watch/cursor/rollup/as-context combinations rather than silently ignoring them. Opt-in selector failures use stamped v1 errors; JSON mode emits structured local and remote errors on stdout with a nonzero exit, preserving remote read-error details without requiring a mutation receipt. Omitted-policy validation and fallback remain unchanged. Entity→text fallback: a bare positional without verb options is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read), the query retries as SQL-level fact-text grep with a stderr note. One predicate and note formatter are shared by the local path and thin-client mirror; explicit grep callers keep exact semantics. `--since` composes with entity and session in one query before LIMIT, on event time unless `--since-last-run`. Local `--grep` is passed to every engine arm (ILIKE with escaped metacharacters, before LIMIT); only `--supersessions` keeps the client-side filter. Pinned by `test/recall-grep-local-cli.test.ts`. Pinned by `test/facts-recall-since-composition.test.ts`, `test/recall-budget-policy-transports.test.ts`, `test/recall-budget-policy-thin-cli.test.ts`, and `test/recall-budget-policy-thin.serial.test.ts`.- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:` (written via `engine.setPageAliases`) and, for linkable entity pages, rewrites the derived title-subject and declared rows (`writeDerivedAliases`, coordinated on managed brains). Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. Pinned by `test/search/reindex-aliases.test.ts`.@@ -25,7 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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`, 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 — 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/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 --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex af4cc5199e..e4736e4633 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -6,8 +6,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. The plan records `budgetExplicit` (the caller passed the budget) and the resolved `packing` (`search.auto_packing` or the library override); `capEngaged` (unit `auto`, explicit budget, packing not `off`) routes allocation to `allocateCapped`: global rank one first (cut with `EVIDENCE_CUT_MARKER` when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest `budget_note`), then conversations by `cap_only` (floors, then enrichment), `breadth_capped` (longest prefix whose title + floor + `return_window` target window fits; rest `breadth_cap`) or `depth_first` (each session grown in turn); nothing spills. `capEvidenceToBudget` recounts title + `chunk_text` at the final boundary (after redaction and `capDeliveredSnippets`, whose marker is paid from the row's own allocation) and rewrites `budget_used`. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list, `effective_date` included (`applyEffectiveDate`, the live rows' normalizer); `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.- `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` from `effective-date.ts` (midnight UTC renders as written, other instants in `brain.timezone`; the one function think's `<page date>` also renders through, while the header's `observed` stays when the text was said, never the content date), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.-- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, read-policy filtered; a title inside a longer matched title is the same mention); `applyEntityAnchoring` (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through `getChunkWindows` under the caller's scope, rows stamped `entity_anchored`, token budget re-applied, fail-open); `entityAnchoringEnabled` (`search.entity_anchoring`, default off). Tests: `test/search-entity-anchor.test.ts`. Gates: `docs/eval/decisions/entity-anchoring-query/`.-- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default on since gates 1b and 2 passed; `false` turns it off). `matchQueryFacts` reads active facts only (not expired, not superseded, `valid_until` not passed, audit rows excluded) under recall's read policy (source scope; remote callers get world facts with private provenance filtered) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms) or a named entity, newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced `factRowOutput` strips page fields (slug, id, type, chunk_id) from fact rows on output, leaving `result_type: 'fact'`, `fact_id`, `follow_up` (`recall` by entity, or `grep` without one) and `page_slug` when the caller can read the entity page (`readableEntityPages`); and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`. Temporal fact reserve: `applyTemporalFactReserve` behind `search.temporal_fact_reserve` (default off): `hasTemporalCue` (the preregistered word, phrase, ISO date and month-name regex), candidates from `collectFactCandidates` (50 cosine, 50 keyword, 20 entity facts; shared with the facts arm's `matchQueryFacts`), scored cosine + term share + 0.1 when `valid_from` is more than a day from `created_at`, kept at cosine >= 0.5 or term share >= 0.34, packed into 15% of the token budget and 30% of the row count (1-20), rendered as fact rows whose text starts with `factDateHeader` (evidence delivery adds no second header), oldest first after the pages. Tests: `test/search-temporal-fact-reserve.test.ts`. Gates: `docs/eval/decisions/temporal-fact-reserve/`.+- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, the title match before the read-policy filter; a title inside a longer matched title is the same mention); `applyEntityAnchoring` (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through `getChunkWindows` under the caller's scope, rows stamped `entity_anchored`, token budget re-applied, fail-open); `entityAnchoringEnabled` (`search.entity_anchoring`, default off). Tests: `test/search-entity-anchor.test.ts`. Gates: `docs/eval/decisions/entity-anchoring-query/`.+- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default on since gates 1b and 2 passed; `false` turns it off). `matchQueryFacts` reads the candidate pool from `fact-relevance.ts` (active facts under recall's read policy) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms, substring match) or a named entity (in that page's source), newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced `factRowOutput` strips page fields (slug, id, type, chunk_id) from fact rows on output, leaving `result_type: 'fact'`, `fact_id`, `follow_up` (`recall` by entity, or `grep` without one) and `page_slug` when the caller can read the entity page (`readableEntityPages`); and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`. Temporal fact reserve: `applyTemporalFactReserve` behind `search.temporal_fact_reserve` (default off): `hasTemporalCue` (the preregistered word, phrase, ISO date and month-name regex), candidates from `collectFactCandidates` (50 cosine, 50 keyword, 20 entity facts, cosine for every candidate), scored and ordered by the shared `scoreFactCandidates` and kept by its `reserve` admission rule (fail-open on any error), packed into 15% of the token budget and 30% of the row count (1-20), rendered as fact rows whose text starts with `factDateHeader` (evidence delivery adds no second header), oldest first after the pages. Tests: `test/search-temporal-fact-reserve.test.ts`. Gates: `docs/eval/decisions/temporal-fact-reserve/`.+- `src/core/search/fact-relevance.ts` — question relevance for saved facts, shared by recall's `question` (`facts/question-recall.ts`), the temporal fact reserve and (pool only) the facts arm. `collectFactCandidates`: one bounded pool under recall's read policy (source scope, active and not superseded, audit rows excluded, quarantine and rederive hiding through `projectionEligibleSql`, the trust floor, remote world-only, `privateProvenanceFilterFragment` when `excludePrivate`) plus recall's filters inside every arm before its LIMIT (`(source_id, entity_slug)` pairs, `source_session`, event-time since, escaped `ILIKE` grep); arms, run concurrently and merged in a fixed order, are keyword FTS (`factsFtsDocument`, served by `idx_facts_fts`), cosine (cast to the facts column type, filtered on model only so the HNSW index serves it, a stale hash or other dimensions yielding no similarity; `ef_search` sized to the depth and pgvector's iterative scan when `hnswIterativeScan` is set) and the named entity page's facts in its own source; depths are bound parameters; `cosineForAll` scores every candidate's cosine whichever arm found it. A missing embedding column or other dimensions skips the cosine arm; any other DB error throws. `scoreFactCandidates`: cosine + whole-word term share + 0.1 when dated, the share's denominator growing past `TERM_STUFFING_RATIO` times the question's terms for a long fact; order score, newest valid_from, id. `admitted`: the `reserve` rule (cosine >= 0.5 or share >= 0.34) or the `facts_arm` rule (cosine >= 0.6, half the terms, or the named entity). `countUncomparableFacts` counts the pool's facts the cosine arm cannot compare, per source: candidates from `idx_facts_unembedded` and `idx_facts_embedding_model` first, the read policy on those rows only. Measured on a 100k-fact Postgres brain: p95 122 ms local, 115 ms remote. Tests: `test/fact-relevance.test.ts`, `test/recall-question.test.ts`.- `src/core/search/query-arms.ts` — `applyQueryArms`: the `query` op's post-retrieval arms in order (entity anchoring, then the facts arm), each behind its own key (entity anchoring default off, the facts arm default on); a temporal-cue query with a token budget takes the temporal fact reserve instead of the facts arm when `search.temporal_fact_reserve` is on; with all off it returns the rows untouched.- `src/core/search/image-vector-presence.ts` — `brainHasImageVectors` (one `EXISTS embedding_image IS NOT NULL` probe per engine, cached 60 s, fail-open to true). `hybrid/arms.ts` uses it so an inferred image/both modality on a brain with no image embeddings stays text: no multimodal embed, keyword arm kept, no `vector_arm_failed`; the opt-in LLM modality tie-break still runs, and an image or both answer is demoted to text. An explicit `crossModal` is honored. Tests: `test/search-image-arm-text-only.test.ts`, `test/cross-modal-hybrid-integration.serial.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 66569744d4..b4818d2030 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -43,7 +43,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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 used by FTS. `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 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/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 --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 07a4aacd56..8c9d2c7c52 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -52,4 +52,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/utils.ts` — Shared SQL utilities used by both engines. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness). `isUndefinedColumnError(err)` predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated; used by `oauth-provider.ts` so genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback. `validateSourceId(id)` throws on anything outside `^[a-z0-9_-]+$`, used by the per-source disk-layout fix in patterns.ts/synthesize.ts before any `join(brainDir, '.sources', source_id, slug+'.md')` so source_id can't traverse out of brainDir. `rowToSearchResult` projects email `message_id` / `thread_id` metadata and exposes `source_subject` only when a non-empty Message-ID proves the page is an email, so generated page titles never become authoritative email subjects. `rowToPage` populates the required `Page.source_id` from the SELECT projection (`scripts/check-source-id-projection.sh` enforces every projection feeding `rowToPage` includes the column). `bigintToStringReplacer(key, value)` — the JSON replacer turning `bigint` into strings (the postgres.js int8 wire shape), shared by cli.ts's local-result normalizer (which re-exports it) and the commands that stringify results themselves (`gbrain call`, `extract --explain`); commands import it from here, never from the dispatcher. Its doc comment deliberately carries no double-dash flag literals — the flag-registry generator harvests them from every module a command transitively imports, and utils.ts is imported by nearly all.-- `src/core/verbs.ts` — MEMORY_VERBS v1: the four frozen protocol verbs (`remember`, `entity`, `synthesize`, `forget`) as first-class Operations, plus `MEMORY_VERBS_VERSION` (single source of truth, =1), `VERB_NAMES`, the hand-authored `RESPONSE_SCHEMAS` registry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), and `ERROR_SCHEMA`. The extended `recall` op is defined in ops/facts.ts and registered through operations.ts. Its response registry advertises optional `budget_packing` policy/applied/reason and per-arm integer accounting without changing required default fields or protocol version; `test/protocol-document.test.ts` pins discovery and malformed metadata rejection. The `context_pack` and `delta` fact items advertise optional `fact_id` and `provenance` (#6146). RUNTIME LEAF invariant: operations.ts spreads `verbOperations` into its array at module-eval time, so this file must never statically import operations.ts VALUES (type-only imports fine; handlers use dynamic import) — violating it causes a TDZ crash on whichever module evaluates second. Every verb error carries a populated `suggestion` + `protocol_version` (via `verbError` in operations.ts). The `forget` verb deliberately has NO cliHints (CLI_ONLY `forget` dispatches first and would shadow it). Frozen contract: docs/protocol/MEMORY_VERBS_v1.md; pinned by test/memory-verbs-conformance.test.ts.+- `src/core/verbs.ts` — MEMORY_VERBS v1: the four frozen protocol verbs (`remember`, `entity`, `synthesize`, `forget`) as first-class Operations, plus `MEMORY_VERBS_VERSION` (single source of truth, =1), `VERB_NAMES`, the hand-authored `RESPONSE_SCHEMAS` registry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), and `ERROR_SCHEMA`. The extended `recall` op is defined in ops/facts.ts and registered through operations.ts. Its response registry advertises optional `budget_packing` policy/applied/reason and per-arm integer accounting without changing required default fields or protocol version; `test/protocol-document.test.ts` pins discovery and malformed metadata rejection. The `context_pack` and `delta` fact items advertise optional `fact_id` and `provenance` (#6146). The recall registry advertises optional `facts_order`, `facts_degraded` and per-fact `relevance` (question ranking). RUNTIME LEAF invariant: operations.ts spreads `verbOperations` into its array at module-eval time, so this file must never statically import operations.ts VALUES (type-only imports fine; handlers use dynamic import) — violating it causes a TDZ crash on whichever module evaluates second. Every verb error carries a populated `suggestion` + `protocol_version` (via `verbError` in operations.ts). The `forget` verb deliberately has NO cliHints (CLI_ONLY `forget` dispatches first and would shadow it). Frozen contract: docs/protocol/MEMORY_VERBS_v1.md; pinned by test/memory-verbs-conformance.test.ts.diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 1356a19181..3da18aab46 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -76,7 +76,8 @@ rejection of serve-only flags before a brain opens.- `src/core/extract-timeline-from-meetings.ts` — normalizes canonical incoming and pack-owned outgoing `attended` edges into meeting/person roles before timeline fan-out. SQL requires a live person and live meeting (including legacy meeting notes); existing private-meeting filtering, source opt-in and source-qualified deduplication still apply. Dual-engine tests in `test/extract-timeline-attendance.test.ts` use an empty gazetteer so a body-mention fallback cannot conceal a broken attendance consumer.- `src/core/context/delta-cursor.ts` — pure helpers for delta's per-arm cursor: the opaque base64url `cursor` (`{v:1, p:[since, slug], f:[created_at, id]}`, validated like `since`), microsecond ISO normalization and the one-microsecond clamp, `nextPagesPos`/`nextFactsPos` (delivered prefix, `now() - 2 s` horizon `DELTA_COMMIT_LAG_MS`, the facts cursor computed from raw rows so a duplicate cluster split by a budget cut loses nothing), `resolveDeltaStart` and `legacyDeltaCursor`. `test/delta-cursor-integrity.test.ts`.-- `src/core/ops/facts.ts` — shared fact/memory operations, including `recall` and the `delta` cursor. `context_pack` and `delta` `facts[]` carry recall's `fact_id` and `provenance` (the stored `facts.source`), read in one batched `withProvenance` lookup by the delivered ids, so hot memory and MCP `_meta` stay unchanged; remote callers get provenance through the same redaction as the fact text, and it never enters `text` (#6146, `test/context-pack-fact-traceability.test.ts`). Recall keeps source/visibility and fact filters before per-arm candidate limits. Its default/explicit `facts_first` packing preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optional `query_first` packs the ranked page prefix first only with a nonblank query and positive finite budget; floor-zero and exhausted remainders explicitly return empty arms rather than call the unbounded zero-budget packer. Neither arm skips oversized prefix items or truncates. No-query and inactive-budget paths keep legacy behavior. Only policy-supplied calls add `budget_packing` effective-policy/reason and candidate/kept/dropped/estimated-used accounting. Counter sums match the frozen fields. Do not change the global packer or fact relevance to implement this policy. Delta rejects calendar-invalid ISO dates and years outside 0001-9999 (on the parsed UTC value) before normalization across fractional-second forms, while preserving valid six-digit microsecond cursors. Delta's per-arm cursor (contributor audit wave P0): the start position resolves `cursor` > `since` (whole tuple, slug only when supplied) > the session row; each arm advances through its delivered prefix only (`src/core/context/delta-cursor.ts`), an arm that failed or never finished holds, the conservative legacy `next_cursor.since`/`slug` never passes the oldest undelivered fact, and a legacy caller at an unpageable same-timestamp boundary is refused with `delta_cursor_upgrade_required`. Incomplete wakes emit `delta_incomplete` (`fix.next: wait`, `report` on the third consecutive wake, counted atomically in `session_context_state.degraded_wakes` with an in-process fallback when the store is down); a failed state read refuses with `unavailable`/`session_state` instead of re-initializing at now. `test/recall-budget-policy.test.ts` pins recall behavior; `test/ambient-recall.test.ts` pins delta cursor validation; `test/delta-cursor-integrity.test.ts` (both engines) pins every no-advance path, the facts drain, legacy safety and the commit-visibility bound.+- `src/core/facts/question-recall.ts` — recall's `question`: `parseQuestionParam` refuses `supersessions`, `include_expired` and more than 2,000 characters with the corrected call as `fix.mcp`; `rankFactsByQuestion` resolves `entity` per source to pairs and runs `unlinkedNamesakes` on the whole filtered pool before ranking, embeds the question once through `embedQueryBounded` (the gateway's query-embedding cache, so a `query` of the same text shares it; the embedding opt-out, a missing provider or a failed embed rank by term share and set `facts_degraded.reason`), ranks with `search/fact-relevance.ts` under the `recall.question_admission` rule (`reserve` default, or `facts_arm`; pool, uncomparable count and rule read concurrently), hydrates the ranked ids through `rowToFact`, counts uncomparable facts (`facts_degraded.unembedded`, the `facts_unembedded` notice with the `embed --stale --facts` preview) and turns a DB error into `unavailable` (`fix.next: wait`). `recallHintNotice` builds `recall_hint`. Tests: `test/recall-question.test.ts` (both engines), `test/recall-question-cli.test.ts`.+- `src/core/ops/facts.ts` — shared fact/memory operations, including `recall` and the `delta` cursor. Every recall response carries `facts_order` (`newest`, or `relevance` when `question` ranked the facts arm through `facts/question-recall.ts`); a `query` call without `question` or a fact filter emits `recall_hint`. `context_pack` and `delta` `facts[]` carry recall's `fact_id` and `provenance` (the stored `facts.source`), read in one batched `withProvenance` lookup by the delivered ids, so hot memory and MCP `_meta` stay unchanged; remote callers get provenance through the same redaction as the fact text, and it never enters `text` (#6146, `test/context-pack-fact-traceability.test.ts`). Recall keeps source/visibility and fact filters before per-arm candidate limits. Its default/explicit `facts_first` packing preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optional `query_first` packs the ranked page prefix first only with a nonblank query and positive finite budget; floor-zero and exhausted remainders explicitly return empty arms rather than call the unbounded zero-budget packer. Neither arm skips oversized prefix items or truncates. No-query and inactive-budget paths keep legacy behavior. Only policy-supplied calls add `budget_packing` effective-policy/reason and candidate/kept/dropped/estimated-used accounting. Counter sums match the frozen fields. Do not change the global packer or fact relevance to implement this policy. Delta rejects calendar-invalid ISO dates and years outside 0001-9999 (on the parsed UTC value) before normalization across fractional-second forms, while preserving valid six-digit microsecond cursors. Delta's per-arm cursor (contributor audit wave P0): the start position resolves `cursor` > `since` (whole tuple, slug only when supplied) > the session row; each arm advances through its delivered prefix only (`src/core/context/delta-cursor.ts`), an arm that failed or never finished holds, the conservative legacy `next_cursor.since`/`slug` never passes the oldest undelivered fact, and a legacy caller at an unpageable same-timestamp boundary is refused with `delta_cursor_upgrade_required`. Incomplete wakes emit `delta_incomplete` (`fix.next: wait`, `report` on the third consecutive wake, counted atomically in `session_context_state.degraded_wakes` with an in-process fallback when the store is down); a failed state read refuses with `unavailable`/`session_state` instead of re-initializing at now. `test/recall-budget-policy.test.ts` pins recall behavior; `test/ambient-recall.test.ts` pins delta cursor validation; `test/delta-cursor-integrity.test.ts` (both engines) pins every no-advance path, the facts drain, legacy safety and the commit-visibility bound.- `src/core/markdown-code.ts` — `stripCodeBlocks` masks fenced and inline code while preserving every CR/LF and UTF-16 code-unit offset. Citation paragraphs and later link references retain their original boundaries, including after an unclosed fence. `parseTimelineEntries` in `src/core/link-extraction.ts` groups the optional dash with its trailing whitespace so leading whitespace does not trigger overlapping repetition. Existing date and delimiter rules remain unchanged. Standalone backtick and tilde fences require valid closing markers; historical inline triple-backtick spans remain masked. Pinned through real FS/DB link and timeline consumers by `test/timeline-parser-regression.test.ts`; its adversarial whitespace workload runs in a timeout-bounded child process. #6133: inline spans pair backtick runs of equal length (CommonMark), found read-only by `fence-scan.ts` `scanMarkdownCode`/`inlineCodeEndAt` over a view where a bare CR is a space (so a span may still cross one), so a double-backtick span and a span holding a single backtick are masked whole and a backslash-escaped backtick opens nothing; the lint `placeholder-date` rule (`src/commands/lint.ts`) runs over the masked text, so placeholders in inline code no longer fire (`test/lint-3958.test.ts`, `test/timeline-parser-regression.test.ts`).diff --git a/docs/guides/multi-language-fts.md b/docs/guides/multi-language-fts.mdindex a07defa843..b211347fb0 100644--- a/docs/guides/multi-language-fts.md+++ b/docs/guides/multi-language-fts.md@@ -50,7 +50,7 @@ Use the explicit command:```bashexport GBRAIN_FTS_LANGUAGE=portuguesegbrain reindex-search-vector --dry-run # preview: language + row counts-gbrain reindex-search-vector --yes # recreate triggers + backfill+gbrain reindex-search-vector --yes # recreate triggers + backfill + rebuild the facts keyword index```The stamp survives later schema work: `initSchema()` — including the replaydiff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.mdindex 78b124a7cb..a90de77417 100644--- a/docs/mcp/TOOL_REFERENCE.md+++ b/docs/mcp/TOOL_REFERENCE.md@@ -322,11 +322,12 @@ Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for## `recall`-MEMORY VERB (v1): retrieve saved facts/snippets — the protocol read verb. Filters hot-memory facts by entity / since / session_id; pass `query` to ALSO run hybrid search over pages (results[] arm); pass `budget_tokens` for server-side packing (response reports budget_used + dropped_count — never trims client-side). Remote callers see visibility=world facts only. Routing: for ONE known person/company/project card use `entity` (zero LLM); for broad questions needing reasoning use `synthesize` (expensive). Branch on structured fields (status/kind/evidence), never on prose. Every response carries protocol_version.+MEMORY VERB (v1): retrieve saved facts/snippets — the protocol read verb. Filters hot-memory facts by entity / since / session_id, newest first, or ranks them by relevance with `question`; pass `query` to ALSO run hybrid search over pages (results[] arm); pass `budget_tokens` for server-side packing (response reports budget_used + dropped_count — never trims client-side). Remote callers see visibility=world facts only. Routing: for ONE known person/company/project card use `entity` (zero LLM); for broad questions needing reasoning use `synthesize` (expensive). Branch on structured fields (status/kind/evidence), never on prose. Every response carries protocol_version.| Parameter | Type | Guidance || --- | --- | --- || `entity` | string | Entity slug (canonical). Returns facts about this entity newest first, each labelled with its source_id. Across several granted sources, same-slug entities that no entity-identity group links are different entities: facts comes back empty and ambiguous_entity names each (source_id, entity_slug); pass source_id to read one. |+| `question` | string | Ranks active facts by relevance to this question (cosine to its embedding plus whole-word term share, +0.1 for a writer-dated fact) instead of newest first. Facts below the admission rule are left out, so an empty facts[] is a valid answer. Each fact carries `relevance` (a ranking score, about 0 to 2.1, not comparable across calls); the response carries `facts_order: "relevance"` and, when ranking ran without full semantic matching, `facts_degraded`. Applies inside `entity`, `session_id`, `since` and `grep`. Does not search pages (`query` does; both may be passed). Rejected with `supersessions` or `include_expired`, and over 2,000 characters (invalid_params, with the corrected call as `fix`). One query embedding per call, shared with a `query` of the same text. || `query` | string | MEMORY_VERBS v1: free-text retrieval over pages (hybrid search arm). Response adds results[] (slug, title, chunk, evidence, create_safety, provenance). Combinable with entity (both arms run). Degrades to keyword-only search when no embedding provider is configured (search_degraded notes it; never an error). || `budget_tokens` | number | MEMORY_VERBS v1: server-side token budget (char/4 estimate). Facts pack first, then results. Response adds budget_tokens, budget_used, dropped_count. || `budget_policy` | string (`facts_first`, `query_first`) | Optional packing order. facts_first (default) packs facts first, then page results. query_first packs the ranked page prefix before facts only with a nonblank query and positive finite budget; a positive budget below one token keeps neither arm. Without a nonblank query and an active budget, packing stays facts_first. Neither policy skips oversized items or truncates. Supplying this option adds budget_packing accounting. Keep fact-focused/entity-filtered questions on facts_first. |diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.mdindex 2794761e41..9f1fa7edd4 100644--- a/docs/protocol/AGENT_OPERATOR_v1.md+++ b/docs/protocol/AGENT_OPERATOR_v1.md@@ -748,7 +748,7 @@ final document.is stateless, so dedupe is per authenticated client and session, and`degraded` and `safety` notices ride every affected call. At most 2`coaching` notices per session. Notices that describe one call's result-(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`)+(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)are never deduped.**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex 3815b4f904..6453b311f6 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -115,7 +115,7 @@ have no per-client row: they serve the server-resolved surface directly.## The verbs-### recall(query?, entity?, budget_tokens?, budget_policy?, source_id?, since?, session_id?, limit?, …) — read+### recall(query?, question?, entity?, budget_tokens?, budget_policy?, source_id?, since?, session_id?, limit?, …) — readRetrieve saved facts and (with `query`) budget-packed page snippets.@@ -128,6 +128,21 @@ Retrieve saved facts and (with `query`) budget-packed page snippets.composes with `entity` and `session_id` in the same query, before theper-arm limit. An unparseable value is rejected with `invalid_params`.- `limit` is a PER-ARM cap (facts and search results each).+- `question`: optional string (at most 2,000 characters). The FACTS arm then+ returns active facts ranked by relevance to the question instead of newest+ first: cosine to the question's embedding plus whole-word term share, plus+ 0.1 when the fact carries a writer-supplied date. Facts below the admission+ rule are not returned, so an empty `facts[]` is a valid answer. `entity`,+ `session_id`, `since` and `grep` filter before ranking. `question` does not+ search pages; `query` does, and both may be passed. `supersessions: true` or+ `include_expired: true` with `question` is `invalid_params` (ranking covers+ active facts only); the error's `fix.mcp` is the call without them. One query+ embedding per call, no model call. Without an embedding provider, with+ embeddings turned off, or when the embed fails, facts rank by term share and+ `facts_degraded.reason` says why. A server without question ranking ignores+ the parameter (or rejects it under `mcp.strict_params=reject`); clients detect+ support by `facts_order: "relevance"` in the response or `question` in the+ live tool schema, not by `protocol_version`.- `budget_tokens`: SERVER-side packing — by default facts pack first and searchresults take the remainder. A positive finite numeric budget is floored;other values leave the arrays unbudgeted. Costs are `ceil(fact.length/4)` or@@ -168,9 +183,17 @@ Response — an additive SUPERSET of the plain facts envelope on EVERY call| `total` | int | count of facts returned || `results[]` | array | search arm only: `slug`, `title`, `chunk`, `evidence`, `create_safety`, `provenance` (origin page slug) || `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 |+A call that passes `query` without `question` and without `entity`,+`session_id`, `since` or `supersessions` returns its facts newest first, as v1+always has, and carries a `recall_hint` notice (kind `info`) whose `fix.mcp` is+the same call with `question` set to the query.+`budget_packing` contains `policy` (effective `facts_first | query_first`),`applied` (whether the requested budget policy applied), `reason`, and `facts` /`results` objects with `candidates`, `kept`, `dropped`, and `used`. Candidates are@@ -771,7 +794,7 @@ Published so harness authors place calls by cost, not by learning at timeout:| `entity` | zero-LLM, **p99 < 100ms** | CI-gated on a 20K-page corpus (below). Safe per entity-bearing message. || `context_pack` | zero-LLM, sub-second | Fan-out capped at 8 entities. Session boundaries, not per-message. Push path passes a wall-clock deadline and returns a PARTIAL pack (`degraded_reason`) rather than overrun. || `delta` | zero-LLM, sub-second | O(changes). Heartbeats — pull path only (there is no push heartbeat); session cursors expire after 7 idle days. |-| `recall` | zero-LLM (keyword) to one embedding call (when `query` is passed) | Sub-second typical; the `query` arm adds one embedding round-trip. |+| `recall` | zero-LLM (keyword) to one embedding call (when `query` or `question` is passed; a `query` and a `question` with the same text share one) | Sub-second typical; the `query` arm adds one embedding round-trip. || `remember` / `forget` | write, sub-second | One durable write; `remember` adds one embedding call for dedup when a provider is configured. || `synthesize` | **EXPENSIVE / SLOW** | LLM calls, seconds-to-minutes, costs money. Never place on a hot or ambient path. |diff --git a/llms-full.txt b/llms-full.txtindex 55214eefe4..9eb0ce5a5d 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -3927,7 +3927,7 @@ final document.is stateless, so dedupe is per authenticated client and session, and`degraded` and `safety` notices ride every affected call. At most 2`coaching` notices per session. Notices that describe one call's result-(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`)+(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)are never deduped.**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`@@ -8614,7 +8614,7 @@ have no per-client row: they serve the server-resolved surface directly.## The verbs-### recall(query?, entity?, budget_tokens?, budget_policy?, source_id?, since?, session_id?, limit?, …) — read+### recall(query?, question?, entity?, budget_tokens?, budget_policy?, source_id?, since?, session_id?, limit?, …) — readRetrieve saved facts and (with `query`) budget-packed page snippets.@@ -8627,6 +8627,21 @@ Retrieve saved facts and (with `query`) budget-packed page snippets.composes with `entity` and `session_id` in the same query, before theper-arm limit. An unparseable value is rejected with `invalid_params`.- `limit` is a PER-ARM cap (facts and search results each).+- `question`: optional string (at most 2,000 characters). The FACTS arm then+ returns active facts ranked by relevance to the question instead of newest+ first: cosine to the question's embedding plus whole-word term share, plus+ 0.1 when the fact carries a writer-supplied date. Facts below the admission+ rule are not returned, so an empty `facts[]` is a valid answer. `entity`,+ `session_id`, `since` and `grep` filter before ranking. `question` does not+ search pages; `query` does, and both may be passed. `supersessions: true` or+ `include_expired: true` with `question` is `invalid_params` (ranking covers+ active facts only); the error's `fix.mcp` is the call without them. One query+ embedding per call, no model call. Without an embedding provider, with+ embeddings turned off, or when the embed fails, facts rank by term share and+ `facts_degraded.reason` says why. A server without question ranking ignores+ the parameter (or rejects it under `mcp.strict_params=reject`); clients detect+ support by `facts_order: "relevance"` in the response or `question` in the+ live tool schema, not by `protocol_version`.- `budget_tokens`: SERVER-side packing — by default facts pack first and searchresults take the remainder. A positive finite numeric budget is floored;other values leave the arrays unbudgeted. Costs are `ceil(fact.length/4)` or@@ -8667,9 +8682,17 @@ Response — an additive SUPERSET of the plain facts envelope on EVERY call| `total` | int | count of facts returned || `results[]` | array | search arm only: `slug`, `title`, `chunk`, `evidence`, `create_safety`, `provenance` (origin page slug) || `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 |+A call that passes `query` without `question` and without `entity`,+`session_id`, `since` or `supersessions` returns its facts newest first, as v1+always has, and carries a `recall_hint` notice (kind `info`) whose `fix.mcp` is+the same call with `question` set to the query.+`budget_packing` contains `policy` (effective `facts_first | query_first`),`applied` (whether the requested budget policy applied), `reason`, and `facts` /`results` objects with `candidates`, `kept`, `dropped`, and `used`. Candidates are@@ -9270,7 +9293,7 @@ Published so harness authors place calls by cost, not by learning at timeout:| `entity` | zero-LLM, **p99 < 100ms** | CI-gated on a 20K-page corpus (below). Safe per entity-bearing message. || `context_pack` | zero-LLM, sub-second | Fan-out capped at 8 entities. Session boundaries, not per-message. Push path passes a wall-clock deadline and returns a PARTIAL pack (`degraded_reason`) rather than overrun. || `delta` | zero-LLM, sub-second | O(changes). Heartbeats — pull path only (there is no push heartbeat); session cursors expire after 7 idle days. |-| `recall` | zero-LLM (keyword) to one embedding call (when `query` is passed) | Sub-second typical; the `query` arm adds one embedding round-trip. |+| `recall` | zero-LLM (keyword) to one embedding call (when `query` or `question` is passed; a `query` and a `question` with the same text share one) | Sub-second typical; the `query` arm adds one embedding round-trip. || `remember` / `forget` | write, sub-second | One durable write; `remember` adds one embedding call for dedup when a provider is configured. || `synthesize` | **EXPENSIVE / SLOW** | LLM calls, seconds-to-minutes, costs money. Never place on a hot or ambient path. |diff --git a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.mdindex f5a7ebabf3..89f371bb6f 100644--- a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md+++ b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md@@ -750,7 +750,7 @@ final document.is stateless, so dedupe is per authenticated client and session, and`degraded` and `safety` notices ride every affected call. At most 2`coaching` notices per session. Notices that describe one call's result-(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`)+(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)are never deduped.**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`diff --git a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.mdindex f5a7ebabf3..89f371bb6f 100644--- a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md+++ b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md@@ -750,7 +750,7 @@ final document.is stateless, so dedupe is per authenticated client and session, and`degraded` and `safety` notices ride every affected call. At most 2`coaching` notices per session. Notices that describe one call's result-(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`)+(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)are never deduped.**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`diff --git a/plugin/skills/conventions/agent-operator-protocol.md b/plugin/skills/conventions/agent-operator-protocol.mdindex f5a7ebabf3..89f371bb6f 100644--- a/plugin/skills/conventions/agent-operator-protocol.md+++ b/plugin/skills/conventions/agent-operator-protocol.md@@ -750,7 +750,7 @@ final document.is stateless, so dedupe is per authenticated client and session, and`degraded` and `safety` notices ride every affected call. At most 2`coaching` notices per session. Notices that describe one call's result-(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`)+(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)are never deduped.**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex b61dce0eb7..5869986a7e 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 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 importsrc/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 1939 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)+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/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 optionsrc/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 --git a/skills/conventions/agent-operator-protocol.md b/skills/conventions/agent-operator-protocol.mdindex f5a7ebabf3..89f371bb6f 100644--- a/skills/conventions/agent-operator-protocol.md+++ b/skills/conventions/agent-operator-protocol.md@@ -750,7 +750,7 @@ final document.is stateless, so dedupe is per authenticated client and session, and`degraded` and `safety` notices ride every affected call. At most 2`coaching` notices per session. Notices that describe one call's result-(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`)+(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)are never deduped.**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex f4b091edee..78d2654ab4 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -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": "e54e9d63da45c852b2897303a97e37a5e67ecba749c45311703059e51524331a",+ "conventions/agent-operator-protocol.md": "e061724e481af6bb22ea8253ff927816865e8f4095a3eef93fced18ec499e9f2","conventions/brain-first.md": "d9b18321150830d38586f5bd23ce9de735f08ac3b54d7ac63bc3184a61e17ef1","conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",diff --git a/src/commands/reindex-search-vector.ts b/src/commands/reindex-search-vector.tsindex 73023a02a6..1de754f6f7 100644--- a/src/commands/reindex-search-vector.ts+++ b/src/commands/reindex-search-vector.ts@@ -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* GBRAIN_FTS_LANGUAGE.** Why this command exists: schema migration v123 (configurable_fts_language)@@ -46,7 +47,7 @@*/import type { BrainEngine } from '../core/engine.ts';-import { getFtsLanguage, FTS_REINDEX_MARKER_KEY } from '../core/fts-language.ts';+import { getFtsLanguage, factsFtsIndexSql, FTS_REINDEX_MARKER_KEY } 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';@@ -153,7 +154,7 @@ export async function runReindexSearchVector(console.log(JSON.stringify(result, null, 2));} else {console.log(`[dry-run] Would recreate 2 trigger functions with language='${lang}'`);- console.log(`[dry-run] Would backfill ${pagesCount} pages + ${chunksCount} chunks`);+ console.log(`[dry-run] Would backfill ${pagesCount} pages + ${chunksCount} chunks and rebuild the facts keyword index`);console.log(`[dry-run] Skipping all DB writes. Applying needs the user's approval (gbrain reindex-search-vector asks).`);}return result;@@ -274,6 +275,9 @@ export async function runReindexSearchVector();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));@@ -292,7 +296,7 @@ export async function runReindexSearchVector(console.log(JSON.stringify(result, null, 2));} else {console.log(`✅ Recreated 2 trigger functions with language='${lang}'`);- console.log(`✅ Backfilled ${pagesCount} pages + ${chunksCount} chunks (${result.durationMs}ms)`);+ console.log(`✅ Backfilled ${pagesCount} pages + ${chunksCount} chunks and rebuilt the facts keyword index (${result.durationMs}ms)`);}return result;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 548ebfc68a..c126e23111 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -373,6 +373,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.147.0', text: 'In a brain folder with the Git durability hook, a write that arrives while the effect worker commits a backlog of Git effects now publishes after the group in flight, inside its 5 s wait, instead of returning pending after the whole backlog; Git effects still commit in order. A write waiting on a busy worktree is reported as `writer_busy` without a stale preparing phase.' },// `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.151.0', text: '`delta` and `context_pack` called without `include_private`, and the per-turn context block that harness hooks inject, now apply to their facts the same page-visibility rule they already apply to their pages. With `include_private` from the local CLI, `delta` and `context_pack` output is unchanged.' },+ // 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.153.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 --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex ea8e0f3b18..9398445cf1 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'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', '--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', '--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-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--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'],'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', '--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'],@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'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'],'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', '--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', '--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', '--allow-create-db', '--allow-docker', '--apply', '--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'],'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'],@@ -98,7 +98,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--brain', '--break-lock', '--client', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],- 'recall': ['--accept-pending', '--access', '--add', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--grep', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--progress-interval', '--progress-json', '--purge', '--query', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],+ 'recall': ['--accept-pending', '--access', '--add', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--grep', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],'reconcile-links': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--apply', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--include-ambiguous', '--json', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--path', '--plan', '--progress-interval', '--progress-json', '--quiet', '--repo', '--self-transfer', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],diff --git a/src/core/config.ts b/src/core/config.tsindex 4ca31ef91c..7590d9e130 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1447,6 +1447,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['models.brainstorm.judge','models.eval.longmemeval', 'models.eval.cross_modal.slot_a', 'models.eval.cross_modal.slot_b', 'models.eval.cross_modal.slot_c', // #5872 D12 probe judge slots'facts.extraction_model',+ 'recall.question_admission', // recall `question` admission rule: reserve (default) | facts_arm (facts/question-recall.ts)// Brain-wide kill switch for fact extraction, read by// src/core/facts/extract.ts:isFactsExtractionEnabled and honored by// sweep.ts, operations.ts and transcripts/ingest-facts.ts. That function'sdiff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.tsindex 956aa1d0b6..e1572adc38 100644--- a/src/core/embedding-migration.ts+++ b/src/core/embedding-migration.ts@@ -83,6 +83,15 @@ export function formatEnvOverrideWarning(w: EnvOverrideWarning): string {return lines.join('\n');}+/** #4252: every index the cascade of DROP COLUMN `table`.embedding takes (pg_depend edges, partial WHERE predicates included). */+async function embeddingDependentIndexes(tx: { executeRaw: <T = unknown>(sql: string, params?: unknown[]) => Promise<T[]> }, table: string) {+ return tx.executeRaw<{ name: string; def: string }>(+ `SELECT DISTINCT c.relname AS name, pg_get_indexdef(d.objid) AS def FROM pg_depend d JOIN pg_class c ON c.oid = d.objid AND c.relkind = 'i'+ WHERE d.classid = 'pg_class'::regclass AND d.refclassid = 'pg_class'::regclass AND d.deptype = 'a' AND d.refobjid = to_regclass($1)+ AND d.refobjsubid = (SELECT attnum FROM pg_attribute WHERE attrelid = to_regclass($1) AND attname = 'embedding' AND NOT attisdropped)`, [table]);+}+const ifNotExists = (def: string) => def.replace(/^CREATE (UNIQUE )?INDEX /, 'CREATE $1INDEX IF NOT EXISTS ');+/*** The atomic DROP + ALTER + CREATE INDEX sequence for content_chunks.* Both engines accept identical SQL (PGLite uses pgvector via WASM, same@@ -121,19 +130,7 @@ export async function runSchemaTransition(engine: BrainEngine, targetDim: number// follows, so this also catches indexes that reference the column only// in a partial WHERE predicate (which a pg_indexes.indexdef text match// could not do without false-matching embedding_image/_multimodal).- const dependentIndexes = await tx.executeRaw<{ name: string; def: string }>(- `SELECT DISTINCT c.relname AS name, pg_get_indexdef(d.objid) AS def- FROM pg_depend d- JOIN pg_class c ON c.oid = d.objid AND c.relkind = 'i'- WHERE d.classid = 'pg_class'::regclass- AND d.refclassid = 'pg_class'::regclass- AND d.deptype = 'a'- AND d.refobjid = to_regclass('content_chunks')- AND d.refobjsubid = (- SELECT attnum FROM pg_attribute- WHERE attrelid = to_regclass('content_chunks')- AND attname = 'embedding' AND NOT attisdropped)`,- );+ const dependentIndexes = await embeddingDependentIndexes(tx, 'content_chunks');// Text embedding column — transition to target dim.await tx.executeRaw(`DROP INDEX IF EXISTS idx_chunks_embedding`);@@ -149,9 +146,7 @@ export async function runSchemaTransition(engine: BrainEngine, targetDim: numberif (hnswIndexExpected('vector', targetDim)) ann.push(...parseDeferredAnnIndexes([idx], DEFERRED_ANN_TABLES));continue;}- await tx.executeRaw(- idx.def.replace(/^CREATE (UNIQUE )?INDEX /, 'CREATE $1INDEX IF NOT EXISTS '),- );+ await tx.executeRaw(ifNotExists(idx.def));}// Image/multimodal embedding column — rebuild index but preserve@@ -309,9 +304,13 @@ async function transitionDimPinnedColumn(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.+ 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})`);+ for (const idx of dependents) if (idx.name !== indexName && !/USING hnsw/i.test(idx.def)) await tx.executeRaw(ifNotExists(idx.def));// HNSW has a per-type dimension ceiling; above it pgvector refuses the// index and exact scans remain the (correct, slower) path. #5088: the index// is returned for the deferred build after the re-embed, not created here.diff --git a/src/core/facts/question-recall.ts b/src/core/facts/question-recall.tsindex 24623cc927..5897afbf32 100644--- a/src/core/facts/question-recall.ts+++ b/src/core/facts/question-recall.ts@@ -193,13 +193,15 @@ export async function rankFactsByQuestion(ctx: OperationContext, input: Questionconst { embedding, reason } = await questionEmbedding(ctx, question);if (!embedding && queryTerms(question).length === 0) return empty({ reason: 'no_query_terms' });try {- const pool = await collectFactCandidates(ctx.engine, question, scope, embedding, {- depth: { keyword: QUESTION_POOL_DEPTH, cosine: QUESTION_POOL_DEPTH, entity: QUESTION_POOL_DEPTH }, filters, cosineForAll: true,- hnswIterativeScan: resolveHnswIterativeScan(ctx.config),- });- const rule = await admissionRule(ctx.engine);+ const [pool, uncomparable, rule] = await Promise.all([+ collectFactCandidates(ctx.engine, question, scope, embedding, {+ depth: { keyword: QUESTION_POOL_DEPTH, cosine: QUESTION_POOL_DEPTH, entity: QUESTION_POOL_DEPTH }, filters, cosineForAll: true,+ hnswIterativeScan: resolveHnswIterativeScan(ctx.config),+ }),+ embedding ? countUncomparableFacts(ctx.engine, scope, filters, embedding.length) : [],+ admissionRule(ctx.engine),+ ]);const ranked = scoreFactCandidates(question, pool.candidates).filter(s => admitted(s, rule)).slice(0, input.limit);- const uncomparable = embedding && pool.column ? await countUncomparableFacts(ctx.engine, scope, filters, embedding.length) : [];const unembedded = uncomparable.reduce((n, r) => n + r.n, 0);const why = reason ?? (embedding && !pool.column ? 'facts_embedding_column_missing' : undefined);const degraded: FactsDegraded | undefined = why || unembedded ? { ...(why ? { reason: why } : {}), ...(unembedded ? { unembedded } : {}) } : undefined;diff --git a/src/core/fts-language.ts b/src/core/fts-language.tsindex 53e24d9442..2c9b04f5ea 100644--- a/src/core/fts-language.ts+++ b/src/core/fts-language.ts@@ -106,3 +106,23 @@ export function applyFtsLanguagePolicy(sql: string): string {// safe to interpolate as a SQL string literal.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`,+ ];+}diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.tsindex a11a7eccd7..c0d1d27d7a 100644--- a/src/core/notice-ledger.ts+++ b/src/core/notice-ledger.ts@@ -23,7 +23,7 @@ export const COACHING_BUDGET_PER_SESSION = 2;/** Notices that describe THIS call's result (never deduped): the diagnosis must ride every affected call. *//** The one muteable `ask`: an unanswered first-run bundle must stay dismissible. Every other ask always shows. */export const MUTEABLE_ASK_CODES: ReadonlySet<string> = new Set(['first_run_decisions']);-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete']);+export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'facts_unembedded']);export interface NoticeAudience {transport: Transport;diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 662a6b5d70..489abba5f1 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -4751,7 +4751,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["params": {"entity": {"type": "string",- "description": "Entity slug; its facts, newest first."+ "description": "Entity slug; its facts."+ },+ "question": {+ "type": "string",+ "description": "Rank facts by relevance to it."},"query": {"type": "string",@@ -4767,7 +4771,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["facts_first","query_first"],- "description": "facts_first (default) or query_first."+ "description": "Default facts_first."},"source_id": {"type": "string",@@ -4775,7 +4779,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"since": {"type": "string",- "description": "Since (ISO 8601 or \"8 hours ago\")."+ "description": "ISO 8601 or \"8 hours ago\"."},"session_id": {"type": "string",@@ -4787,7 +4791,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"supersessions": {"type": "boolean",- "description": "Supersession audit log only."+ "description": "Supersession log only."},"limit": {"type": "number",@@ -4795,7 +4799,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"grep": {"type": "string",- "description": "Substring of the fact text."+ "description": "Fact text substring."},"include_pending": {"type": "boolean",@@ -4810,7 +4814,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["page","auto"],- "description": "results[] evidence unit (see search)."+ "description": "results[] unit (see search)."},"return_window": {"type": "number",diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex 7e46f814a6..b4e6f6129f 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -239,22 +239,22 @@ const recall: Operation = {mutating: false,idempotent: true,outputRedaction: { retrieval: { localVerbatim: ['facts'] } },- description: 'MEMORY VERB (v1): read saved facts by entity, since or session_id, newest first, or ranked by `question`; `query` also searches pages. Remote callers see world facts only. One card: entity; reasoning: synthesize.',+ description: 'MEMORY VERB (v1): read saved facts by entity, since or session_id; `query` also searches pages. Remote callers see world facts only. One card: entity; reasoning: synthesize.',params: {- entity: { type: 'string', description: 'Entity slug; its facts, newest first.' },- question: { type: 'string', description: 'Rank saved facts by relevance to this question instead of recency; does not search pages. Max 2000 chars.' },+ entity: { type: 'string', description: 'Entity slug; its facts.' },+ question: { type: 'string', description: 'Rank facts by relevance to it.' },query: { type: 'string', description: 'Also search pages (results[]).' },budget_tokens: { type: 'number', description: 'Token budget; facts pack first.' },- budget_policy: { type: 'string', enum: ['facts_first', 'query_first'], description: 'facts_first (default) or query_first.' },+ budget_policy: { type: 'string', enum: ['facts_first', 'query_first'], description: 'Default facts_first.' },source_id: { type: 'string', description: 'One source you may read.' },- since: { type: 'string', description: 'Since (ISO 8601 or "8 hours ago").' },+ since: { type: 'string', description: 'ISO 8601 or "8 hours ago".' },session_id: { type: 'string', description: "This session's facts." },include_expired: { type: 'boolean', description: 'Include expired.' },- supersessions: { type: 'boolean', description: 'Supersession audit log only.' },+ supersessions: { type: 'boolean', description: 'Supersession log only.' },limit: { type: 'number', description: 'Per-arm max (default 50, cap 100).' },- grep: { type: 'string', description: 'Substring of the fact text.' },+ grep: { type: 'string', description: 'Fact text substring.' },include_pending: { type: 'boolean', description: 'Pending count.' },- return_unit: { type: 'string', enum: ['chunk', 'window', 'section', 'page', 'auto'], description: 'results[] evidence unit (see search).' },+ return_unit: { type: 'string', enum: ['chunk', 'window', 'section', 'page', 'auto'], description: 'results[] unit (see search).' },return_window: { type: 'number', description: 'Window size 1-3.' },min_trust: MIN_TRUST_PARAM,},diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex ed00b02841..7cdcfafcf0 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 232;+export const LATEST_SCHEMA_VERSION = 233;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex a485bbbba3..5612e410b9 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -233,6 +233,7 @@ 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';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -464,4 +465,5 @@ export const MIGRATIONS: Migration[] = [v230,v231,v232,+ v233,];diff --git a/src/core/schema-migrations/v233-facts-question-recall-indexes.ts b/src/core/schema-migrations/v233-facts-question-recall-indexes.tsnew file mode 100644index 0000000000..136a0e9339--- /dev/null+++ b/src/core/schema-migrations/v233-facts-question-recall-indexes.ts@@ -0,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,+ 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 --git a/src/core/search/entity-anchor.ts b/src/core/search/entity-anchor.tsindex 61a9581a6b..d716a56b44 100644--- a/src/core/search/entity-anchor.ts+++ b/src/core/search/entity-anchor.ts@@ -76,9 +76,11 @@ interface EntityCandidate { id: number; slug: string; title: string; type: strinexport async function namedEntity(engine: BrainEngine, query: string, scope: PageReadScope): Promise<EntityCandidate | null> {const params: unknown[] = [query.toLowerCase()];const filter = pageReadFilter('p', scope, params, true);+ // The title match runs first over bare rows; the read filter (page visibility subqueries) then sees only the matches.const rows = await engine.executeRaw<EntityCandidate>(- `SELECT p.id, p.slug, p.title, p.type, p.source_id FROM pages p- WHERE ${filter} AND p.title IS NOT NULL AND length(p.title) >= 3 AND strpos($1, lower(p.title)) > 0+ `WITH titled AS MATERIALIZED (SELECT id FROM pages WHERE title IS NOT NULL AND length(title) >= 3 AND strpos($1, lower(title)) > 0)+ SELECT p.id, p.slug, p.title, p.type, p.source_id FROM pages p+ WHERE p.id IN (SELECT id FROM titled) AND ${filter}ORDER BY p.source_id, p.slug LIMIT 50`, params);const matches = rows.filter(r => isFactEntityPage(r.slug, r.type) && isTitleMentionedInQuery(query, r.title));const outer = matches.filter(m => !matches.some(o => o !== m && o.title.length > m.title.length && containsTokenRun(tokenizeTitle(o.title), tokenizeTitle(m.title))));diff --git a/src/core/search/fact-relevance.ts b/src/core/search/fact-relevance.tsindex 7daea90ba2..dfa25618e2 100644--- a/src/core/search/fact-relevance.ts+++ b/src/core/search/fact-relevance.ts@@ -25,7 +25,7 @@import type { BrainEngine } from '../engine.ts';import type { TrustTier } from '../trust/tier.ts';import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';-import { getFtsLanguage } from '../fts-language.ts';+import { factsFtsDocument, getFtsLanguage } from '../fts-language.ts';import { getEmbeddingModel } from '../ai/gateway.ts';import { privateProvenanceFilterFragment } from './private-visibility.ts';import { quarantinedProvenanceFilterFragment } from '../quarantine.ts';@@ -136,9 +136,9 @@ function poolPredicate(scope: FactPoolScope, filters: FactPoolFilters | undefinereturn { where: clauses.join(' AND '), params };}-/** The comparable-embedding predicate: same model, current text hash, same dimensions. */-const comparable = (model: string, dims: string) =>- `f.embedding IS NOT NULL AND f.embedding_model = ${model} AND f.embedded_text_hash = md5(f.fact) AND vector_dims(f.embedding) = ${dims}`;+/** The comparable-embedding predicate: same model, current text hash, same dimensions (`dims` null when the column declares the query's). */+const comparable = (model: string, dims: string | null) =>+ `f.embedding IS NOT NULL AND f.embedding_model = ${model} AND f.embedded_text_hash = md5(f.fact)${dims ? ` AND vector_dims(f.embedding) = ${dims}` : ''}`;/*** The bounded candidate pool for `question`. Throws on a database error@@ -165,40 +165,46 @@ export async function collectFactCandidates(engine: BrainEngine, question: strin}};- if (terms.length) {+ type Row = FactCandidate & { similarity?: number | null };+ const keyword = async (): Promise<Row[]> => {+ if (!terms.length) return [];const p = armParams(allSim ? simParams : []);- const lang = `$${p.length + 1}`;- const q = `$${p.length + 2}`;- const doc = `to_tsvector(${lang}::regconfig, f.fact || ' ' || replace(COALESCE(f.entity_slug, ''), '-', ' '))`;- add(await engine.executeRaw(- `WITH q AS (SELECT NULLIF(replace(plainto_tsquery(${lang}::regconfig, ${q})::text, ' & ', ' | '), '')::tsquery AS q)+ const doc = factsFtsDocument('f');+ return engine.executeRaw<Row>(+ `WITH q AS (SELECT NULLIF(replace(plainto_tsquery('${getFtsLanguage()}'::regconfig, $${p.length + 1})::text, ' & ', ' | '), '')::tsquery AS q)SELECT ${COLS}, ${allSim ? simSql : 'NULL::float8 AS similarity'} FROM facts f, q WHERE ${where} AND q.q IS NOT NULL AND ${doc} @@ q.q- ORDER BY ts_rank_cd(${doc}, q.q) DESC, f.valid_from DESC, f.id DESC LIMIT $${p.length + 3}`,- [...p, getFtsLanguage(), terms.join(' '), opts.depth.keyword]));- }- if (vec) {+ ORDER BY ts_rank_cd(${doc}, q.q) DESC, f.valid_from DESC, f.id DESC LIMIT $${p.length + 2}`,+ [...p, terms.join(' '), opts.depth.keyword]);+ };+ const nearest = async (): Promise<Row[]> => {+ if (!vec) return [];const p = armParams(simParams);- const sql = `SELECT ${COLS}, ${simSql} FROM facts f WHERE ${where} AND ${comparable(`$${n + 2}`, `$${n + 3}`)}- ORDER BY f.embedding <=> $${n + 1}${vec.cast}, f.id DESC LIMIT $${p.length + 1}`;+ const sql = `SELECT ${COLS}, ${simSql} FROM facts f WHERE ${where} AND f.embedding IS NOT NULL AND f.embedding_model = $${n + 2}${column!.dims > 0 ? '' : ` AND vector_dims(f.embedding) = $${n + 3}`}+ ORDER BY f.embedding <=> $${n + 1}${vec.cast} LIMIT $${p.length + 1}`;const bound = [...p, opts.depth.cosine];- add(opts.hnswIterativeScan- ? await engine.transaction(async tx => {- const iterative = opts.hnswIterativeScan !== 'off'- && supportsHnswIterativeScan((await tx.executeRaw<{ extversion: string }>(VECTOR_EXTENSION_VERSION_SQL))[0]?.extversion);- return withVectorSettings((s, v) => tx.executeRaw(s, v), iterative, opts.depth.cosine, 20_000,- () => tx.executeRaw<FactCandidate & { similarity: number }>(sql, bound), undefined, opts.hnswIterativeScan);- })- : await engine.executeRaw<FactCandidate & { similarity: number }>(sql, bound));- }- const sourceIds = scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? 'default'];- const named = await namedEntity(engine, question, { sourceIds, excludePrivate: scope.excludePrivate });- if (named) {+ if (!opts.hnswIterativeScan) return engine.executeRaw<Row>(sql, bound);+ return engine.transaction(async tx => {+ const iterative = opts.hnswIterativeScan !== 'off'+ && supportsHnswIterativeScan((await tx.executeRaw<{ extversion: string }>(VECTOR_EXTENSION_VERSION_SQL))[0]?.extversion);+ return withVectorSettings((s, v) => tx.executeRaw(s, v), iterative, opts.depth.cosine, 20_000,+ () => tx.executeRaw<Row>(sql, bound), undefined, opts.hnswIterativeScan);+ });+ };+ const entityFacts = async (): Promise<Row[]> => {+ const sourceIds = scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? 'default'];+ const named = await namedEntity(engine, question, { sourceIds, excludePrivate: scope.excludePrivate });+ if (!named) return [];const p = armParams(allSim ? simParams : []);- add(await engine.executeRaw(+ return engine.executeRaw<Row>(`SELECT ${COLS}, ${allSim ? simSql : 'NULL::float8 AS similarity'} FROM facts f WHERE ${where} AND f.source_id = $${p.length + 1} AND f.entity_slug = $${p.length + 2}ORDER BY f.valid_from DESC, f.id DESC LIMIT $${p.length + 3}`,- [...p, named.source_id, named.slug, opts.depth.entity]), true);- }+ [...p, named.source_id, named.slug, opts.depth.entity]);+ };+ // Independent arms run concurrently (separate connections on Postgres); merged in a fixed order.+ const [byKeyword, byCosine, byEntity] = await Promise.all([keyword(), nearest(), entityFacts()]);+ add(byKeyword);+ add(byCosine);+ add(byEntity, true);return { candidates: [...found.values()], cosine, column: !!column };}@@ -209,9 +215,19 @@ export async function collectFactCandidates(engine: BrainEngine, question: strin*/export async function countUncomparableFacts(engine: BrainEngine, scope: FactPoolScope, filters: FactPoolFilters | undefined, dims: number): Promise<Array<{ source_id: string; n: number }>> {const { where, params } = poolPredicate(scope, filters);+ const model = `$${params.length + 1}`;+ const column = await factsEmbeddingColumn(engine);+ if (!column) return [];+ const declared = column.dims === dims;+ // Cheap candidates first (idx_facts_unembedded, idx_facts_embedding_model), then the read policy on those rows only.+ const uncomparable = declared+ ? `SELECT f.id FROM facts f WHERE f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND (f.embedding IS NULL OR f.embedded_text_hash IS DISTINCT FROM md5(f.fact))+ UNION SELECT f.id FROM facts f WHERE f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND (f.embedding_model IS NULL OR f.embedding_model < ${model} OR f.embedding_model > ${model})`+ : `SELECT f.id FROM facts f WHERE f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND NOT (${comparable(model, `$${params.length + 2}`)})`;const rows = await engine.executeRaw<{ source_id: string; n: number | string }>(- `SELECT f.source_id, count(*) AS n FROM facts f WHERE ${where} AND NOT (${comparable(`$${params.length + 1}`, `$${params.length + 2}`)})- GROUP BY f.source_id ORDER BY count(*) DESC, f.source_id`, [...params, getEmbeddingModel(), dims]);+ `WITH u AS MATERIALIZED (${uncomparable})+ SELECT f.source_id, count(*) AS n FROM facts f WHERE f.id IN (SELECT id FROM u) AND ${where}+ GROUP BY f.source_id ORDER BY count(*) DESC, f.source_id`, [...params, getEmbeddingModel(), ...(declared ? [] : [dims])]);return rows.map(r => ({ source_id: r.source_id, n: Number(r.n) }));}diff --git a/src/core/verbs.ts b/src/core/verbs.tsindex a00cf18fc5..5b31cae065 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -512,9 +512,19 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {provenance: { type: 'string' },valid_until: { type: ['string', 'null'] },visibility: { type: 'string', enum: ['private', 'world'] },+ relevance: { type: 'number', description: 'Present when `question` was passed: cosine + term share + 0.1 when dated (about 0 to 2.1). A ranking score within this response, not a probability; not comparable across calls.' },},},},+ facts_order: { type: 'string', enum: ['relevance', 'newest'], description: 'How facts[] is ordered: relevance (question passed) or newest. A server without question ranking omits it.' },+ facts_degraded: {+ type: 'object',+ description: 'Present when question ranking ran without full semantic matching.',+ properties: {+ reason: { type: 'string', description: 'Why the cosine arm did not run: keyword_only_no_embedding_provider, keyword_only_embedding_disabled, embed_timeout, embed_unavailable, no_query_terms or facts_embedding_column_missing.' },+ unembedded: { type: 'integer', description: 'Facts in scope without a comparable embedding (ranked by word overlap only).' },+ },+ },results: {type: 'array',description: 'Search arm — present only when `query` was passed.',diff --git a/test/e2e/recall-question-postgres.test.ts b/test/e2e/recall-question-postgres.test.tsnew file mode 100644index 0000000000..ca2a20c973--- /dev/null+++ b/test/e2e/recall-question-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../recall-question.test.ts'));diff --git a/test/e2e/schema-catalog-golden.test.ts b/test/e2e/schema-catalog-golden.test.tsindex 36be5cbca2..fc29f2296f 100644--- a/test/e2e/schema-catalog-golden.test.ts+++ b/test/e2e/schema-catalog-golden.test.ts@@ -182,10 +182,11 @@ describe.skipIf(skip)('Postgres catalog goldens (E4, E2E)', () => {}});- test('non-default FTS language changes only function bodies', () => {+ test('non-default FTS language changes only function bodies and the facts keyword index', () => {const diff = diffCatalogSnapshots(requireCaptured('engine:default'), requireCaptured('engine:fts-portuguese'));expect(diff.length).toBeGreaterThan(0);- expect([...new Set(diff.map((d) => d.section))]).toEqual(['functions']);+ expect([...new Set(diff.map((d) => d.section))].sort()).toEqual(['functions', 'indexes']);+ expect(diff.filter((d) => d.section === 'indexes').map((d) => d.key)).toEqual(['idx_facts_fts']);});test('T-G13: PG <-> PGLite column parity stays name-based (existing drift contract)', async () => {diff --git a/test/embedding-migration.test.ts b/test/embedding-migration.test.tsindex dc436aadab..fa7ed44193 100644--- a/test/embedding-migration.test.ts+++ b/test/embedding-migration.test.ts@@ -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 () => {+ 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 --git a/test/fact-relevance.test.ts b/test/fact-relevance.test.tsnew file mode 100644index 0000000000..41cc363bfb--- /dev/null+++ b/test/fact-relevance.test.ts@@ -0,0 +1,74 @@+/**+ * The shared fact scorer (src/core/search/fact-relevance.ts), pure parts:+ * whole-word term share, the per-fact stuffing cap, the dated bonus, the+ * (score, valid_from, id) order and both preregistered admission rules.+ */+import { describe, expect, test } from 'bun:test';+import { DATED_BONUS, TERM_STUFFING_RATIO, admitted, scoreFactCandidates, type FactCandidate } from '../src/core/search/fact-relevance.ts';++let next = 1;+function cand(fact: string, extra: Partial<FactCandidate> = {}): FactCandidate {+ const at = extra.created_at ?? '2026-01-10T00:00:00Z';+ return {+ id: next++, fact, kind: 'fact', entity_slug: null, source_id: 'default', source: 'test',+ valid_from: at, valid_until: null, created_at: at, claim_metric: null, claim_period: null, entity: false, ...extra,+ };+}++describe('fact scorer', () => {+ test('term share counts whole words, never substrings', () => {+ const [s] = scoreFactCandidates('rust compiler', [cand('We trust the compilers team')]);+ expect(s!.matched).toBe(0);+ expect(s!.termShare).toBe(0);+ const [w] = scoreFactCandidates('rust compiler', [cand('The rust compiler got faster')]);+ expect(w!.matched).toBe(2);+ expect(w!.termShare).toBe(1);+ });++ test('entity slugs match as words, hyphenated and split', () => {+ const [s] = scoreFactCandidates('alice offsite', [cand('Booked the offsite', { entity_slug: 'alice-example' })]);+ expect(s!.matched).toBe(2);+ });++ test('a fact with many more content terms than the question has its term share scaled down', () => {+ const question = 'coffee roast morning';+ const stuffed = cand(`coffee roast morning ${Array.from({ length: 60 }, (_, i) => `word${i}x`).join(' ')}`);+ const [s] = scoreFactCandidates(question, [stuffed]);+ expect(s!.matched).toBe(3);+ expect(s!.termShare).toBeCloseTo(3 / Math.ceil(63 / TERM_STUFFING_RATIO), 6);+ expect(admitted(s!, 'reserve')).toBe(false);+ const [plain] = scoreFactCandidates(question, [cand('Dark roast coffee every morning')]);+ expect(plain!.termShare).toBe(1);+ expect(admitted(plain!, 'reserve')).toBe(true);+ });++ test('score is cosine + term share + the dated bonus when valid_from is a writer-supplied date', () => {+ const dated = cand('trip to Lisbon', { valid_from: '2025-05-01T00:00:00Z', created_at: '2026-01-10T00:00:00Z', similarity: 0.4 });+ const [s] = scoreFactCandidates('lisbon trip', [dated]);+ expect(s!.score).toBeCloseTo(0.4 + 1 + DATED_BONUS, 6);+ });++ test('ties order by newest valid_from, then id', () => {+ const older = cand('kayak lesson', { valid_from: '2026-01-01T00:00:00Z', created_at: '2026-01-01T00:00:00Z' });+ const newer = cand('kayak lesson', { valid_from: '2026-01-05T00:00:00Z', created_at: '2026-01-05T00:00:00Z' });+ const sameTimeA = cand('kayak lesson', { valid_from: '2026-01-05T00:00:00Z', created_at: '2026-01-05T00:00:00Z' });+ const order = scoreFactCandidates('kayak lesson', [older, newer, sameTimeA]).map(s => s.candidate.id);+ expect(order).toEqual([sameTimeA.id, newer.id, older.id]);+ });++ test('the two admission rules: reserve (cosine 0.5 or share 0.34) and facts arm (cosine 0.6, half the terms, or the named entity)', () => {+ const q = 'alpha beta gamma delta';+ const [oneTerm] = scoreFactCandidates(q, [cand('alpha only here')]);+ expect(admitted(oneTerm!, 'reserve')).toBe(false);+ expect(admitted(oneTerm!, 'facts_arm')).toBe(false);+ const [twoTerms] = scoreFactCandidates(q, [cand('alpha and beta')]);+ expect(admitted(twoTerms!, 'reserve')).toBe(true);+ expect(admitted(twoTerms!, 'facts_arm')).toBe(true);+ const [cos55] = scoreFactCandidates(q, [cand('unrelated words', { similarity: 0.55 })]);+ expect(admitted(cos55!, 'reserve')).toBe(true);+ expect(admitted(cos55!, 'facts_arm')).toBe(false);+ const [entity] = scoreFactCandidates(q, [cand('unrelated words', { entity: true })]);+ expect(admitted(entity!, 'reserve')).toBe(false);+ expect(admitted(entity!, 'facts_arm')).toBe(true);+ });+});diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex a099eafc92..9a21b8cc09 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -990,14 +990,17 @@"idx_extract_rollup_7d_day": "CREATE INDEX idx_extract_rollup_7d_day ON public.extract_rollup_7d USING btree (day)","idx_facts_dimension": "CREATE INDEX idx_facts_dimension ON public.facts USING btree (source_id, entity_slug, dimension, valid_from DESC) WHERE ((expired_at IS NULL) AND (dimension IS NOT NULL))","idx_facts_embedding_hnsw": "CREATE INDEX idx_facts_embedding_hnsw ON public.facts USING hnsw (embedding halfvec_cosine_ops) WHERE ((embedding IS NOT NULL) AND (expired_at IS NULL))",+ "idx_facts_embedding_model": "CREATE INDEX idx_facts_embedding_model ON public.facts USING btree (source_id, embedding_model) WHERE (expired_at IS NULL)","idx_facts_entity_active": "CREATE INDEX idx_facts_entity_active ON public.facts USING btree (source_id, entity_slug, valid_from DESC) WHERE (expired_at IS NULL)","idx_facts_extract_conversation_session": "CREATE INDEX idx_facts_extract_conversation_session ON public.facts USING btree (source_id, source_session) WHERE (source ~~ 'cli:extract-conversation-facts%'::text)","idx_facts_fence_key": "CREATE UNIQUE INDEX idx_facts_fence_key ON public.facts USING btree (source_id, source_markdown_slug, row_num) WHERE (row_num IS NOT NULL)",+ "idx_facts_fts": "CREATE INDEX idx_facts_fts ON public.facts USING gin (to_tsvector('english'::regconfig, ((fact || ' '::text) || replace(COALESCE(entity_slug, ''::text), '-'::text, ' '::text)))) WHERE (expired_at IS NULL)","idx_facts_ontology_stint_dedup": "CREATE UNIQUE INDEX idx_facts_ontology_stint_dedup ON public.facts USING btree (source_id, entity_slug, dimension, value_hash, source_markdown_slug, valid_from) WHERE (dimension IS NOT NULL)","idx_facts_session": "CREATE INDEX idx_facts_session ON public.facts USING btree (source_id, source_session, created_at DESC) WHERE (expired_at IS NULL)","idx_facts_since": "CREATE INDEX idx_facts_since ON public.facts USING btree (source_id, created_at DESC) WHERE (expired_at IS NULL)","idx_facts_since_event_time": "CREATE INDEX idx_facts_since_event_time ON public.facts USING btree (source_id, COALESCE(valid_from, created_at) DESC) WHERE (expired_at IS NULL)","idx_facts_unconsolidated": "CREATE INDEX idx_facts_unconsolidated ON public.facts USING btree (source_id, entity_slug) WHERE ((consolidated_at IS NULL) AND (expired_at IS NULL))",+ "idx_facts_unembedded": "CREATE INDEX idx_facts_unembedded ON public.facts USING btree (source_id) WHERE ((expired_at IS NULL) AND ((embedding IS NULL) OR (embedded_text_hash IS DISTINCT FROM md5(fact))))","idx_facts_unlinked_active": "CREATE INDEX idx_facts_unlinked_active ON public.facts USING btree (source_id, id) WHERE ((entity_slug IS NULL) AND (expired_at IS NULL))","idx_facts_withdrawal_fingerprint": "CREATE INDEX idx_facts_withdrawal_fingerprint ON public.facts USING btree (source_id, visibility, gbrain_fact_fingerprint(fact))","idx_files_hash": "CREATE INDEX idx_files_hash ON public.files USING btree (content_hash)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 8d3a3b23e8..9d77f3d1aa 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -990,14 +990,17 @@"idx_extract_rollup_7d_day": "CREATE INDEX idx_extract_rollup_7d_day ON public.extract_rollup_7d USING btree (day)","idx_facts_dimension": "CREATE INDEX idx_facts_dimension ON public.facts USING btree (source_id, entity_slug, dimension, valid_from DESC) WHERE ((expired_at IS NULL) AND (dimension IS NOT NULL))","idx_facts_embedding_hnsw": "CREATE INDEX idx_facts_embedding_hnsw ON public.facts USING hnsw (embedding halfvec_cosine_ops) WHERE ((embedding IS NOT NULL) AND (expired_at IS NULL))",+ "idx_facts_embedding_model": "CREATE INDEX idx_facts_embedding_model ON public.facts USING btree (source_id, embedding_model) WHERE (expired_at IS NULL)","idx_facts_entity_active": "CREATE INDEX idx_facts_entity_active ON public.facts USING btree (source_id, entity_slug, valid_from DESC) WHERE (expired_at IS NULL)","idx_facts_extract_conversation_session": "CREATE INDEX idx_facts_extract_conversation_session ON public.facts USING btree (source_id, source_session) WHERE (source ~~ 'cli:extract-conversation-facts%'::text)","idx_facts_fence_key": "CREATE UNIQUE INDEX idx_facts_fence_key ON public.facts USING btree (source_id, source_markdown_slug, row_num) WHERE (row_num IS NOT NULL)",+ "idx_facts_fts": "CREATE INDEX idx_facts_fts ON public.facts USING gin (to_tsvector('portuguese'::regconfig, ((fact || ' '::text) || replace(COALESCE(entity_slug, ''::text), '-'::text, ' '::text)))) WHERE (expired_at IS NULL)","idx_facts_ontology_stint_dedup": "CREATE UNIQUE INDEX idx_facts_ontology_stint_dedup ON public.facts USING btree (source_id, entity_slug, dimension, value_hash, source_markdown_slug, valid_from) WHERE (dimension IS NOT NULL)","idx_facts_session": "CREATE INDEX idx_facts_session ON public.facts USING btree (source_id, source_session, created_at DESC) WHERE (expired_at IS NULL)","idx_facts_since": "CREATE INDEX idx_facts_since ON public.facts USING btree (source_id, created_at DESC) WHERE (expired_at IS NULL)","idx_facts_since_event_time": "CREATE INDEX idx_facts_since_event_time ON public.facts USING btree (source_id, COALESCE(valid_from, created_at) DESC) WHERE (expired_at IS NULL)","idx_facts_unconsolidated": "CREATE INDEX idx_facts_unconsolidated ON public.facts USING btree (source_id, entity_slug) WHERE ((consolidated_at IS NULL) AND (expired_at IS NULL))",+ "idx_facts_unembedded": "CREATE INDEX idx_facts_unembedded ON public.facts USING btree (source_id) WHERE ((expired_at IS NULL) AND ((embedding IS NULL) OR (embedded_text_hash IS DISTINCT FROM md5(fact))))","idx_facts_unlinked_active": "CREATE INDEX idx_facts_unlinked_active ON public.facts USING btree (source_id, id) WHERE ((entity_slug IS NULL) AND (expired_at IS NULL))","idx_facts_withdrawal_fingerprint": "CREATE INDEX idx_facts_withdrawal_fingerprint ON public.facts USING btree (source_id, visibility, gbrain_fact_fingerprint(fact))","idx_files_hash": "CREATE INDEX idx_files_hash ON public.files USING btree (content_hash)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex cfd3aeab82..c0408ea8f9 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -988,14 +988,17 @@"idx_eval_capture_failures_ts": "CREATE INDEX idx_eval_capture_failures_ts ON public.eval_capture_failures USING btree (ts DESC)","idx_extract_rollup_7d_day": "CREATE INDEX idx_extract_rollup_7d_day ON public.extract_rollup_7d USING btree (day)","idx_facts_dimension": "CREATE INDEX idx_facts_dimension ON public.facts USING btree (source_id, entity_slug, dimension, valid_from DESC) WHERE ((expired_at IS NULL) AND (dimension IS NOT NULL))",+ "idx_facts_embedding_model": "CREATE INDEX idx_facts_embedding_model ON public.facts USING btree (source_id, embedding_model) WHERE (expired_at IS NULL)","idx_facts_entity_active": "CREATE INDEX idx_facts_entity_active ON public.facts USING btree (source_id, entity_slug, valid_from DESC) WHERE (expired_at IS NULL)","idx_facts_extract_conversation_session": "CREATE INDEX idx_facts_extract_conversation_session ON public.facts USING btree (source_id, source_session) WHERE (source ~~ 'cli:extract-conversation-facts%'::text)","idx_facts_fence_key": "CREATE UNIQUE INDEX idx_facts_fence_key ON public.facts USING btree (source_id, source_markdown_slug, row_num) WHERE (row_num IS NOT NULL)",+ "idx_facts_fts": "CREATE INDEX idx_facts_fts ON public.facts USING gin (to_tsvector('english'::regconfig, ((fact || ' '::text) || replace(COALESCE(entity_slug, ''::text), '-'::text, ' '::text)))) WHERE (expired_at IS NULL)","idx_facts_ontology_stint_dedup": "CREATE UNIQUE INDEX idx_facts_ontology_stint_dedup ON public.facts USING btree (source_id, entity_slug, dimension, value_hash, source_markdown_slug, valid_from) WHERE (dimension IS NOT NULL)","idx_facts_session": "CREATE INDEX idx_facts_session ON public.facts USING btree (source_id, source_session, created_at DESC) WHERE (expired_at IS NULL)","idx_facts_since": "CREATE INDEX idx_facts_since ON public.facts USING btree (source_id, created_at DESC) WHERE (expired_at IS NULL)","idx_facts_since_event_time": "CREATE INDEX idx_facts_since_event_time ON public.facts USING btree (source_id, COALESCE(valid_from, created_at) DESC) WHERE (expired_at IS NULL)","idx_facts_unconsolidated": "CREATE INDEX idx_facts_unconsolidated ON public.facts USING btree (source_id, entity_slug) WHERE ((consolidated_at IS NULL) AND (expired_at IS NULL))",+ "idx_facts_unembedded": "CREATE INDEX idx_facts_unembedded ON public.facts USING btree (source_id) WHERE ((expired_at IS NULL) AND ((embedding IS NULL) OR (embedded_text_hash IS DISTINCT FROM md5(fact))))","idx_facts_unlinked_active": "CREATE INDEX idx_facts_unlinked_active ON public.facts USING btree (source_id, id) WHERE ((entity_slug IS NULL) AND (expired_at IS NULL))","idx_facts_withdrawal_fingerprint": "CREATE INDEX idx_facts_withdrawal_fingerprint ON public.facts USING btree (source_id, visibility, gbrain_fact_fingerprint(fact))","idx_files_hash": "CREATE INDEX idx_files_hash ON public.files USING btree (content_hash)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 6790dcad8d..5ae909ed41 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -992,14 +992,17 @@"idx_extract_rollup_7d_day": "CREATE INDEX idx_extract_rollup_7d_day ON public.extract_rollup_7d USING btree (day)","idx_facts_dimension": "CREATE INDEX idx_facts_dimension ON public.facts USING btree (source_id, entity_slug, dimension, valid_from DESC) WHERE ((expired_at IS NULL) AND (dimension IS NOT NULL))","idx_facts_embedding_hnsw": "CREATE INDEX idx_facts_embedding_hnsw ON public.facts USING hnsw (embedding halfvec_cosine_ops) WHERE ((embedding IS NOT NULL) AND (expired_at IS NULL))",+ "idx_facts_embedding_model": "CREATE INDEX idx_facts_embedding_model ON public.facts USING btree (source_id, embedding_model) WHERE (expired_at IS NULL)","idx_facts_entity_active": "CREATE INDEX idx_facts_entity_active ON public.facts USING btree (source_id, entity_slug, valid_from DESC) WHERE (expired_at IS NULL)","idx_facts_extract_conversation_session": "CREATE INDEX idx_facts_extract_conversation_session ON public.facts USING btree (source_id, source_session) WHERE (source ~~ 'cli:extract-conversation-facts%'::text)","idx_facts_fence_key": "CREATE UNIQUE INDEX idx_facts_fence_key ON public.facts USING btree (source_id, source_markdown_slug, row_num) WHERE (row_num IS NOT NULL)",+ "idx_facts_fts": "CREATE INDEX idx_facts_fts ON public.facts USING gin (to_tsvector('english'::regconfig, ((fact || ' '::text) || replace(COALESCE(entity_slug, ''::text), '-'::text, ' '::text)))) WHERE (expired_at IS NULL)","idx_facts_ontology_stint_dedup": "CREATE UNIQUE INDEX idx_facts_ontology_stint_dedup ON public.facts USING btree (source_id, entity_slug, dimension, value_hash, source_markdown_slug, valid_from) WHERE (dimension IS NOT NULL)","idx_facts_session": "CREATE INDEX idx_facts_session ON public.facts USING btree (source_id, source_session, created_at DESC) WHERE (expired_at IS NULL)","idx_facts_since": "CREATE INDEX idx_facts_since ON public.facts USING btree (source_id, created_at DESC) WHERE (expired_at IS NULL)","idx_facts_since_event_time": "CREATE INDEX idx_facts_since_event_time ON public.facts USING btree (source_id, COALESCE(valid_from, created_at) DESC) WHERE (expired_at IS NULL)","idx_facts_unconsolidated": "CREATE INDEX idx_facts_unconsolidated ON public.facts USING btree (source_id, entity_slug) WHERE ((consolidated_at IS NULL) AND (expired_at IS NULL))",+ "idx_facts_unembedded": "CREATE INDEX idx_facts_unembedded ON public.facts USING btree (source_id) WHERE ((expired_at IS NULL) AND ((embedding IS NULL) OR (embedded_text_hash IS DISTINCT FROM md5(fact))))","idx_facts_unlinked_active": "CREATE INDEX idx_facts_unlinked_active ON public.facts USING btree (source_id, id) WHERE ((entity_slug IS NULL) AND (expired_at IS NULL))","idx_facts_withdrawal_fingerprint": "CREATE INDEX idx_facts_withdrawal_fingerprint ON public.facts USING btree (source_id, visibility, gbrain_fact_fingerprint(fact))","idx_file_migration_ledger_status": "CREATE INDEX idx_file_migration_ledger_status ON public.file_migration_ledger USING btree (status) WHERE (status <> 'complete'::text)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 46799ee911..1fce7d2f8b 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -992,14 +992,17 @@"idx_extract_rollup_7d_day": "CREATE INDEX idx_extract_rollup_7d_day ON public.extract_rollup_7d USING btree (day)","idx_facts_dimension": "CREATE INDEX idx_facts_dimension ON public.facts USING btree (source_id, entity_slug, dimension, valid_from DESC) WHERE ((expired_at IS NULL) AND (dimension IS NOT NULL))","idx_facts_embedding_hnsw": "CREATE INDEX idx_facts_embedding_hnsw ON public.facts USING hnsw (embedding halfvec_cosine_ops) WHERE ((embedding IS NOT NULL) AND (expired_at IS NULL))",+ "idx_facts_embedding_model": "CREATE INDEX idx_facts_embedding_model ON public.facts USING btree (source_id, embedding_model) WHERE (expired_at IS NULL)","idx_facts_entity_active": "CREATE INDEX idx_facts_entity_active ON public.facts USING btree (source_id, entity_slug, valid_from DESC) WHERE (expired_at IS NULL)","idx_facts_extract_conversation_session": "CREATE INDEX idx_facts_extract_conversation_session ON public.facts USING btree (source_id, source_session) WHERE (source ~~ 'cli:extract-conversation-facts%'::text)","idx_facts_fence_key": "CREATE UNIQUE INDEX idx_facts_fence_key ON public.facts USING btree (source_id, source_markdown_slug, row_num) WHERE (row_num IS NOT NULL)",+ "idx_facts_fts": "CREATE INDEX idx_facts_fts ON public.facts USING gin (to_tsvector('portuguese'::regconfig, ((fact || ' '::text) || replace(COALESCE(entity_slug, ''::text), '-'::text, ' '::text)))) WHERE (expired_at IS NULL)","idx_facts_ontology_stint_dedup": "CREATE UNIQUE INDEX idx_facts_ontology_stint_dedup ON public.facts USING btree (source_id, entity_slug, dimension, value_hash, source_markdown_slug, valid_from) WHERE (dimension IS NOT NULL)","idx_facts_session": "CREATE INDEX idx_facts_session ON public.facts USING btree (source_id, source_session, created_at DESC) WHERE (expired_at IS NULL)","idx_facts_since": "CREATE INDEX idx_facts_since ON public.facts USING btree (source_id, created_at DESC) WHERE (expired_at IS NULL)","idx_facts_since_event_time": "CREATE INDEX idx_facts_since_event_time ON public.facts USING btree (source_id, COALESCE(valid_from, created_at) DESC) WHERE (expired_at IS NULL)","idx_facts_unconsolidated": "CREATE INDEX idx_facts_unconsolidated ON public.facts USING btree (source_id, entity_slug) WHERE ((consolidated_at IS NULL) AND (expired_at IS NULL))",+ "idx_facts_unembedded": "CREATE INDEX idx_facts_unembedded ON public.facts USING btree (source_id) WHERE ((expired_at IS NULL) AND ((embedding IS NULL) OR (embedded_text_hash IS DISTINCT FROM md5(fact))))","idx_facts_unlinked_active": "CREATE INDEX idx_facts_unlinked_active ON public.facts USING btree (source_id, id) WHERE ((entity_slug IS NULL) AND (expired_at IS NULL))","idx_facts_withdrawal_fingerprint": "CREATE INDEX idx_facts_withdrawal_fingerprint ON public.facts USING btree (source_id, visibility, gbrain_fact_fingerprint(fact))","idx_file_migration_ledger_status": "CREATE INDEX idx_file_migration_ledger_status ON public.file_migration_ledger USING btree (status) WHERE (status <> 'complete'::text)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 488085377e..9f9c318465 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -990,14 +990,17 @@"idx_eval_capture_failures_ts": "CREATE INDEX idx_eval_capture_failures_ts ON public.eval_capture_failures USING btree (ts DESC)","idx_extract_rollup_7d_day": "CREATE INDEX idx_extract_rollup_7d_day ON public.extract_rollup_7d USING btree (day)","idx_facts_dimension": "CREATE INDEX idx_facts_dimension ON public.facts USING btree (source_id, entity_slug, dimension, valid_from DESC) WHERE ((expired_at IS NULL) AND (dimension IS NOT NULL))",+ "idx_facts_embedding_model": "CREATE INDEX idx_facts_embedding_model ON public.facts USING btree (source_id, embedding_model) WHERE (expired_at IS NULL)","idx_facts_entity_active": "CREATE INDEX idx_facts_entity_active ON public.facts USING btree (source_id, entity_slug, valid_from DESC) WHERE (expired_at IS NULL)","idx_facts_extract_conversation_session": "CREATE INDEX idx_facts_extract_conversation_session ON public.facts USING btree (source_id, source_session) WHERE (source ~~ 'cli:extract-conversation-facts%'::text)","idx_facts_fence_key": "CREATE UNIQUE INDEX idx_facts_fence_key ON public.facts USING btree (source_id, source_markdown_slug, row_num) WHERE (row_num IS NOT NULL)",+ "idx_facts_fts": "CREATE INDEX idx_facts_fts ON public.facts USING gin (to_tsvector('english'::regconfig, ((fact || ' '::text) || replace(COALESCE(entity_slug, ''::text), '-'::text, ' '::text)))) WHERE (expired_at IS NULL)","idx_facts_ontology_stint_dedup": "CREATE UNIQUE INDEX idx_facts_ontology_stint_dedup ON public.facts USING btree (source_id, entity_slug, dimension, value_hash, source_markdown_slug, valid_from) WHERE (dimension IS NOT NULL)","idx_facts_session": "CREATE INDEX idx_facts_session ON public.facts USING btree (source_id, source_session, created_at DESC) WHERE (expired_at IS NULL)","idx_facts_since": "CREATE INDEX idx_facts_since ON public.facts USING btree (source_id, created_at DESC) WHERE (expired_at IS NULL)","idx_facts_since_event_time": "CREATE INDEX idx_facts_since_event_time ON public.facts USING btree (source_id, COALESCE(valid_from, created_at) DESC) WHERE (expired_at IS NULL)","idx_facts_unconsolidated": "CREATE INDEX idx_facts_unconsolidated ON public.facts USING btree (source_id, entity_slug) WHERE ((consolidated_at IS NULL) AND (expired_at IS NULL))",+ "idx_facts_unembedded": "CREATE INDEX idx_facts_unembedded ON public.facts USING btree (source_id) WHERE ((expired_at IS NULL) AND ((embedding IS NULL) OR (embedded_text_hash IS DISTINCT FROM md5(fact))))","idx_facts_unlinked_active": "CREATE INDEX idx_facts_unlinked_active ON public.facts USING btree (source_id, id) WHERE ((entity_slug IS NULL) AND (expired_at IS NULL))","idx_facts_withdrawal_fingerprint": "CREATE INDEX idx_facts_withdrawal_fingerprint ON public.facts USING btree (source_id, visibility, gbrain_fact_fingerprint(fact))","idx_file_migration_ledger_status": "CREATE INDEX idx_file_migration_ledger_status ON public.file_migration_ledger USING btree (status) WHERE (status <> 'complete'::text)",diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 1a1e35e109..4f7babb83b 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 227640,- "stdoutSha256": "16c270d5e53097660f179d20c4e5588d0c5e459c76ac28458fba52e7a186abb4",+ "stdoutBytes": 227727,+ "stdoutSha256": "d287a34cd377d201db103a781a2ef2ea96ea6fab8af6f49225e1f3a8f473cb5d","toolNames": ["remember","entity",@@ -5665,6 +5665,7 @@"limit": "number?","min_trust": "string?","query": "string?",+ "question": "string?","return_unit": "string?","return_window": "number?","session_id": "string?",@@ -5676,7 +5677,7 @@"schema": {"properties": {"budget_policy": {- "description": "facts_first (default) or query_first.",+ "description": "Default facts_first.","enum": ["facts_first","query_first"@@ -5688,11 +5689,11 @@"type": "number"},"entity": {- "description": "Entity slug; its facts, newest first.",+ "description": "Entity slug; its facts.","type": "string"},"grep": {- "description": "Substring of the fact text.",+ "description": "Fact text substring.","type": "string"},"include_expired": {@@ -5723,8 +5724,12 @@"description": "Also search pages (results[]).","type": "string"},+ "question": {+ "description": "Rank facts by relevance to it.",+ "type": "string"+ },"return_unit": {- "description": "results[] evidence unit (see search).",+ "description": "results[] unit (see search).","enum": ["chunk","window",@@ -5743,7 +5748,7 @@"type": "string"},"since": {- "description": "Since (ISO 8601 or \"8 hours ago\").",+ "description": "ISO 8601 or \"8 hours ago\".","type": "string"},"source_id": {@@ -5751,7 +5756,7 @@"type": "string"},"supersessions": {- "description": "Supersession audit log only.",+ "description": "Supersession log only.","type": "boolean"}},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 99a9134378..09fb0ecc8c 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 227,+ "count": 228,"gaps": [17,18,@@ -26,6 +26,7 @@"buildIndexOnline": "ed5378b90f24f7d662e02865cf73af4248e348002661f8fbfd8ee1087c60a3e5","clampOAuthTokenTtls": "b1e94ea8f5b3c3870a56b0f6d00d0a274c2e9dcad912b828848aec250732645f","dropInvalidConcurrentIndex": "6864d844b7dfb2fbecdd0fb9c73e06248473376feb794b3fe58f036c70d2d44c",+ "factsFtsIndexSql": "2bfacc9979a0962b592b2edd3541508259e21f42156fb94d042566461925286c","getFtsLanguage": "0d790b4c4af1f67a2a1bbd59470beb13f434917b381931baf8404a41c5d903db","grantFromRow": "2d0603bb0f964d7e45e04aa76bac54cd4f6f63c91a8d9f028b60b4792bc1695e","hnswMaxDimsForType": "a187cdcc520f813b7c39da97ce53da58509232ed9f851627ef41abfe1b68bd26",@@ -42,7 +43,7 @@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 232,+ "latest": 233,"records": [{"handler": {@@ -3475,6 +3476,26 @@"transaction": "absent","verify": "absent","version": 232+ },+ {+ "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}],"versions": [@@ -3704,7 +3725,8 @@229,230,231,- 232+ 232,+ 233]},"normalizer": "migrations-record-v1"diff --git a/test/helpers/evidence-delivery-fixture.ts b/test/helpers/evidence-delivery-fixture.tsindex 5b79109054..de7d111064 100644--- a/test/helpers/evidence-delivery-fixture.ts+++ b/test/helpers/evidence-delivery-fixture.ts@@ -94,15 +94,26 @@ export function offPathMcpBytes(res: { content: { type: string; text: string }[]const leanRetrieval = (meta: Record<string, unknown>) => ({ ...meta, rows: 'lean' });+/** Recall's additive `facts_order` (MEMORY_VERBS v1), which every response carries right after `total`; these captures are all newest-first. */+function withFactsOrder(payload: Record<string, unknown>): Record<string, unknown> {+ if ('facts_order' in payload || !('total' in payload)) return payload;+ return Object.fromEntries(Object.entries(payload).flatMap(([k, v]) => k === 'total' ? [[k, v], ['facts_order', 'newest']] : [[k, v]]));+}+/*** The cost wave changes remote output on purpose: C1 projects remote* search/query rows to lean rows (and reports `rows: "lean"` in the retrieval- * meta), and C2 serializes MCP content[0] as compact JSON. The frozen- * pre-feature bytes stay as captured; this applies exactly those two declared- * transforms to them, so every other byte of the capture is still compared.+ * meta), and C2 serializes MCP content[0] as compact JSON. Recall's question+ * ranking adds `facts_order` to every recall response. The frozen pre-feature+ * bytes stay as captured; this applies exactly those declared transforms to+ * them, so every other byte of the capture is still compared.*/export function withCostWave(key: string, frozen: string): string {const base = key.replace(/:chunk$/, '');+ if (base === 'recall' || base === 'recall-budget') {+ const v = JSON.parse(frozen) as { result: Record<string, unknown>; meta: unknown };+ return JSON.stringify({ ...v, result: withFactsOrder(v.result) });+ }if (base === 'search-remote') {const v = JSON.parse(frozen) as { result: Record<string, unknown>[]; meta: Array<{ key: string; value: Record<string, unknown> }> };return JSON.stringify({@@ -114,7 +125,7 @@ export function withCostWave(key: string, frozen: string): string {const res = JSON.parse(frozen) as { content: Array<{ type: string; text: string }>; _meta?: Record<string, Record<string, unknown>> };const body = JSON.parse(res.content[0].text);const lean = base === 'mcp-search' || base === 'mcp-query';- res.content[0].text = JSON.stringify(lean ? (body as Record<string, unknown>[]).map(leanRow) : body);+ res.content[0].text = JSON.stringify(lean ? (body as Record<string, unknown>[]).map(leanRow) : base === 'mcp-recall' ? withFactsOrder(body) : body);if (lean && res._meta?.retrieval) res._meta.retrieval = leanRetrieval(res._meta.retrieval);return JSON.stringify(res);}diff --git a/test/mcp-schema-budget.test.ts b/test/mcp-schema-budget.test.tsindex be5cea4373..b30b944741 100644--- a/test/mcp-schema-budget.test.ts+++ b/test/mcp-schema-budget.test.ts@@ -50,7 +50,7 @@ import { cl100kAvailable, estimateTokens } from '../src/core/chunkers/token-esticonst SERVED_STARTER_MAX_CHARS = 25_000;const SERVED_STARTER_MAX_TOKENS = 5_700;-/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0; traverse_graph's `hops` is full-surface-only, 25,941 measured; 26,402 once mute_notice, the dismissal for the coaching notices starter sessions receive, joined starter; 26,671 with #6007's put_page wait_ms param and write guidance, which carry the put_pages hint and the receipt poll rule starter agents need; 26,679 with delta's opaque `cursor` param, paid for by trimming delta's own descriptions, model-visible 24,985). */+/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0; traverse_graph's `hops` is full-surface-only, 25,941 measured; 26,402 once mute_notice, the dismissal for the coaching notices starter sessions receive, joined starter; 26,671 with #6007's put_page wait_ms param and write guidance, which carry the put_pages hint and the receipt poll rule starter agents need; 26,679 with delta's opaque `cursor` param, paid for by trimming delta's own descriptions, model-visible 24,985; 26,692 with recall's `question` param, paid for by trimming recall's own parameter text, model-visible 24,998). */const SERVED_STARTER_MAX_JSON_CHARS = 26_700;/** 4,042 at the cost wave + 586 for the operator contract's error protocol, notice prefix and memory loop (F1); no schema guidance moved here. */const INSTRUCTIONS_MAX_CHARS = 4_868; // #6007: +240 for the issue-required write guidance (put_pages, wait_ms)diff --git a/test/recall-question-cli.test.ts b/test/recall-question-cli.test.tsnew file mode 100644index 0000000000..d46503da69--- /dev/null+++ b/test/recall-question-cli.test.ts@@ -0,0 +1,136 @@+/**+ * `gbrain recall --question` (W1): the value is the question, never an+ * entity (the parser used to skip the unknown flag and take its value as the+ * positional entity). Local in-process with question only and with question+ * plus query; `--question=` form; the human render; the thin-client route+ * sends `question` to the remote recall and notes an older server that+ * answered without `facts_order`. PGLite and a fixture MCP server; no keys.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { recallNeedsLocalEngine, runRecall } from '../src/commands/recall.ts';+import { validateCommandFlags } from '../src/cli/main.ts';+import { runCli } from './helpers/cli-spawn.ts';++let engine: PGLiteEngine;+const origWrite = process.stdout.write.bind(process.stdout);+let captured = '';+const QUESTION = 'Which kayak brand does Alice Example paddle?';++async function recall(args: string[]): Promise<string> {+ captured = '';+ await runRecall(engine, [...args, '--source', 'default']);+ return captured;+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.insertFact({ fact: 'Alice Example paddles a Wavecraft kayak', kind: 'fact', entity_slug: 'alice-example', source: 'test', visibility: 'world', valid_from: new Date('2025-01-01T00:00:00Z') }, { source_id: 'default' });+ await engine.insertFact({ fact: 'The team offsite moved to Denver', kind: 'fact', entity_slug: null, source: 'test', visibility: 'world' }, { source_id: 'default' });+});+afterAll(async () => {+ process.stdout.write = origWrite;+ await engine.disconnect();+});+beforeEach(() => {+ process.stdout.write = ((chunk: string | Uint8Array) => {+ captured += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString();+ return true;+ }) as typeof process.stdout.write;+});++describe('gbrain recall --question', () => {+ test('the value is the question, not an entity: facts come back ranked, no page search', async () => {+ const out = JSON.parse(await recall(['--question', QUESTION, '--json']));+ expect(out.facts_order).toBe('relevance');+ expect(out.facts.map((f: { fact: string }) => f.fact)).toEqual(['Alice Example paddles a Wavecraft kayak']);+ expect(typeof out.facts[0].relevance).toBe('number');+ expect(out.results).toBeUndefined();+ });++ test('--question= form and question plus query (facts ranked and pages searched)', async () => {+ const eq = JSON.parse(await recall([`--question=${QUESTION}`, '--json']));+ expect(eq.facts_order).toBe('relevance');+ const both = JSON.parse(await recall(['--question', QUESTION, '--query', QUESTION, '--json']));+ expect(both.facts_order).toBe('relevance');+ expect(Array.isArray(both.results)).toBe(true);+ });++ test('human render names the ranking and each relevance; an unmatched question says so', async () => {+ const human = await recall(['--question', QUESTION]);+ expect(human).toContain('Facts (ranked by relevance to the question):');+ expect(human).toMatch(/Wavecraft kayak — test \(relevance \d\.\d\d\)/);+ expect(await recall(['--question', 'zymurgy quokka xylophone'])).toContain('No saved fact matched the question.');+ });++ test('routing: --question has a thin-client path; --query alone stays in-process; the flag registry accepts it', () => {+ expect(recallNeedsLocalEngine(['--question', QUESTION])).toBe(false);+ expect(recallNeedsLocalEngine(['--question', QUESTION, '--query', QUESTION])).toBe(false);+ expect(recallNeedsLocalEngine(['--query', QUESTION])).toBe(true);+ expect(validateCommandFlags('recall', ['--question', QUESTION, '--json'])).toBeNull();+ });++ test('--question refuses the watch, cursor, rollup and context renders', async () => {+ const errors: string[] = [];+ const origError = console.error;+ console.error = (...args: unknown[]) => { errors.push(args.join(' ')); };+ try { await recall(['--question', QUESTION, '--watch', '5']); } finally { console.error = origError; }+ expect(errors.join('\n')).toContain('Error [invalid_params]: --question cannot be combined with --watch');+ });+});++describe('gbrain recall --question on a thin client', () => {+ async function thinCall(args: string[], reply: Record<string, unknown>) {+ const calls: Array<{ name?: string; arguments?: Record<string, unknown> }> = [];+ const server = Bun.serve({ hostname: '127.0.0.1', port: 0, async fetch(request): Promise<Response> {+ const path = new URL(request.url).pathname;+ const base = `http://127.0.0.1:${server.port}`;+ if (path === '/.well-known/oauth-authorization-server') return Response.json({ issuer: base, token_endpoint: `${base}/token` });+ if (path === '/token') return Response.json({ access_token: 'fixture', token_type: 'bearer', expires_in: 3600, scope: 'read' });+ if (path !== '/mcp' || request.method !== 'POST') return new Response(null, { status: 405 });+ const body = await request.json() as { id?: number; method: string; params?: { protocolVersion?: string; name?: string; arguments?: Record<string, unknown> } };+ if (body.id === undefined) return new Response(null, { status: 202 });+ if (body.method === 'initialize') return Response.json({ jsonrpc: '2.0', id: body.id, result: {+ protocolVersion: body.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'fixture', version: '1' },+ } });+ calls.push({ name: body.params?.name, arguments: body.params?.arguments });+ return Response.json({ jsonrpc: '2.0', id: body.id, result: { content: [{ type: 'text', text: JSON.stringify(reply) }] } });+ } });+ const home = mkdtempSync(join(tmpdir(), 'gbrain-recall-question-thin-'));+ mkdirSync(join(home, '.gbrain'));+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite'), remote_mcp: {+ issuer_url: `http://127.0.0.1:${server.port}`, mcp_url: `http://127.0.0.1:${server.port}/mcp`, oauth_client_id: 'fixture', oauth_client_secret: 'fixture',+ } }));+ try {+ const result = await runCli(['recall', ...args], { home, cwd: home, timeoutMs: 20_000, env: {+ GBRAIN_BRAIN_ID: 'host', GBRAIN_NO_BANNER: '1', GBRAIN_MODEL_DISCOVERY: 'off', ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined,+ } });+ return { ...result, calls };+ } finally {+ await server.stop(true);+ rmSync(home, { recursive: true, force: true });+ }+ }++ test('sends question to the remote recall and renders the ranked facts', async () => {+ const r = await thinCall(['--question', QUESTION], { protocol_version: 1, total: 1, facts_order: 'relevance',+ facts: [{ fact_id: '7', fact: 'Alice Example paddles a Wavecraft kayak', kind: 'fact', entity_slug: 'alice-example', provenance: 'test', relevance: 1.25 }] });+ expect(r.exitCode).toBe(0);+ expect(r.calls.map(c => c.name)).toEqual(['recall']);+ expect(r.calls[0]!.arguments).toMatchObject({ question: QUESTION });+ expect(r.calls[0]!.arguments!.entity).toBeUndefined();+ expect(r.stdout).toContain('(relevance 1.25)');+ }, 30_000);++ test('an older server that answers without facts_order is reported as not ranked', async () => {+ const r = await thinCall(['--question', QUESTION], { protocol_version: 1, total: 1,+ facts: [{ fact_id: '8', fact: 'The team offsite moved to Denver', kind: 'fact', entity_slug: null, provenance: 'test' }] });+ expect(r.exitCode).toBe(0);+ expect(r.stdout).toContain('did not rank facts by the question');+ }, 30_000);+});diff --git a/test/recall-question.test.ts b/test/recall-question.test.tsnew file mode 100644index 0000000000..5fa8727d36--- /dev/null+++ b/test/recall-question.test.ts@@ -0,0 +1,375 @@+/**+ * 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 () => {+ 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 () => {+ 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('@@ q.q'))).toContain(`${factsFtsDocument('f')} @@ q.q`);+ });++ 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 --git a/test/reindex-search-vector.serial.test.ts b/test/reindex-search-vector.serial.test.tsindex 773f586210..08c911f3c4 100644--- a/test/reindex-search-vector.serial.test.ts+++ b/test/reindex-search-vector.serial.test.ts@@ -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+ 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');@@ -134,6 +135,8 @@ describe('runReindexSearchVector', () => {// proconfig): both recreated bodies pin search_path.expect(state.calls[1]).toContain('SET search_path = pg_catalog, public');expect(state.calls[2]).toContain('SET search_path = pg_catalog, public');+ expect(state.calls[5]).toBe('DROP INDEX IF EXISTS idx_facts_fts');+ expect(state.calls[6]).toContain("CREATE INDEX idx_facts_fts ON facts USING gin (to_tsvector('pt_br'::regconfig");});test('default english language still recreates + backfills (no shortcut here)', async () => {@@ -148,7 +151,7 @@ describe('runReindexSearchVector', () => {expect(result.status).toBe('ok');expect(result.language).toBe('english');- expect(state.calls.length).toBe(5);+ expect(state.calls.length).toBe(7);// Trigger recreates (calls 1, 2) and chunks backfill (call 4) embed the// language literal. Pages backfill (call 3) is UPDATE-to-self that@@ -158,6 +161,7 @@ describe('runReindexSearchVector', () => {expect(state.calls[2]).toContain("'english'");expect(state.calls[3]).toMatch(/UPDATE pages/);expect(state.calls[4]).toContain("'english'");+ expect(state.calls[6]).toContain("to_tsvector('english'::regconfig");});test('SQL injection attempt falls back to english', async () => {@@ -279,7 +283,7 @@ describe('runReindexSearchVector', () => {expect([...state.config!.keys()]).toEqual([]);// The existing executeRaw shape is untouched (config goes through// get/set/unsetConfig, not executeRaw).- expect(state.calls.length).toBe(5);+ expect(state.calls.length).toBe(7);});test('resumes the chunks backfill from the persisted checkpoint when the marker matches the language', async () => {diff --git a/test/schema-catalog-golden.test.ts b/test/schema-catalog-golden.test.tsindex 75eab87c67..0c7da1863d 100644--- a/test/schema-catalog-golden.test.ts+++ b/test/schema-catalog-golden.test.ts@@ -104,11 +104,13 @@ describe('PGLite catalog goldens (E4)', () => {expect(embedding.udtName).toBe('vector');});- test('non-default FTS language changes only function bodies (search_vector triggers)', () => {+ test('non-default FTS language changes only function bodies (search_vector triggers) and the facts keyword index', () => {for (const path of ['engine', 'blob'] as const) {const diff = diffCatalogSnapshots(requireCaptured(`${path}:default`), requireCaptured(`${path}:fts-portuguese`));expect(diff.length).toBeGreaterThan(0);- expect([...new Set(diff.map((d) => d.section))]).toEqual(['functions']);+ // The facts table (and its v233 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);}});