Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.50.1.0 fix: community fix wave — 21 PR adoptions + 35 verified issue fixes + composite review, rebased on 0.50.0.0 (#5097)

Sina Matianf1fbdfba1933
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index fdcd57dcfa..875a2a31df 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.50.0.0",
+ "version": "0.50.1.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index cfaf9488cf..c0591f4703 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.50.0.0",
+ "version": "0.50.1.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.github/workflows/heavy-tests.yml b/.github/workflows/heavy-tests.yml
index 0de8bcf5f4..a67e1797f6 100644
--- a/.github/workflows/heavy-tests.yml
+++ b/.github/workflows/heavy-tests.yml
@@ -210,7 +210,7 @@ jobs:
HERMES_VERSION: "0.20.0"
HERMES_GIT_TAG: "v2026.8.3"
HERMES_GIT_COMMIT: "3c27eb6234bf91b8ceee9e9071591b31e9b148cb"
- HERMES_INSTALL_SHA256: "2076946edc23b3aed4a82ccb2e6b38ab593575626206dbdd192384e375b6d57c"
+ HERMES_INSTALL_SHA256: "5854b15670b51a8daae8f59ddfa917062de9f74be261eb73b4b8d719710f8968"
GBRAIN_REAL_HERMES_E2E: '1'
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index d04d22825e..35ae6ce1f4 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.50.0.0 -->
+<!-- gbrain-runbook-stamp: 0.50.1.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 10e73d890f..b0701a625e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,152 @@
All notable changes to GBrain will be documented in this file.
+## [0.50.1.0] - 2026-09-14
+
+**The community fix wave, rebased onto 0.50.0.0: 21 contributor pull requests adopted or reworked with credit, 35 verified open issues fixed directly.** `gbrain sync --json` prints one JSON document again, so piping it into `jq` works, and a sync that only swept dead pages tells you so instead of "Already up to date". Brains on Gemini embeddings get a real dollar estimate in the cost gate, facts extraction on a local Ollama model asks for schema-constrained JSON so small models stop returning malformed output, and `gbrain dream --dry-run` stops billing you for takes and calibration while the patterns phase skips outright when nothing new has been reflected on. A remote search on a brain that has not been reindexed says so instead of claiming a clean miss, each Codex rollout lands on its own conversation page, and `gbrain config set` accepts the `search.*` keys the search path actually reads. A source marked `syncEnabled: false` is left alone by the daemon, the phantom redirect no longer aborts on a canonical page that already holds facts, and emoji folder names carrying an invisible variation selector slugify cleanly. Every adopted code fix carries a regression test proven red before the fix.
+
+## To take advantage of v0.50.1.0
+
+`gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:
+
+1. **Run the orchestrator manually:**
+ ```bash
+ gbrain apply-migrations --yes
+ ```
+2. **No new schema migration ships in this release; the mechanical side is a binary upgrade.** Brains whose pages predate the safe-chunk index now see `degraded: [safe_index_pending]` on empty remote `search`/`query` results until `gbrain reindex --markdown` (or a fresh import) rebuilds their chunks.
+3. **Verify the outcome:**
+ ```bash
+ gbrain doctor
+ gbrain search modes
+ ```
+
+**Say to your agent:** *"run the brain health check and tell me what changed in this upgrade"*
+
+### Behavior changes (read before you upgrade)
+
+- **`gbrain sync --json` prints exactly one JSON document.** The cost-gate status object that used to print as a second top-level value now nests inside the envelope as `cost_gate`, for single-source and `--all` runs alike, so `sync --json | jq` and `JSON.parse` work as documented. `schema_version` stays 1; callers that read the gate from the first stdout line must read `.cost_gate` instead. (#4684)
+- **A sweep-only sync reports what it did.** When a pass only soft-deletes un-syncable pages, `deleted` counts the swept pages and the result reads `synced` instead of `up_to_date` / "Already up to date."; a run whose pull failed reports its swept pages the same way. The strategy root cause shipped in v0.48.5.0. (#4786)
+- **`gbrain config set` accepts the `search.*` keys the search path actually reads.** The registered keys are the camelCase `search.tokenBudget`, `search.intentWeighting` and `search.searchLimit` plus the reranker, cross-modal and relational knobs. The three snake_case spellings nothing read (`search.token_budget`, `search.intent_weighting`, `search.limit_default`) are still accepted through the `search.` prefix but have no reader; re-set any override under the name `gbrain search modes` prints for it. (#4605)
+- **Remote searches on a not-yet-reindexed brain say so.** Remote/MCP `search` and `query` on a brain whose pages predate the safe-chunk index now report `degraded: [safe_index_pending]` when they come back empty, instead of asserting a clean miss; the pages themselves are still withheld from remote callers, as before. `gbrain doctor` counts them and names the fix, `gbrain reindex --markdown`. (#5004)
+- **Company links in list sections no longer inherit a person's role.** A person page whose bio says "is an advisor" or "partner at" used to type every bare company link on the page with that role, including links inside Timeline, See-also, Related, Facts, Sources, Links, Email mention links, Backlinks and Significant moments sections. New extractions type those links as `mentions`; per-edge verbs still type normally everywhere. The extractor watermark moves to 2026-09-09, so the next `gbrain extract --stale` re-extracts every brain, but that re-run only adds `mentions` rows beside the older `works_at` / `advises` / `invested_in` edges: those rows are not removed and keep feeding `who works at X` style relational answers until a separate repair. (#4977, @ethanbeard)
+- **By-mention checkpoints reset once.** The `extract --by-mention` resume checkpoint now hashes every gazetteer entry, so it notices a new entity even when it shares a first word with an existing one. Existing checkpoints are invalidated once on upgrade: the first `gbrain extract links --by-mention --source db` after upgrading rescans every page. Checkpoints are resume state, not data; `gbrain extract --stale` does not perform this rescan. (#4858, @proxynico)
+- **Gemini embeddings are priced.** Cost estimates now know Google's `gemini-embedding-001` and `gemini-embedding-2`, directly or through OpenRouter, so the sync cost gate and `--max-cost` checks stop tripping the no-pricing guard and stop pricing these models at another provider's rate. Expect a real dollar figure where you used to see "estimate unavailable". (#4953, @morven-ai; hosted-google coverage test from #4989, @dov-kela)
+- **`gbrain dream --dry-run` no longer bills.** It skips `propose_takes`, `grade_takes` and `calibration_profile` (status `skipped`, reason `no_dry_run_support`) instead of making model calls and writing proposal, grade and profile rows; `--help` names the trio. (#4823)
+- **The dream patterns phase skips when nothing new happened.** A completed run records the newest reflection it consumed (`dream.patterns.last_evidence_ts`); until a newer reflection lands in the lookback window, re-runs skip with `no_new_evidence` instead of paying for another model pass, so autopilot's hourly tick cannot mint near-duplicate pattern pages. `gbrain dream --phase patterns --once` forces a run. (#4879)
+- **`context_pack` and `delta` honor `budget_tokens` on the injectable text.** Each item is costed as the line it renders to, and the envelope plus section headers are reserved up front (roughly 32 tokens for `context_pack`, 48 for `delta` with a `since` cursor). A budget below that reserve returns an empty pack: `context_pack` reports it through `dropped_count` equal to the item count (it has no `has_more` field), while `delta` also sets `has_more: true`. `delta` never drops open threads; only pages and facts count toward the budget. Unbudgeted output is unchanged. (#4761)
+- **Codex rollouts land one page per thread.** Each forked or subagent rollout gets its own conversation page, keyed by its own per-thread id (the root session id stays as a legacy fallback), so child rollouts no longer collapse onto the parent's page, re-import on every pass, or get dropped as duplicates. Existing root-session pages keep their slug; a parent page that had absorbed child content re-imports once. (#4981)
+- **Emoji names with an invisible variation selector re-key.** Folder and file names carrying the VS16 selector that macOS Finder and most pickers append now slugify to the clean slug, and `[[wikilinks]]` typed with the same emoji resolve to it. Pages keyed under the old selector-bearing slug re-key on their next touch or one `gbrain sync --full`; twins that already exist are not retired for you (`gbrain orphans` lists them), so rename or delete them once. (#4985, @ozp)
+- **`syncEnabled: false` is honored by the daemon.** Autopilot's freshness dispatcher skips such a source before queuing a sync job, the full-cycle fan-out drops the `sync` phase (and its pull) while keeping lint, backlinks, extract and the freshness stamp, and `sync --all` and `gbrain sources status` agree with it, including on PGLite brains. An explicit `gbrain sync --source <id>` naming the source still syncs it. (#4952, @Masashi-Ono0611)
+- **The phantom redirect no longer aborts on `idx_facts_fence_key`.** When the canonical page already holds fenced facts, `migrateFactsToCanonical` (both engines) renumbers the migrated rows past the canonical page's current max `row_num` (NULL stays NULL); `extract_facts` re-harmonises exact numbering against the disk fence on its next pass. (#4558)
+- **A stall-aborted embed drain fails the phase.** The dream/autopilot embed phase now reports a stall-watchdog-aborted drain (`reason: stall_timeout`) as a failed phase instead of a healthy one, matching every other non-CLI embed consumer. The root cause of the wedge itself stays open. (#4599)
+
+### AI providers
+- Embedding cost estimates now price Google's `gemini-embedding-001` and `gemini-embedding-2`, so brains on Gemini embeddings (directly or through OpenRouter) get a dollar figure instead of "estimate unavailable", are no longer silently priced at another provider's rate in the sync cost gate, and no longer trip the no-pricing gate under `--max-cost` (#4953, thanks @morven-ai; the hosted-google coverage-gate test is folded from #4989, thanks @dov-kela)
+- Facts extraction on a local Ollama model now requests schema-constrained JSON (Ollama enforces `json_schema` server-side), so small models such as gemma3:4b stop emitting malformed extractor output; every other provider lane is unchanged. An openai-compatible backend that rejects `response_format: json_schema` at call time (an older Ollama build, a strict proxy) gets one retry without the schema and is remembered for the rest of the process instead of failing every extraction; the facts schema is OpenAI-strict-safe (every property required, optional ones nullable). **Say to your agent:** *"use my local Ollama model for facts extraction"* — your agent runs `gbrain config set facts.extraction_model ollama:<model>` (#4968, closes #4863, thanks @ofroiland)
+- `claude-cli` declares prompt caching (Claude Code caches `--print` runs itself), so `gbrain doctor` no longer tells subscription users to move a claude-cli subagent tier to the metered API for a cache they already have (#4973, thanks @LongPV)
+- GLM-4.5+/5.x models routed through the `ollama:` (`ollama:glm-5.3-flash:cloud`) and `openrouter:` (`openrouter:z-ai/glm-5`) recipes now get the same thinking-by-default output headroom the `zhipu:` recipe already grants, so `gbrain think` and gateway chat/tool-loop calls no longer truncate at 4000/4096 tokens while the model is still reasoning; pre-4.5 GLM tags keep the conservative caps (#4727)
+
+### Dream / cycle
+- `gbrain dream`'s `recompute_emotional_weight` phase no longer holds the cycle lock inside one silent full-brain UPDATE: rows whose weight is unchanged are skipped on both engines (no per-row trigger fan-out), and writes go out in bounded slices with a progress tick, cycle-lock refresh, and abort check between them, so a long first run is visible and interruptible (#4797)
+- `gbrain dream --dry-run` now skips propose_takes, grade_takes and calibration_profile (status `skipped`, reason `no_dry_run_support`) instead of billing LLM calls and writing proposal / grade / profile rows; `--help` names the trio as skipped (#4823, the dry-run aside only)
+- Dream subagent writes (synthesize agentic lane, patterns, delegated jobs) no longer mint page types the active schema pack does not declare: an explicit undeclared `type:` is stored as `note` with the model's type kept in `frontmatter.legacy_type`, so `gbrain sync` stops warning every night about `reflection`/`original`/`pattern` pages. Existing rows keep warning until `gbrain jobs submit unify-types` retypes them (#4852)
+- A completed run records the newest reflection it consumed (`dream.patterns.last_evidence_ts`); until a reflection in the lookback window is newer, re-runs skip with `no_new_evidence` instead of paying for another model pass, so autopilot's hourly global tick can't mint near-duplicate pattern pages. `gbrain dream --phase patterns --once` forces a run (and still records what it consumed). **Say to your agent:** *"run the patterns phase now even though nothing changed"* — your agent runs `gbrain dream --phase patterns --once` (#4879)
+
+### Atoms / extraction / facts
+- Conversation parser: a matched speaker anchor whose date cannot be reconstructed (e.g. a localized month name in a Telegram export) now opens its own message instead of being dropped and folding its words into the previous speaker; the parse reports `date_fallback_count`, and `gbrain conversation-parser scan` prints it as `date_fallback_count` in JSON and `date_fallbacks` in human output (narrow cut from #4681, contributed by @jeanpierre121)
+- Per-slug extractors (sync inline, GitHub/Google source inline, cycle incremental) now resolve each slug to its real on-disk file via a shared `buildSlugPathIndex` instead of rebuilding `slug + '.md'`, so pages whose filenames are not already slugs (spaces, capitals, punctuation) get their links and timeline extracted; a slug the index cannot resolve falls back to the legacy `slug + '.md'` path before being treated as deleted, so `_`-prefixed files and dot-dirs waived via `sync.include_hidden` are still extracted inline. The sync call sites stamp `links_extracted_at` only for the slugs actually read (`slugsSafeToStamp`), so a skipped page stays visible to `gbrain extract --stale` instead of being marked fresh forever. The published `gbrain/extract` subpath's `extractLinksForSlugs`/`extractTimelineForSlugs` now return `{ created, processed }` instead of a number (no in-repo consumer). (#4967, @IvanPham03)
+- Phantom redirect no longer aborts on `idx_facts_fence_key` when the canonical page already holds fenced facts: `migrateFactsToCanonical` (both engines) now renumbers migrated rows past the canonical page's current max `row_num` (NULL stays NULL); `extract_facts` re-harmonises exact numbering against the disk fence on the next pass (#4558)
+- The `extract_facts` cycle reconcile now honors `visibility` and `notability` edits on existing `## Facts` fence rows. Editing either cell on a row whose claim, source, and row number were unchanged used to be a silent no-op (the cycle reported 0 reconciled and the DB kept the old value indefinitely); the page now re-heals once through the existing atomic wipe+reinsert, and a page whose fence and DB already agree cannot churn (#4870)
+
+### Doctor / brain health
+- Schema drift self-heal: a brain whose migration ledger reads current but whose `links_link_source_check` constraint reverted to the pre-v114 closed allowlist (drifted restore, manual DDL) silently rejected every kebab provenance link write (`atom-provenance`, `concept-provenance`). `gbrain apply-migrations` (and every migrate pass) now probes the live constraint shape once the ledger has reached v114 (older brains get the gate from migration v114 itself) and restores the kebab-case gate: it counts violating rows first and refuses loudly, altering nothing, when existing rows fail it; on Postgres the restore uses the same non-blocking two-phase form as v114 (`ADD ... NOT VALID` in a transaction, `VALIDATE CONSTRAINT` outside it, validate-only when the definition is right but unvalidated), while PGLite keeps the one-shot form. `gbrain doctor` gained a `links_link_source_check` row (fail when the definition rejects kebab writes; warn when the gate is absent or NOT VALID). Same self-heal class as the timeline-dedup and pages-upsert-arbiter repairs (#4613)
+- `gbrain reindex-search-vector` now survives interruption: it records an in-progress marker before flipping the FTS trigger language, checkpoints every batch so a re-run with the same `GBRAIN_FTS_LANGUAGE` resumes where it stopped, and `gbrain doctor` fails with `fts_reindex_incomplete` (naming the resume command) until the run completes; previously a killed run silently left keyword search split across two tokenizers. The marker is cleared when the very first DDL statement fails on a fresh run (a missing privilege cannot leave a permanent false `fts_reindex_incomplete`) and preserved when a resume fails, so doctor keeps warning about a genuinely split index and never about one that never started (#4795)
+- `gbrain doctor` `image_assets` no longer reports Supabase/S3 storage objects as "missing from disk": file writers (`files upload`, `upload-raw`, `files sync`, the `file_upload` op) now stamp `metadata.storage` with the configured backend, doctor skips explicitly non-git lanes with a note pointing at `gbrain files verify`, and every files upsert merges metadata on conflict so older unmarked rows heal on their next changed upload. Genuinely vanished local/git assets are still detected (#4910)
+- `gbrain doctor`'s `source_config_shape` repair hint no longer promises that "any `gbrain sources` config write" heals a non-object source config (`set-cr-mode`, `rename`, `set-path` write other columns and left the check red). It now leads with the paste-ready SQL, names `gbrain sources federate <id>` / `unfederate <id>` (re-assert the source's current federation state; federate on an isolated source also flips it into default search), and lists the commands that do not repair it; the runtime warning in sources-load says the same. Text only (#5002)
+- `gbrain doctor`'s truncated-pages hint no longer tells you to run `gbrain sync --force` (a flag that never existed); it gives the working re-import steps and points at docs/integrations/reliability-repair.md. Text only.
+- The remote doctor's `contextual_retrieval_coverage` check counts only the caller's granted sources, matching the other scope-aware checks.
+
+### Search / eval
+- Searches through the `query` op read search-mode settings once instead of twice, saving a config read on hosted Postgres and closing a cache-key/result mismatch window (#4972, @Masashi-Ono0611)
+- `gbrain config set` now registers exactly the `search.*` keys the search path reads (the camelCase `search.tokenBudget` / `search.intentWeighting` / `search.searchLimit` plus the reranker/cross-modal/relational knobs; the three unread snake_case spellings are gone), `gbrain search modes` prints the real copy-pasteable config key for every overridden knob, and `search.adaptive_return*` set on the DB plane now reaches the adaptive return policy as documented. The three retired spellings (`search.token_budget`, `search.intent_weighting`, `search.limit_default`) are still accepted by `config set` through the `search.` prefix but have no reader; re-set them under the camelCase names shown by `gbrain search modes` (#4605)
+- Remote/MCP `search` and `query` on a brain whose pages have not yet been reindexed to the safe-chunk index version now report `degraded: [safe_index_pending]` (the MCP empty-result block names it) instead of asserting a clean miss; `gbrain doctor` counts the withheld pages and names the consequence with the `gbrain reindex --markdown` fix. The remote withholding itself is unchanged, and the disclosure probe uses the `chunker_version` index rather than scanning every markdown page (#5004)
+- The `gbrain init` mode picker's cost note no longer claims the semantic result cache is free while result caching is disabled.
+
+### MCP / schema / auth
+- MCP: remote `put_page`/`capture` now say so in the response (`write_through.warning`) when a write landed only in the database because the resolved source has no repo or local path configured; local CLI output is unchanged. Addresses #4844's minimum ask (#4956, @javieraldape)
+- `docs/mcp/DEPLOY.md` gains an "Owner login links for AI agents" section documenting the existing owner login flow (`POST /admin/api/issue-magic-link` with the server bootstrap credential, five-minute single-use link, private delivery, never GET the link to verify it) and `gbrain auth --help` points at it, so an agent asked for the admin login link no longer falls back to the static `/admin/` URL or the bootstrap token. Say to your agent: "Give me the GBrain admin login link" — your agent calls POST /admin/api/issue-magic-link with the server bootstrap credential and hands you a five-minute single-use link (#5008, fixes #5007, contributed by @garrytan-agents)
+- `gbrain schema show` / `graph` / `lint` / `explain` / `stats` and the `schema_graph` / `schema_explain_type` / `schema_lint` / `schema_stats` MCP ops now resolve the active pack through the brain-wide DB-config `schema_pack` tier, matching what `gbrain schema active` and `get_active_schema_pack` already report, so there are no more split answers about which pack is active within one process (#4653)
+- A path-shaped `schema_pack` value in the DB or `gbrain.yml` config plane now resolves as an unknown pack instead of being joined into the schema-packs directory path.
+- `gbrain serve`'s idle maintenance sweep now reconciles links for the same source the stdio session resolves (`.gbrain-source` dotfile, registered `local_path`, `sources.default`), not just `GBRAIN_SOURCE`/`default`, so a dotfile-scoped MCP session gets its body wikilinks reconciled without a serve restart. The brain-ops skill, the `put_page` description and its remote hint now say plainly that MCP writes (stdio and HTTP) skip inline auto-link and are reconciled asynchronously by the serve sweep or `gbrain sweep --once` (#4679)
+- `context_pack` / `delta`: `budget_tokens` is now honored by the injectable `text`. Each item is costed as the line it renders to and the envelope plus section headers are reserved up front (roughly 32 tokens for `context_pack`, 48 for `delta` with a `since` cursor); `budget_used` reports the token estimate of `text`, envelope and headers included. A budget below the reserve returns an empty pack: `context_pack` reports the loss as `dropped_count` equal to the item count (it has no `has_more` field) and `delta` sets `has_more: true`. `delta` never budget-drops open threads: every thread is rendered whole and only pages and facts count toward the budget (`dropped_count` / `has_more` count only pages and facts; `budget_used` exceeds the budget only when the envelope plus the threads alone do). Cursor semantics are unchanged from v1 (the page keyset, no hold or skip state). Unbudgeted output is unchanged (#4761)
+- `docs/mcp/DEPLOY.md` states the dual-mode `/mcp` auth contract: the same route verifies OAuth 2.1 tokens and `gbrain auth create` bearers, and the 401 + `resource_metadata` challenge is spec-mandated discovery emitted for ANY header-less request, not proof the configured bearer failed. It adds a Troubleshooting entry for "client status shows needsAuth but tool calls succeed" (judge from `whoami` / `gbrain auth test`), and `docs/guides/agent-to-gbrain.md`'s `gbrain connect` row cross-links it (#4893)
+
+### Sync / import
+- `gbrain import --json` also reports `source_id`, the resolved destination source the pages were written to (`sourceId ?? 'default'`, the same value the ingest_log row records) (#4779, @chris-conte)
+- Emoji folder/file names written with a variation selector (the VS16 macOS Finder and most pickers append) now slugify to the clean slug, and `[[wikilinks]]` written with the same emoji resolve to it; pages previously keyed under the invisible-selector slug re-key on next touch or one `gbrain sync --full`. **Say to your agent:** *"re-sync my vault in full"* — your agent runs `gbrain sync --full`. Existing pages that were keyed under a selector-bearing slug are not retired automatically; rename or delete those twins once (`gbrain orphans` lists them), and remote `put_page` still accepts selector characters in slugs (#4985, @ozp)
+- On durability-hardened brains, `delete_page` now commits the page removal (path-limited, best-effort) so the post-commit hook pushes it and commit-driven sync sees it, matching the write side; the `delete_page` result's `write_through` carries `committed: true` when the removal landed in git (hardened repos only) (#4994, @howardpark)
+- New persisted `sync.include_hidden` config key, the dot-directory waiver's twin to `sync.exclude`, so `sync --all`, autopilot and the dream cycle honour a committed `.github/`-style directory that `--include-hidden` (refused under `--all`, unavailable to internal callers) could only admit per invocation. Same dialect (comma/newline list, trailing `/` = whole subtree), unioned with the per-call flag, read above the full-sync early returns so the very first sync honours it; default unchanged (unset admits nothing). The `--all` refusal and `--help` now name the key. **Say to your agent:** "index my repo's .github folder on every sync" — your agent runs `gbrain config set sync.include_hidden '.github/'`. #4901's dot-directory default question stays open. (#5003, @Jey2311)
+- `gbrain sync` and `gbrain import` now refresh a page's recorded `source_path` on the unchanged-content skip path, so legacy rows whose bookkeeping still named a pre-rename file self-heal on the next `sync --full` instead of being reconcile-deleted, and write-through stops recreating the old directory on every write; the stored path (now projected by `getPage` on both engines) is compared first, so re-syncing an unchanged tree issues no bookkeeping writes (#4588)
+- `gbrain sync --json` (single-source and `--all`) now emits exactly ONE JSON document on stdout: the cost-gate status object is nested inside the envelope as `cost_gate` instead of printed as a second top-level value, so `sync --json | jq` and `JSON.parse` work as documented (schema_version stays 1; --json callers that read the gate from stdout line 1 must read `.cost_gate`) (#4684)
+- A sync pass that soft-deletes un-syncable pages now reports them: `deleted` counts the swept pages and a sweep-only run reports `synced` instead of `up_to_date` / "Already up to date."; a sync whose pull failed still reports the un-syncable pages it swept in `deleted` on its `partial` / `pull_failed` result instead of zero (the strategy root cause shipped in v0.48.5.0; this closes Expected #3 of #4786)
+- Sync no longer queues an automatic embed-backfill after a run that only swept un-syncable pages or deleted files (nothing new to embed); the jobs `sync` handler reports `embed_skip_reason: 'no_new_content'` for such runs, so a real import inside the old cooldown window is no longer skipped.
+
+### Transcripts / code intel
+- Transcripts: Claude Code workflow-run artifacts (nested `subagents/workflows/<wf>/` agent logs, their `journal.jsonl`, and title/metadata-only session stubs) no longer read as host-format drift or `unknown format` errors, so `gbrain transcripts ingest --since last` advances its watermark again instead of re-scanning the same files forever (#4969, thanks @LongPV)
+- `code_callees` / `gbrain code-callees` now honor the documented "bare or qualified name" contract: a bare method name whose chunk identity is namespace/class-qualified (C#, Java, Ruby, Rust, TS class methods) resolves via an exact fallback on the chunk's bare symbol name instead of returning 0. Say to your agent: *"what does SubmitAsync call?"* — your agent runs `gbrain code-callees SubmitAsync` (#4670)
+- Codex transcript imports: each forked/subagent rollout now lands on its own conversation page. Identity comes from the rollout's own per-thread id (with the root session id as a legacy fallback) and the first session header wins, so child rollouts no longer collapse onto the parent's page, re-import on every pass, or get dropped as duplicates. Existing root-session pages keep their slug; a parent page that previously absorbed child content re-imports once. Say to your agent: *"import my conversations from Codex"* (#4981)
+
+### Minions / autopilot
+- A source with `config.syncEnabled: false` is no longer auto-synced by the daemon. Autopilot's per-source freshness dispatcher skips it before queuing a sync job, and the full-cycle fan-out drops the `sync` phase (and the pull that feeds it) from that source's `autopilot-cycle` job while keeping lint/backlinks/extract and the freshness stamp; `sync --all` shares the same predicate (and now also honours the flag when PGLite hands the config back as a JSON string), and `gbrain sources status` / the status snapshot report `sync_enabled: false` for such a source on PGLite brains, matching what `sync --all` skips. An explicit `gbrain sync --source <id>` naming the source is unchanged. refs #4399 (its cycle_freshness exemption ask stays open). (#4952, @Masashi-Ono0611)
+
+### Bootstrap / hooks
+- Ambient writeback's Stop hook now banks the real prompt when a Claude Code turn ends in a tool call: tool-result entries (which Claude stores under a user role) no longer shadow the human prompt or suppress the wide-tail retry, and `<command-name>` / `<local-command-stdout>` transcript records are no longer treated as the user's prompt. **Say to your agent:** *"Turn on ambient writeback so my preferences get remembered"* — your agent runs `gbrain config set memory.auto_writeback salient` (#4980, @markkasdorf)
+- `gbrain bootstrap harness --status` now derives the claude-code MCP target's state from the live `claude mcp get` ownership check: a registration replaced by another install (different URL, or a non-HTTP serve at user scope) reads `failed — <reason>` in the human line and `--json targets[]` and exits 1 instead of replaying the receipt's apply-time `confirmed`; not-found/unparseable output keeps the honest degrade (#4586)
+- `gbrain frontmatter install-hook` now installs for sources registered as a subdirectory of a git repo (the `<workspace>/brain` layout `gbrain bootstrap` creates): the hook lands at the enclosing repo root, scoped by git pathspec to that subdirectory so host-repo markdown is never validated; several nested sources share one hook (union of scopes, uninstall drops one at a time); root-registered sources get a byte-identical script (#4600)
+- `gbrain frontmatter install-hook` never silently disables hooks you already have. It leaves `core.hooksPath` unset, still writes the hook, and reports `installed_unwired` with the reason and the manual wiring step when the host repo's `.git/hooks` already holds active hooks, when `.githooks/` already holds other executable hook scripts (wiring would have started running them), or when `core.hooksPath` in any scope already points somewhere other than `.githooks` (husky, secret-scanner templates, dotfiles); a value that already resolves to `.githooks` is left alone and counts as wired. Re-runs and fresh clones that already carry the committed hook now reach the wiring step: `unchanged` means current AND wired, and an inert hook reports `installed` (wired now) or `installed_unwired` (blocked, with the reason).
+- The frontmatter pre-commit hook validates staged files whose names contain spaces or non-ASCII characters (NUL-separated listing and a POSIX `read` loop, proven under dash and bash-as-sh). `install-hook` refuses a symlinked `.githooks/` or `pre-commit` instead of writing (or, on `--uninstall`, removing) through the link, and refuses a source path that contains a line terminator instead of embedding it in the generated script; in both cases the CLI prints the real skip reason for that source and continues with the remaining sources, on install and on `--uninstall` alike.
+- Bootstrap.md's install table now says `GBRAIN_STOP_PUSH` and `hooks.stop_push_debounce_min` govern the Stop-hook push only, documents the SessionEnd push as switch-free (`GBRAIN_HOOKS=0` is the only off-switch) with its `reason: push_spawned` heartbeat attribution, and adds the SessionStart crash-recovery push row (#4986)
+
+### CLI
+- `gbrain reindex --code`, a flag `reindex` never parsed, now fails loud as an unknown flag instead of being accepted silently; run `gbrain reindex-code`. The CLI flag registry no longer legalises flags that only appeared in code comments, and the three docs that still said `reindex --code` were corrected.
+- `gbrain maintain --safe --json` emits a single parseable JSON document; the embedded stale-extraction summary no longer leaks onto stdout.
+- `gbrain files upload-raw` no longer clears a file's stored metadata `type` when the same file is re-uploaded without `--type`.
+
+### CI / test infra
+- Nightly hermes door: installer digest re-pinned after an upstream installer change so the door re-verifies digest + payload + version pins again; the door still loud-fails on schedule until the owner sets ANTHROPIC_API_KEY (#4991, thanks @janusch; fixes #4990)
+
+### serve --http
+- `gbrain serve --http` no longer retains every accepted TCP connection for the life of the process (Bun's node:http never emits socket `close` on server-side sockets), so a deployment whose health checker opens a fresh connection per probe no longer grows its memory with every check. Accepted sockets are now tracked weakly; shutdown still severs live keep-alive connections (#4955, @pavelpp-topia)
+- `gbrain serve --http` shutdown is bounded: if `server.close()` has not returned after 5s (a connection the socket tracker could no longer reach), the daemon logs one line and finishes shutting down instead of hanging, and a `close()` error that arrives after that deadline is logged instead of dropped.
+- `docs/mcp/DEPLOY.md` documents the tailnet/LAN-only `serve --http` shapes (Tailscale Serve over the loopback bind with an `https://` `--public-url`; plain-HTTP bearer-only with no `--public-url`), adds a Troubleshooting entry for the MCP SDK's `Issuer URL must be HTTPS` startup exit and its `MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL` opt-in, notes that `--source-guard` is stdio-only (HTTP writes are token-scoped) and cross-links the `GBRAIN_HTTP_CORS_ORIGIN` allowlist; `docs/mcp/ALTERNATIVES.md` splits Tailscale Serve (tailnet-only) from Funnel (public) (#4500)
+
+### Links / graph
+- Mention linking with `link_resolution.cross_source` on now treats same-slug pages in different sources as distinct targets (a foreign namesake of the scanning page is no longer dropped as a self-link, and two sources sharing a slug both link), and the `extract --by-mention` resume checkpoint notices a new entity even when it shares a first word with an existing one (its hash now covers every gazetteer entry). Existing by-mention checkpoints are invalidated once on upgrade, so the first `gbrain extract links --by-mention --source db` after upgrading rescans every page; checkpoints are resume state, not data (#4858, @proxynico)
+- Person-page role prior (bio "is an advisor" / "partner at" language) no longer types bare company links inside Timeline, See-also, Related, Facts, Sources, Links, Email mention links, Backlinks and Significant moments sections: new extractions type those links as `mentions`, per-edge verbs still type normally everywhere, and a `## Timeline` / `## See also` heading quoted inside a fenced code block no longer suppresses the prior for the prose that follows it. Precision over recall, the same posture as #3466. The link-extractor watermark moves to 2026-09-09, so the next `gbrain extract --stale` re-extracts every brain; that re-run only adds `mentions` rows beside older `works_at` / `advises` / `invested_in` edges from list sections and does not remove or retype them, so `who works at X` / `who advises X` answers that rested on those edges keep coming back until a separate, opt-in repair (#4977, @ethanbeard)
+- The `autopilot.incremental_extract_include_frontmatter` knob is now honoured on every extraction path (sync's inline extract, the GitHub/Google source inline extracts, the `extract_stale` minion, `gbrain maintain`, and a flagless `gbrain extract --stale`), not just the autopilot cycle. Those paths used to skip `related:`/`sources:` frontmatter edges AND stamp the page fresh, so an enabled knob was silently defeated on cron/webhook/minion/maintain runs and the cycle's stale drain never revisited the pages. `1`/`yes`/`on` now count as true for the key, and a hand-edited string or number in config.json no longer resolves to false and shadows `gbrain config set` (only a real boolean is a file-plane answer). No new config key; default unchanged. **Say to your agent:** "keep my frontmatter `related:` links up to date on every sync" — your agent runs `gbrain config set autopilot.incremental_extract_include_frontmatter true`. Fixes #4997. (#4999, @sheelcheyne)
+- Markdown links carrying a `#anchor` (`[Notes](registry/tally.md#section)`, `[see](b.md#section)`) now produce a graph edge to the target page on both the DB and `--source fs` extract paths (the anchor is dropped, as wikilinks already did), and pass-1 markdown targets are lowercased to match how slugs are stored, so a brain that links with anchors no longer reports an empty graph (#4995)
+
+### Pages
+- `delete_page` and `restore_page` now say what they do to disk: the MCP tool description, `gbrain delete --help`, `gbrain pages --help`, and the TOOL_CATALOG row all state that deleting a page also removes its markdown file from the source working tree (the source `local_path`, or `sync.repo_path` when the source has none; skipped when `sync.write_through` is off) and that restoring re-creates it, with the `write_through` result field reporting the outcome. Text only; the behavior itself is unchanged (#4829)
+
+### Docs
+- The context-audit skill's deterministic token pre-pass now divides `wc -c` bytes by the calibrated 2.8 (ceil integer math `(n*10+27)/28`), so the always-loaded-stack estimate lands within about ±8% of the measured count rather than 13-24% under. This replaces the chars/4 estimate (which undercounted Claude-loaded markdown by 25-35%); the report header states the divisor (`Estimate basis: bytes/2.8`) and a host-reported exact context breakdown (e.g. Claude Code `/context`) outranks the estimate. Say to your agent: "context audit" / "reduce context size" (#4988, #5009, contributed by @javieraldape)
+- The mode-bundle `expansion` row and the `search.expansion` key govern no shipped verb: `gbrain query` expands in every mode unless `--no-expand`, while `search`, the memory verbs and the eval harnesses pin expansion per call; search-modes.md, the init picker copy, the CLAUDE.md matrix, RETRIEVAL.md, eval-bench.md and the `gbrain search modes` per-call note now say so (#4601)
+- `docs/mcp/OPENCLAW.md` Option 2 now registers gbrain with `openclaw mcp add gbrain --command <abs path> --arg serve --env GBRAIN_HOME=$HOME` (OpenClaw 2026.8.x reads `mcp.servers` in `~/.openclaw/openclaw.json`, not `mcpServers` in `config.json`), Verify checks `openclaw mcp list`, Option 1 adds the install-the-plugin-by-id (`gbrain-context-engine`) step before setting the `gbrain-context` slot, and a note says to leave `GBRAIN_SOURCE` unset unless single-source retrieval is intended; the README OpenClaw bullet matches (#4842)
+- System-of-record.md's Timeline row and compiled-truth.md now say timeline extraction scans the whole page, not the section after the `<!-- timeline -->` sentinel: a dated `[Source: ..., YYYY-MM-DD]` citation in compiled truth mints a timeline row (dated by the citation, summary = the bullet it sits in); the one placement that mints nothing is a citation alone in its own paragraph, and `gbrain config set auto_timeline off` disables the write-path extraction (#4987)
+
+### Other
+- The dream/autopilot embed phase now reports a stall-watchdog-aborted drain (`reason: stall_timeout`) as a failed phase instead of a healthy one, matching the contract every other non-CLI embed consumer already honours (#4599, residual; root cause of the wedge stays open)
+- Skillopt: a validation gate where every task fails (dead target provider, e.g. a logged-out `claude-cli` child) or every rollout's judge errors now ends the run `errored` with the provider message as the failure detail (exit 2) instead of finishing as a plausible `no_improvement` at 0.000; steps where the optimizer proposed no edits say so on stderr and log audit reason `no_edits_proposed`; the hermetic-config docs no longer claim macOS survives the empty-config-dir form (#4741)
+- Brainstorm/lsd: a judge-phase failure no longer deletes the run checkpoint (every paid cross result stays on disk with `judge_done=false`); the advice now names the existing `gbrain <brainstorm|lsd> --resume <run_id>`, which re-runs only the judge and re-scores into the same saved idea page the failed run wrote (the slug rides in the run checkpoint) instead of saving a second page under a new slug, rather than a `--retry-judge` flag that never existed (#4766)
+
+With thanks to every contributor whose pull request this wave adopts:
+@chris-conte, @dov-kela, @ethanbeard, @garrytan-agents, @howardpark,
+@IvanPham03, @janusch, @javieraldape, @jeanpierre121, @Jey2311, @LongPV,
+@markkasdorf, @Masashi-Ono0611, @morven-ai, @ofroiland, @ozp,
+@pavelpp-topia, @proxynico, @sheelcheyne, and to the reporters whose
+verified issues drove the direct fixes.
+
## [0.50.0.0] - 2026-09-10
**Approve client connection requests and keep background work within the access you granted.**
@@ -176,7 +322,7 @@ regression test proven red before the fix.
fallback will be soft-deleted (72 hours recoverable) on the next sync when
they are modified; switch the source to `auto` if you want both kinds.
Code pages imported before this release pick up their file path on the
- next change, `sync --force`, or `gbrain reindex-code --force`. (#4903,
+ next change or on `gbrain reindex-code --force`. (#4903,
contributed by @Jey2311; fixes #4899, #4900)
- **Migration v146** adds a small table that remembers which transcripts
returned nothing from atom extraction. The first run after upgrading
@@ -246,7 +392,8 @@ regression test proven red before the fix.
@Walliiee); a persistently rate-limited Gmail request now waits out the
limit for up to two minutes instead of six seconds (#4894, contributed by
@johnerik); concept synthesis on a thinking-by-default model requests
- 8,000 output tokens instead of 500 (#4889, contributed by @awilhite); the
+ the gateway's shared thinking-model cap (32,000 output tokens) instead of
+ 500 (#4889, contributed by @awilhite); the
cwd `.env` guard now also ignores a project `DATABASE_URL` in
`.env.development.local`, `.env.production.local` and `.env.test.local`
(#4895); atom extraction may now legitimately return zero atoms for a
@@ -514,7 +661,8 @@ regression test proven red before the fix.
@arisgysel-design; fixes #4911)
- The local CI lane's timeout multiplier reaches the CLI-spawning unit tests
(#4659), and the open-loops reopen test no longer depends on the database
- clock advancing between statements (#4928).
+ clock advancing between statements (#4930, contributed by
+ @arisgysel-design; fixes #4928).
### Review hardening
@@ -12659,8 +12807,8 @@ built-in registry covering the most common chat-export shapes on Earth, plus an
opt-in LLM fallback for the long tail. The dream cycle picks the right parser
per page automatically — no config, no waiting for the next release.
-The same wave introduces a new `progressive-batch` primitive (Wintermute-inspired
-ramp-up: trial 10 → 100 → 500 → full with verification at each stage) so future
+The same wave introduces a new `progressive-batch` primitive (the ramp-up Garry's
+OpenClaw uses: trial 10 → 100 → 500 → full with verification at each stage) so future
batch operations get the discipline for free instead of each reinventing it.
### How to use it
@@ -14849,7 +14997,7 @@ No action required — this is a docs-only release. The wave commitments below l
Five items duplicate older entries lower in TODOS.md (`.sql` indexing, Magika, doc_comment, CJK items) — duplication noted inline. The new top section is the canonical wave-commitment register; historical entries stay as detail.
## [0.40.7.0] - 2026-05-23
-**Your agents can now author your brain's schema pack themselves — no more shell-out, no more hand-editing YAML.** If you've ever opened `gbrain` and noticed thousands of pages stuck as untyped "notes" under `meetings/` or `research/`, this release closes that loop. Tell Wintermute (or any agent connected via MCP) "my brain has 4000 untyped meetings pages — add a `meeting` type and backfill them," and it does the whole thing safely: locks the pack file so two agents can't race, validates the change won't create dangling references, writes atomically so a crash never leaves the pack half-written, audits the mutation with the agent's identity, then updates every matching page in 1000-row batches that never wedge concurrent writers. The cathedral that was bundled but unreachable in v0.39 is now reachable from the outside.
+**Your agents can now author your brain's schema pack themselves — no more shell-out, no more hand-editing YAML.** If you've ever opened `gbrain` and noticed thousands of pages stuck as untyped "notes" under `meetings/` or `research/`, this release closes that loop. Tell your OpenClaw (or any agent connected via MCP) "my brain has 4000 untyped meetings pages — add a `meeting` type and backfill them," and it does the whole thing safely: locks the pack file so two agents can't race, validates the change won't create dangling references, writes atomically so a crash never leaves the pack half-written, audits the mutation with the agent's identity, then updates every matching page in 1000-row batches that never wedge concurrent writers. The cathedral that was bundled but unreachable in v0.39 is now reachable from the outside.
This release rebuilds the design from a closed community PR ([#1321](https://github.com/garrytan/gbrain/pull/1321)) by `@garrytan-agents` into a production-grade `gbrain schema` cathedral. The four mutation verbs that PR proposed (`add-type`, `remove-type`, `stats`, `sync`) all ship — hardened with atomic+locked+audited writes, pack-aware fallback semantics that fail loud instead of silently re-introducing types you removed, and a batched MCP op (`schema_apply_mutations`) that lets a remote agent compose multi-step refactors as one atomic transaction. The lint surface grew from 2 rules to 11. The graph visualization renders link verbs. And the agent on-ramp story — RESOLVER routing, a `schema-author` skill with explicit boundary callouts to `brain-taxonomist` and `eiirp`, a `conventions/schema-evolution.md` decision tree for "when to add a type vs alias vs prefix" — means agents will actually FIND this surface instead of inventing their own ad-hoc YAML edits.
@@ -14874,8 +15022,8 @@ gbrain schema sync --apply # backfills page.type on matching pages
gbrain whoknows "machine learning" # researcher-typed pages now route through expert routing
# 4. If you run `gbrain serve --http` for remote MCP, register a client
-# with admin scope so Wintermute or any other agent can author packs remotely:
-gbrain auth register-client wintermute --scopes admin
+# with admin scope so your OpenClaw or any other agent can author packs remotely:
+gbrain auth register-client my-openclaw --scopes admin
```
If any step fails or numbers look wrong, please file an issue with the output of `gbrain doctor` and `tail -20 ~/.gbrain/audit/schema-mutations-*.jsonl` so we can debug the mutation chain.
@@ -14903,7 +15051,7 @@ If any step fails or numbers look wrong, please file an issue with the output of
- `schema_graph` (read) — JSON `{nodes, edges}` derived from link types and frontmatter_links.
- `schema_explain_type` (read) — resolved settings for one declared type.
- `schema_review_orphans` (read) — drilldown into untyped pages.
-- `schema_apply_mutations` (admin scope, NOT localOnly) — **batched** atomic mutation op. One call applies a list of mutations (`add_type`, `add_link_type`, `set_extractable`, etc.) inside a single `withPackLock` scope. Remote agents like Wintermute can compose multi-step refactors as one transaction. Audit log records `actor: mcp:<clientId8>` per mutation.
+- `schema_apply_mutations` (admin scope, NOT localOnly) — **batched** atomic mutation op. One call applies a list of mutations (`add_type`, `add_link_type`, `set_extractable`, etc.) inside a single `withPackLock` scope. Remote agents like your OpenClaw can compose multi-step refactors as one transaction. Audit log records `actor: mcp:<clientId8>` per mutation.
- `reload_schema_pack` (admin) — flush cache + extends-chain cascade.
**Lint rules grew from 2 to 11:**
diff --git a/CLAUDE.md b/CLAUDE.md
index 5044026d43..7632ecb04e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -217,6 +217,11 @@ project resolves through `src/core/search/mode.ts`.
| `autocut` (rerank-cliff cut) | off | off | off |
| `searchLimit` default | 10 | 25 | 50 |
+The `expansion` row governs no shipped verb today: `gbrain query` expands by
+default in every mode (`--no-expand` / `expand: false` opts out); `search`, the
+memory verbs and the eval harnesses pin it per call; only a caller that leaves
+`expansion` unset AND wires an `expandFn` would inherit the bundle value.
+
**Cost anchors (downstream agent input cost — gbrain itself is rounding error).**
The corner-to-corner spread is 25x once you pair mode with downstream model.
Chunks ~400 tokens avg. Per-query cost @ 10K queries/month (typical
@@ -234,8 +239,9 @@ Mismatches (tokenmax+Haiku, conservative+Opus) waste capacity differently
— too-big payload overwhelms a cheap model; too-small payload starves an
expensive one.
-tokenmax adds ~\$1.50 per 1K queries in Haiku expansion calls on top of
-the matrix (\$15/mo @ 10K). Semantic result caching is temporarily disabled; budget for fresh retrieval on every query. **The matrix
+`gbrain query` adds ~\$1.50 per 1K queries for the Haiku expansion call in
+EVERY mode (\$15/mo @ 10K; `--no-expand` skips it) — `gbrain search` and the
+memory verbs never expand, so no mode buys that line item back. Semantic result caching is temporarily disabled; budget for fresh retrieval on every query. **The matrix
has three verbatim homes: this section, the `gbrain init` picker copy
(`src/commands/init-mode-picker.ts`), and `INSTALL_FOR_AGENTS.md` Step
3.5** — update all three when refreshing.
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index c499f77457..b06f136762 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -201,6 +201,9 @@ Per-query cost @ 10K queries/mo (typical single-user volume):
> 3) tokenmax (recommended default — preserves v0.31.x retrieval shape) —
> no budget, LLM expansion ON, 50 chunks. Best for Opus/frontier models.
>
+> ("no expansion" governs `gbrain search` and callers that leave expansion
+> unset; `gbrain query` expands in every mode unless you pass `--no-expand`.)
+>
> Cost depends on BOTH the mode AND the downstream model you run. See the
> matrix above for the 9-cell breakdown.
diff --git a/README.md b/README.md
index 8e6cae6dde..86c45ff618 100644
--- a/README.md
+++ b/README.md
@@ -213,7 +213,7 @@ commands, embedding costs, and the restrictions that remain after rebuilding.
- **[Muse personal agent](docs/guides/muse.md)** — first verify its durable user-files location, then install the local CLI. Native MCP configuration and skill activation are not assumed.
- **[Grok Build](docs/mcp/GROK.md)** — `grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- gbrain serve --surface verbs`. The add is lazy (exit 0 without connecting) — verify with `grok mcp doctor gbrain`, which spawns the server and reports `7 tools discovered`. Verified against Grok Build v1.0.4.
- **[opencode](docs/mcp/OPENCODE.md)** (opencode.ai / SST — not OpenClaw) — `opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- gbrain serve --surface verbs`, or let `gbrain bootstrap hooks --harness opencode` write the config for you (opencode is a bootstrap-supported harness — it reads AGENTS.md natively). The add is lazy — verify with `opencode mcp list`, which spawns the server (`✓ gbrain connected`). Remote: `gbrain connect https://your-host/mcp --token gbrain_xxx --agent opencode [--install]` — the config stores only the `{env:GBRAIN_REMOTE_TOKEN}` interpolation. Verified against opencode v1.18.18.
-- **[OpenClaw](docs/mcp/OPENCLAW.md)** — the ClawHub bundle plugin registers gbrain automatically (`openclaw.plugin.json` ships in this repo), or add `{"command": "gbrain", "args": ["serve"]}` to `~/.openclaw/config.json`'s `mcpServers`.
+- **[OpenClaw](docs/mcp/OPENCLAW.md)** — the ClawHub bundle plugin registers gbrain automatically (`openclaw.plugin.json` ships in this repo), or register the stdio server with `openclaw mcp add gbrain --command "$(command -v gbrain)" --arg serve --env GBRAIN_HOME=$HOME` (absolute path: the launchd gateway PATH lacks `~/.bun/bin`); verify with `openclaw mcp list`.
- **[Claude Desktop (Cowork)](docs/mcp/CLAUDE_DESKTOP.md)** — Settings → Integrations → add the URL of your HTTP server. Remote only; the local `claude_desktop_config.json` does not work for remote servers.
- **[Claude Cowork (team plan)](docs/mcp/CLAUDE_COWORK.md)** — org Owner adds the connector under Organization Settings → Connectors.
- **[Perplexity Computer](docs/mcp/PERPLEXITY.md)** — `gbrain connect https://your-host/mcp --agent perplexity --oauth --register` mints a least-privilege OAuth client and prints the Issuer/Client ID/Secret to paste into Settings → Connectors (OAuth is the right path for a cloud connector; a bearer token also works for local use). Pro subscription required.
@@ -353,7 +353,7 @@ Most personal-knowledge tools force one fixed layout: their idea of "notes" + "p
**gbrain doesn't have a fixed layout.** It ships with bundled schema packs and lets you author your own when none fit:
- **`gbrain-base-v2`** (default) — 15-type DRY/MECE canonical taxonomy (14 canonical + `note` catch-all): `person`, `company`, `media`, `tweet`, `social-digest`, `analysis`, `atom`, `concept`, `source`, `deal`, `email`, `slack`, `writing`, `project`, `note`. Subtypes/format/origin pushed to frontmatter.
-- **`gbrain-base`** (legacy) — the wider 24-type layout. Stays bundled for back-compat; brains on it can upgrade via `gbrain onboard --check --explain` → `gbrain jobs submit unify-types --allow-protected --params '{"target_pack":"gbrain-base-v2","apply":true}'` (omit `"apply":true` for a dry-run preview — that is the default).
+- **`gbrain-base`** (legacy) — the wider 24-type layout. Stays bundled for back-compat; brains on it can upgrade via `gbrain onboard --check --explain` → `gbrain jobs submit unify-types --params '{"target_pack":"gbrain-base-v2","apply":true}'` (omit `"apply":true` for a dry-run preview — that is the default).
- **`gbrain-recommended`** — extends `gbrain-base` with the 13 additional directories from `docs/GBRAIN_RECOMMENDED_SCHEMA.md` (source, place, trip, conversation, personal, civic, project, etc.). Activate with `gbrain schema use gbrain-recommended`.
- **Your own pack** — `gbrain schema detect` clusters your actual filesystem into proposed types, `gbrain schema suggest` runs an LLM pass over them, and `gbrain schema review-candidates --apply` promotes the ones you like. Three commands and the brain knows your shape. Authoring a successor pack (declares `migration_from:` so existing brains can opt in): see [`docs/architecture/pack-upgrade-mechanism.md`](docs/architecture/pack-upgrade-mechanism.md).
diff --git a/TODOS.md b/TODOS.md
index 992185227b..cf7070f65b 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,5 +1,33 @@
# TODOS
+## Community fix wave follow-ups (filed 2026-09-09)
+
+- [ ] **P3 — new v0.49/v0.50 tests assume `os.tmpdir()` is already a realpath (macOS `/var` vs `/private/var`).**
+ **What:** `test/agent-install.test.ts`, `test/harness-install-ownership.test.ts`, `test/harness-onboarding.test.ts`, `test/init-mcp-only.test.ts`, `test/minions-submission-authority.test.ts`, `test/harness-access.serial.test.ts` and `test/harness-delivery-recovery.serial.test.ts` fail on macOS with "Refusing a symlink in managed path: /var" / "Source file escapes registered root" while the same files pass on Linux CI — the fixtures build paths under `os.tmpdir()` (a symlink on macOS) and the managed-path / registered-root guards compare against realpaths. **Why:** every local and Mac-mini run of the suite now carries 19 red tests that are not defects, which hides real regressions (the v0.50.1.0 ship had to classify them by re-running on a clean master checkout). **Fix:** `realpathSync(os.tmpdir())` in those fixtures (the `upgrade-bun-link-arc` e2e has the same gap). **Effort:** S. **Priority:** P3.
+- [ ] **P2 — `delta`: fetch facts oldest-first with an overflow flag instead of a newest-first `limit: 50` window.**
+ **What:** `src/core/context/turn-context.ts` fetches delta facts with `listFactsSince(..., { limit: 50 })` ordered `created_at DESC` and never sets `has_more` for facts, so more than 50 new facts since the cursor silently drop the OLDEST ones as the page cursor advances past them. **Why:** the v0.50.1.0 pre-landing review found it while simplifying the delta cursor; the fix is an ascending keyset fetch plus `has_more` when the window is full (an engine-options change, so it was left out of the wave). **Effort:** M. **Priority:** P2.
+- [ ] **P2 — `session_context_state` cursor upsert: GREATEST, not COALESCE.**
+ **What:** `src/core/context/session-state.ts` upserts `last_wake_at = COALESCE(EXCLUDED.last_wake_at, …)` (last-writer-wins) while its own doc and `src/mcp/context-pack-handler.ts` assume a monotonic GREATEST, so a `context_pack` push after a `delta` wake can move the shared cursor forward past items the delta never delivered. **Why:** pre-existing, surfaced by the v0.50.1.0 review; fix the SQL to GREATEST and pin it. **Effort:** S. **Priority:** P2.
+- [ ] **P3 — `schema lint --with-db` has no test.**
+ **What:** the v0.50.1.0 wave re-plumbed `gbrain schema lint --with-db` inside `withConnectedEngine` (tier-4 `schema_pack` read + `process.exit(1)` on a missing pack) and nothing in `test/` drives it. **Why:** a regression there would ship green. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — recompute_emotional_weight: pin `pages_recomputed` semantics and the lock-steal path.**
+ **What:** `pages_recomputed` now counts evaluated rows (`details.pages_updated` counts writes) and feeds `totals.pages_emotional_weight_recomputed`; the phase moved under `racedTimePhase` with no lock-steal test, and its Postgres SQL twin runs only in the nightly e2e lane. **Why:** the coverage audit flagged both as unpinned behavior changes. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — minion `put_page` type pin: round-trip fidelity test + delegated-lane wording.**
+ **What:** `pinUndeclaredType` re-serializes the whole page when an undeclared explicit `type:` is rewritten to `note`; no test carries a `timeline` block, extra frontmatter or a pre-existing `legacy_type`, and its docblock says "trusted-workspace subagents" although master's delegated jobs also set `allowedSlugPrefixes`. **Why:** flagged by the v0.50.1.0 review; the behavior is fine, the pins are missing. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — stdio idle sweep: pin the no-dotfile / no `GBRAIN_SOURCE` lane.**
+ **What:** `gbrain serve`'s idle maintenance sweep now resolves its source through the stdio ladder (#4679); only the `.gbrain-source` dotfile lane is tested, so the `local_path` / `sources.default` rungs the sweep now follows for a plain serve are unpinned. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — inline extract: inbound links to `_`-prefixed and hidden-directory pages still fail to resolve.**
+ **What:** the wave restored the legacy `slug + '.md'` fallback for the FROM side of the per-slug extractors (#4967 follow-up), but `allSlugs` at `src/commands/extract.ts` is still walk-only, so links INTO admitted `_note.md` / `.github/*.md` pages are dropped as unresolved — as on master before the wave. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — link-extractor watermark bumps cannot demote already-typed edges.**
+ **What:** re-extraction writes via `addLinksBatch … ON CONFLICT DO NOTHING` and never prunes, so the 2026-09-09 `LINK_EXTRACTOR_VERSION_TS` bump adds `mentions` rows beside prior-typed `works_at`/`advises` edges from machine-written list sections instead of demoting them. A doctor `--fix` that deletes prior-typed markdown edges whose anchor sits in a suppressed range is the cleanup; needs the maintainer's call on evidence. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — brainstorm `--resume` from a pre-0.50.1.0 checkpoint still mints a fresh idea slug.**
+ **What:** checkpoints written before the wave carry no `idea_slug`, so one legacy resume can still create a second idea page (the bug #4766's follow-up fixed for new checkpoints). A one-line stderr note or a slug back-derivation would close it. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — hermes-door: pin the installer bootstrapper by upstream commit instead of sha-pinning the served `install.sh`.**
+ **What:** `.github/workflows/heavy-tests.yml` pins `HERMES_INSTALL_SHA256` against the bytes served at the vendor's stable install URL, which upstream edits often: the pin has needed four refreshes in four weeks (latest #4991, fixes #4990) and one was stale within hours of being observed, so every upstream edit is a red nightly until someone re-reviews the upstream diff and re-pins the two homes (the workflow constant + `docs/mcp/HERMES-CLI-PIN.md`). The door also stays red at its Preconditions step until the `ANTHROPIC_API_KEY` repo secret is set; the re-pin restores digest + payload + version verification, not a green job. **How (maintainer design call):** fetch the bootstrapper from the upstream repo at a reviewed commit (the door already commit-pins the PAYLOAD via `HERMES_GIT_COMMIT`, so a commit-pinned bootstrapper is consistent; the served-URL door was kept deliberately as the real user install path — weigh that against a roughly weekly re-pin chore), or keep the served-URL pin and accept the chore. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — `extract_facts`: heal an attribute-only fence edit in place instead of wipe+reinsert.**
+ **What:** since #4870 the reconcile treats a `visibility` / `notability` cell edit as drift and re-syncs the page through the same atomic wipe+reinsert the other drift classes use. That transports the edit but re-embeds every row on the page (a paid call when an embedding key is configured; NULL embeddings until re-embedded when it is not) and rotates the rows' ids. **Why:** the v0.50.1.0 ship found the keyless case through `test/e2e/phantom-redirect.test.ts` round 12 (the seed disagreed with its fence, so the reconcile wiped the migrated row); the test seed was fixed, the reconcile was not. An attribute-only drift with matching content key, row number and struck-state can be a per-row `UPDATE facts SET visibility, notability` under the same page lock. **Effort:** S. **Priority:** P3.
+
+
## Community fix wave follow-ups (filed 2026-09-07, search-eval train)
- [ ] **P2 — bump MARKDOWN_CHUNKER_VERSION to 5 so already-indexed CJK-dominant pages pick up the CJK overlap fix.**
@@ -189,10 +217,7 @@
retrieval-gate path were deferred. Triage records (verdict, evidence, fix
sketch, key files per issue) live in the wave workspace
`.context/wave/triage/issue/` + `.context/wave/refute/issue/` (gitignored
- wave working state, not repo content). Deferred: #4381 #4558 #4576 #4578
- #4586 #4588 #4600 #4603 #4605 #4613 #4616 #4622 #4649 #4653 #4670 #4684
- #4741 #4761 #4766 #4772 #4795 #4797 #4852 #4879 #4910 #4921, plus #4359
- (S, but it lives in `search/hybrid.ts` and needs an eval-replay receipt).
+ wave working state, not repo content). Deferred: #4381 #4576 #4578 #4603 #4616 #4622 #4649 #4772 #4921 (of the 0.48.5.0 wave's 26 deferrals, 17 shipped in 0.48.6.0: #4558 #4586 #4588 #4600 #4605 #4613 #4653 #4670 #4684 #4741 #4761 #4766 #4795 #4797 #4852 #4879 #4910).
Of the 0.48.1.0 wave's 27 deferrals, ten shipped in 0.48.5.0 (#4744 via
#4933, #4729 via #4865, #4728, #4696, #4652, #4620, #4606, #4597, #4589,
#4563), five were re-classified on verification (#4738 and #4732
@@ -229,6 +254,18 @@
sources (order is now total; the cursor is not). (11) `bootstrap harness`
resolves the implicit source from its own cwd while the serve resolves from
its cwd at boot; the shared ladder narrows but does not close the gap.
+- [ ] **P2 — Corrective-release follow-ups (0.48.5.1): two INVESTIGATE items
+ from the adversarial passes on the release-notes fix.** (a) The CLI flag
+ validator accepts `gbrain sync --force` although `sync` never reads it:
+ `scripts/generate-flag-registry.ts` harvests `--[a-z0-9-]*` tokens from
+ source text, and a comment in `src/commands/sync.ts` (`(--force skips …)`)
+ puts `--force` on the sync row. Either harvest from the parsed argv sites
+ only, or strip comments before scanning; then add a registry test that a
+ comment-only token does not register. (b) `scripts/check-privacy.sh
+ --staged` takes filenames from the index but greps their WORKING copies,
+ so a banned name staged for commit and then removed from the working copy
+ (without staging the removal) passes the pre-commit guard. Read the staged
+ blob (`git show :path`) in that mode. **Effort:** S each. **P2.**
- [ ] **P3 — Simplification advisories from the wave review (structure, not
defects).** One `mirrorFenceBodyToDb` helper for the three pasted fence-mirror
recipes (fence-write.ts, forget.ts x2); static import of
@@ -603,9 +640,12 @@ deferred M-effort issues above are NOT repeated here.
contract constant references get_page/put_page/list_skills/get_skill, which
don't exist on `--surface verbs`; serve the verb-appropriate contract per
surface.
-- [ ] **P3 — per-source sync.exclude scoping.** **What:** #4667's persisted
- exclude scope is global (union-only widening across every source); a
- per-source key was the author's own follow-up note.
+- [ ] **P3 — per-source sync.exclude / sync.include_hidden scoping.** **What:**
+ #4667's persisted exclude scope and #5003's persisted dot-directory waiver
+ are both brain-global (one list reaches every source on `sync --all`); a
+ per-source key was the author's own follow-up note. Admission
+ (`sync.include_hidden`) is the riskier direction — a `.github/` waiver meant
+ for one repo admits that directory in every source — so scope it first.
- [ ] **P3 — skills-doc note on capture-time vs retroactive backlink dating.**
**What:** #4552/#4595 made backlink REPAIR insert undated "Referenced by"
rows (retroactive dating is forgery), while live capture keeps dated
@@ -1431,11 +1471,12 @@ deferred M-effort issues above are NOT repeated here.
by ON CONFLICT DO NOTHING, the tool still executes, and the settle UPDATE
then matches 0 rows — the outcome is silently unrecorded and a non-idempotent
tool can re-execute on replay. Add a rowcount check + job-log warn (needs a
- logging seam in the persist helpers). (b) extract-atoms tombstones cover
- pages only: `recordPageFailureCount` returns null for `kind !== 'page'`, so
- a transcript that deterministically yields malformed output re-spends LLM
- budget every cycle forever — extend #4148's failure-count machinery to
- transcript items. (c) getHealth coverage numerators are not liveness-
+ logging seam in the persist helpers). (b) DONE in v0.48.5.0 (#4916):
+ extract-atoms now keeps per-transcript strike counts and tombstones
+ (`extract_atoms_transcript_state`, migration v146), so a transcript that
+ deterministically yields malformed output stops re-spending LLM budget;
+ the item as filed (`recordPageFailureCount` returning null for
+ `kind !== 'page'`) is closed by that table. (c) getHealth coverage numerators are not liveness-
filtered while islanded now is (#4153): a page whose only inbound link is
from a soft-deleted page counts as covered AND orphaned simultaneously;
align the coverage EXISTS subqueries with the islanded liveness JOINs in
diff --git a/VERSION b/VERSION
index d7c2f20c92..34f40a4243 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.50.0.0
+0.50.1.0
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 50bf5f638d..cfcef0246e 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -618,6 +618,7 @@ Unit tests and what they cover:
- `test/sync-failures.test.ts` — `classifyErrorCode` regex coverage for all 12 codes against literal production message strings from `markdown.ts` and `import-file.ts`; `summarizeFailuresByCode` sort + pre-classified-honor; `recordSyncFailures` code-field persistence; `acknowledgeSyncFailures` `AcknowledgeResult` shape + backfill on legacy entries.
- `test/sync-soft-delete.serial.test.ts` — removed-file recovery arc: a `git rm` drained by sync SOFT-deletes the page (`deleted_at` set; row recoverable, not gone), an already-soft-deleted row isn't re-flipped (purge clock preserved), batch delete failures decompose to per-file batches and the run banks instead of aborting, delete → re-add inside the window revives via upsert (content updated, chunks replaced, no duplicate), soft-deleted pages stay invisible to search/getLinks/getBacklinks, the rename lane converges against an out-of-band soft delete, and full-sync reconcile + the unsyncable lane are SOFT with the purge window honored end-to-end.
- `test/sync-exclude-config.test.ts` — persisted `sync.exclude` reach: honored with no flag on incremental AND first-sync full-walk paths, trailing-slash covers directory contents, a per-call flag narrows without re-opening the persisted scope, mixed comma+newline multi-pattern values, conservative posture (pages imported before the exclusion stay live, incl. full-sync reconcile), and a throwing/unreadable config read degrades to no-persisted-scope instead of breaking the sync.
+- `test/sync-include-hidden-config.test.ts` — persisted `sync.include_hidden` reach (the dot-directory waiver's twin to `sync.exclude`): baseline control (no config, no flag → dot-directory pruned), honored with no flag on incremental AND first-sync full-walk paths, trailing-slash covers nested files (lowercased slug), an unnamed dot-directory stays pruned, a per-call `includeHidden` unions with the persisted waiver, and a throwing config read degrades to no-waiver instead of breaking the sync.
- `test/doctor.test.ts` — doctor command; assertions that `jsonb_integrity` scans the four JSONB write sites and `markdown_body_completeness` is present.
- `test/utils.test.ts` — shared SQL utilities + `tryParseEmbedding` null-return and single-warn semantics.
- `test/build-llms.test.ts` — `llms.txt`/`llms-full.txt` generator: path resolution, idempotence, spec shape, regen-drift guard, content contract, AGENTS.md install-path mirror, size-budget enforcement.
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index d0f933f093..3c3866a402 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -158,7 +158,7 @@ Every non-localOnly operation on the MCP surface: 122 tools across 23 areas. **S
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
| `capture` | Capture a quick note into the brain — the "just remember this" write. | write | yes | |
-| `delete_page` | Soft-delete a page. | write | | |
+| `delete_page` | Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). | write | | |
| `fetch` | Fetch the full text of one search result by its `id` (OpenAI deep-research contract: the search/fetch pair). | read | | |
| `get_chunks` | Get content chunks for a page | read | | |
| `get_page` | Read a page by slug (supports optional fuzzy matching). | read | yes | |
@@ -168,7 +168,7 @@ Every non-localOnly operation on the MCP surface: 122 tools across 23 areas. **S
| `put_page` | Write or replace a page (markdown with frontmatter). | write | yes | |
| `put_raw_data` | Store raw API response data for a page | write | | |
| `resolve_slugs` | Fuzzy-resolve a partial slug to matching page slugs | read | yes | |
-| `restore_page` | v0.26.5 — restore a soft-deleted page (clear deleted_at). | write | | |
+| `restore_page` | v0.26.5 — restore a soft-deleted page (clear deleted_at) and re-create its markdown file on disk (the counterpart to delete_page removing it; the result write_through field reports the outcome). | write | | |
| `revert_version` | Revert page to a previous version | write | | |
## schema
diff --git a/docs/UPGRADING_DOWNSTREAM_AGENTS.md b/docs/UPGRADING_DOWNSTREAM_AGENTS.md
index 3d455701c8..009891e125 100644
--- a/docs/UPGRADING_DOWNSTREAM_AGENTS.md
+++ b/docs/UPGRADING_DOWNSTREAM_AGENTS.md
@@ -37,7 +37,9 @@ not know to backfill the structured timeline.
3. Apply the diff (paste the new block in the indicated location).
4. Update the version banner at the top of your fork (`# Based on gbrain v0.12.0`).
5. Verify: ask the agent to write a test page and confirm the response includes
- `auto_links: { created, removed, errors }`.
+ `auto_links: { created, removed, errors }`. (Local CLI writes only — MCP
+ writes, stdio included, return `auto_links: { skipped: "remote" }` and are
+ reconciled later by the serve maintenance sweep or `gbrain sweep --once`.)
Total time: ~10 minutes for all four skills.
@@ -52,18 +54,25 @@ agent's mental model says it must call `gbrain link` after every `put_page`, whi
is redundant and can cause double-add warnings.
```markdown
-### Phase 2.5: Structured Graph Updates (automatic)
-
-Every `put_page` call automatically extracts entity references and writes them
-to the graph (`links` table) with inferred relationship types. Stale links
-(refs no longer in the page text) are removed in the same call. This is
-"auto-link" reconciliation.
-
-- No manual `add_link` calls needed for ordinary page writes.
+### Phase 2.5: Structured Graph Updates (auto-link)
+
+"Auto-link" reconciliation extracts entity references from a page and writes
+them to the graph (`links` table) with inferred relationship types; stale
+links (refs no longer in the page text) are removed. WHO runs it depends on
+the write path:
+
+- **Trusted local writes** (`gbrain put`, `gbrain capture`,
+ `gbrain call put_page`) auto-link inline and return
+ `auto_links: { created, removed, errors }`.
+- **MCP callers (stdio AND HTTP)** return `auto_links: { skipped: "remote", hint }`
+ and `auto_timeline: { skipped: "remote" }`. Body wikilinks are saved as text;
+ edges are reconciled asynchronously by the serve's maintenance sweep
+ (at startup and on 10-minute idle ticks), or on demand with
+ `gbrain sweep --once` / `gbrain extract links --source db`. Use `add_link`
+ for relationships you need immediately. Untrusted body text can plant
+ ranking-boosting edges, which is why the inline path is local-only.
- Inferred link types: `attended` (meeting -> person), `works_at`, `invested_in`,
`founded`, `advises`, `source` (frontmatter), `mentions` (default).
-- The `put_page` MCP response includes `auto_links: { created, removed, errors }`
- so the agent can verify outcomes.
- To disable: `gbrain config set auto_link false`. Default is on.
- Timeline entries with specific dates still need explicit `gbrain timeline-add`
(or batch via `gbrain extract timeline --source db`).
@@ -74,7 +83,8 @@ on every brain write (Iron Law)" without qualification, append:
```markdown
**v0.12.0 update:** Auto-link satisfies the Iron Law for entity-reference links
-on every `put_page`. The agent's Iron Law obligation is now: include the
+on every `put_page` (inline for trusted local writes; for MCP writes, once the
+serve maintenance sweep runs). The agent's Iron Law obligation is now: include the
entity reference in the page content (e.g., `[Alice](people/alice)`); auto-link
handles the structured row. Manual `add_link` calls are reserved for
relationships you can't express in markdown content.
@@ -153,8 +163,11 @@ New (paste):
**Note (v0.12.0):** Links between brain pages are auto-created on every
`put_page` call (auto-link post-hook). Step 7 focuses on content
cross-references (updating related pages' compiled truth with new signal
-from this enrichment), not on creating links. Verify via the `auto_links`
-field in the put_page response (`{ created, removed, errors }`).
+from this enrichment), not on creating links. On a trusted local write the
+put_page response carries `auto_links: { created, removed, errors }`; MCP
+writes (stdio and HTTP) return `auto_links: { skipped: "remote", hint }`
+instead — edges are reconciled by the serve maintenance sweep or
+`gbrain sweep --once`, and `add_link` covers an edge you need immediately.
Timeline entries still need explicit `gbrain timeline-add` calls.
```
@@ -178,7 +191,9 @@ Timeline entries still need explicit `gbrain timeline-add` calls.
3. **Verify auto-link works:** ask the agent to write a test page that references
`[Some Person](people/some-person)`. Confirm the put_page response includes
- `auto_links: { created: 1, removed: 0, errors: 0 }`.
+ `auto_links: { created: 1, removed: 0, errors: 0 }`. (Local CLI write; an
+ MCP write returns `auto_links: { skipped: "remote" }` — run
+ `gbrain sweep --once`, then check the edge with `gbrain graph-query`.)
4. **Verify graph traversal works:**
```bash
diff --git a/docs/ai-providers/claude-cli.md b/docs/ai-providers/claude-cli.md
index cc35dac803..acf10ac333 100644
--- a/docs/ai-providers/claude-cli.md
+++ b/docs/ai-providers/claude-cli.md
@@ -117,7 +117,7 @@ above.
| Streaming | Not implemented. `doStream()` throws. `gateway.toolLoop()` (the main caller) is non-streaming already, so this is not a practical limitation for subagent dispatch, but any caller that expects a streaming chat surface cannot use `claude-cli`. |
| Tool use | JSON emission via a system-prompt-injected protocol, not the CLI's native tool-call mechanism. Parallel tool calls in one turn round-trip correctly. |
| Multimodal | Not supported over the subprocess path. File/image message parts are rendered as a `[file <mediaType>]` text stub, not sent as actual content. |
-| Prompt caching | The recipe declares `supports_prompt_cache: false`. The CLI manages its own caching internally but does not expose it through gbrain's `cache_control` control plane, so from the gateway's point of view this model does not support prompt caching. |
+| Prompt caching | The recipe declares `supports_prompt_cache: true`: Claude Code caches prompt prefixes itself on every `--print` run (Anthropic's Claude Code docs put `-p` runs in the main-conversation TTL bucket — one hour on a subscription, five minutes on an API key). gbrain cannot place `cache_control` breakpoints on this path — the adapter renders messages to stdin text and ignores `providerOptions` — so caching is automatic rather than gateway-driven, and `doctor`'s `subagent_capability` no longer grades a claude-cli subagent tier `degraded:no_caching`. `cache_read_input_tokens` is surfaced as `usage.cachedInputTokens` (next row). |
| Usage / token counts | Reported `usage.input_tokens` / `usage.output_tokens` are read straight from the CLI's `--output-format json` envelope (`result.usage?.input_tokens` / `output_tokens`); gbrain does not independently count tokens for this path. The envelope's `cache_read_input_tokens` is surfaced as `usage.cachedInputTokens`, so cache reads are counted in gbrain's usage accounting; `cache_creation_input_tokens` is not surfaced (the AI SDK's usage shape has no corresponding field). |
| Cost figures | The recipe declares `cost_per_1m_input_usd: 3.0` / `cost_per_1m_output_usd: 15.0` — the same Sonnet-class figures the `anthropic` recipe declares (`price_last_verified: 2026-06-17`) — purely so gbrain's budget ledger has a number to attribute per call. Neither the recipe nor the adapter code checks what you're actually billed; treat these as the ledger's nominal per-call number, not a verified charge. The `--max-usd` / `--max-cost` budget gate does not read them either: it prices `claude-cli:<model>` at the nominal Anthropic rate for that model, and a short alias (`claude-cli:haiku`) prices identically to the dated id it resolves to; `pricing.overrides` forces $0 or a real rate for any `claude-cli:*` string. |
| User-level CLAUDE.md | `~/.claude/CLAUDE.md` still loads on every call (see above) — only the working directory changes (see "What actually happens on a call" for exactly what that directory is and isn't). |
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index c95581be74..534d9ef9a5 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -22,8 +22,8 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`). Two load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`.
- `src/core/ops/pages.ts` — the page-domain op module (`get_page`, `put_page`, `delete_page`/`restore_page`, `capture`, …; the source-scoping contract of the delete/restore trio is described under `src/core/destructive-guard.ts`). `get_page` resolution ladder: exact read in the caller's scope → alias hop → fuzzy. The alias hop scopes its lookup to the federated grant (`sourceIds[]`) > the scalar `sourceId` > (trusted unscoped only) every LIVE source — archived sources' alias rows count only when `include_deleted` asks for archived material — through `engine.resolveSlugWithAliasDetailed`, then reads the canonical page IN THE SOURCE THAT OWNS THE ALIAS ROW (`getPage(canonical, { sourceId: hit.source_id })`): a federated `getPage` prefers the anchor source, so an unrelated live page at the canonical slug in another granted source would otherwise shadow the alias owner's page. The redirect target composes with the same private-page gate as the exact read and reports `resolved_slug`. `capture`: an EXPLICIT type (the `type` param, else a frontmatter `type:` in the content — `explicitCaptureType` in `src/core/capture-content.ts`, BOM/CRLF tolerant, malformed YAML → none) is validated against the active pack when one resolves (`schema-pack/write-vocabulary.ts`) and IS the effective type for both the default slug and the merged frontmatter — approved as X, stored as X; no explicit type stamps `note` (never checked). Sits at its module-size ratchet ceiling (`scripts/module-size-limits.tsv`); the next growth peels a submodule. Pinned by `test/get-page-federated-scope.test.ts`, `test/capture-explicit-type.test.ts`, and the engine-parity suite (both engines pick the same owning row). The alias hop has no catch of its own: both engines return `null` for the pre-v104 missing-table case, so any other rejection (connection reset, timeout) propagates instead of degrading to `page_not_found`.
- `src/core/ops/admin.ts` — the admin/diagnostics domain module (`get_stats`, `get_health`, `get_brain_identity`, …). All three aggregate ops confine remote callers via the same ladder reads use: `ctx.remote === false` keeps the trusted brain-wide view; every other caller gets `sourceScopeOpts(ctx)` (federated array > scalar > the unmatchable `__all__` sentinel, which fail-closes to zeros) threaded into `engine.getStats(scope)`/`getHealth(scope)` — aggregates leak by subtraction, so they scope exactly like reads, and read-scope `get_brain_identity` is confined the same way. `get_health`'s `migrations {pending, partial, wedged, skipped_future}` block stays GLOBAL for scoped callers by decision: it is a host filesystem ledger with no per-source semantics, a wedged host migration is exactly what a remote agent needs to see to explain degraded behavior, and it is composed at the op layer (not in `BrainEngine.getHealth` — growing the engine interface would force both engines to duplicate a file read).
-- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run.
-- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)` — cheap cross-source enumeration instead of a `getAllSlugs()→getPage(slug)` N+1 (which would silently default to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. `traversePathsDetailed(slug, opts?)` returns `{ paths: GraphPath[], truncated }` — the final SELECT of the path-enumerating recursive CTE is bounded at `TRAVERSE_PATH_ROW_CAP + 1` rows on both engines (the probe row signals overflow; `ORDER BY depth` means the deepest edges are dropped, so a truncated result is still the complete shallow neighbourhood; the cap counts raw rows before the in-memory edge dedup, so `paths.length` alone cannot reveal truncation) and `traversePaths` is its `.paths` projection. `resolveSlugWithAliasDetailed(slug, sourceOrSources)` returns `{ canonical_slug, source_id } | null` — the winning alias row AND its owning source under the same scope/precedence rules (`ORDER BY array_position(scope, source_id), id`; null when nothing matches or the `slug_aliases` table does not exist yet); `resolveSlugWithAlias` is its canonical-slug projection (falls back to the input slug). A consumer that goes on to read the canonical page must scope that read to `source_id`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks`/`getChunks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); `getChunks` falls back to the `'default'` source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (`getChunksWithEmbeddings` stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise<GraphNode[]>` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise<string[]>` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. `softDeletePages(slugs, {sourceId}): Promise<string[]>` is the batch soft-delete twin, mirroring `deletePages`' contract exactly (required `sourceId`, `> DELETE_BATCH_SIZE` throws, empty input short-circuits, caller owns chunking + decompose-to-one-element-batches on failure): one `UPDATE … SET deleted_at = now() … AND deleted_at IS NULL … RETURNING slug` round-trip returning only the slugs that actually flipped active→soft-deleted — the `deleted_at IS NULL` predicate is load-bearing so a re-run never refreshes an already-soft-deleted row's 72h purge clock — and NOTHING cascades (chunks/links/timeline stay behind the read-side `deleted_at` filters; the autopilot purge phase hard-deletes after 72h; a re-import within the window revives via `putPage`'s upsert; `deletePage`/`deletePages` remain the purge/teardown primitives). `getStats(opts?)` / `getHealth(opts?)` take an optional `{sourceId?, sourceIds?}` scope (same shape as `sourceScopeOpts` output): omitted = brain-wide; scoped = EVERY counter/coverage/degree confines to the grant, including derived-table counts via their page joins, and link-derived numbers count only edges with BOTH endpoints in scope — so an excluded source's numbers can't be recovered by subtraction. Consumer is the remote-caller ladder in `src/core/ops/admin.ts`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number>` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional `findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>` (identity precedence is content_hash OR frontmatter->>'id', both with `deleted_at IS NULL`); (2) `resolveSlugs(partial, opts?)` extended with `{sourceId?, sourceIds?}` so the MCP fuzzy `get_page` path scopes by source (field names match `sourceScopeOpts(ctx)` output so handlers spread directly; no opts gives the unscoped behavior). Plus a stable tiebreaker `ORDER BY score DESC, page_id ASC, chunk_id ASC` in `searchVector` in both engines: on a score tie (basis-vector eval fixtures) older `page_id` wins, so a new index on `pages` cannot flip ranking on tied scores.
+- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's result is empty and `hasUnsealedPagesInScope` finds markdown pages in scope below the safe-chunk index version (sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by `pages_chunker_version_idx` as an Index Cond — NOT the COALESCE `safeChunksFilter` form, which the partial btree cannot serve and which walked every markdown page on a sealed brain; pinned by `test/search-safe-index-probe.test.ts`; fail-open; ignores the call's `types`/`excludePrivate`), it appends the `safe_index_pending` degraded stage so the MCP empty-result block names the pending `gbrain reindex --markdown` instead of a clean miss; the withholding itself is unchanged.
+- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)` — cheap cross-source enumeration instead of a `getAllSlugs()→getPage(slug)` N+1 (which would silently default to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. `traversePathsDetailed(slug, opts?)` returns `{ paths: GraphPath[], truncated }` — the final SELECT of the path-enumerating recursive CTE is bounded at `TRAVERSE_PATH_ROW_CAP + 1` rows on both engines (the probe row signals overflow; `ORDER BY depth` means the deepest edges are dropped, so a truncated result is still the complete shallow neighbourhood; the cap counts raw rows before the in-memory edge dedup, so `paths.length` alone cannot reveal truncation) and `traversePaths` is its `.paths` projection. `resolveSlugWithAliasDetailed(slug, sourceOrSources)` returns `{ canonical_slug, source_id } | null` — the winning alias row AND its owning source under the same scope/precedence rules (`ORDER BY array_position(scope, source_id), id`; null when nothing matches or the `slug_aliases` table does not exist yet); `resolveSlugWithAlias` is its canonical-slug projection (falls back to the input slug). A consumer that goes on to read the canonical page must scope that read to `source_id`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks`/`getChunks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); `getChunks` falls back to the `'default'` source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (`getChunksWithEmbeddings` stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise<GraphNode[]>` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence and offsetting `row_num` past the canonical page's current MAX(row_num) (all rows incl. expired — the partial `idx_facts_fence_key` only excludes NULL; NULL stays NULL) so overlapping fence rows never collide; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise<string[]>` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. `softDeletePages(slugs, {sourceId}): Promise<string[]>` is the batch soft-delete twin, mirroring `deletePages`' contract exactly (required `sourceId`, `> DELETE_BATCH_SIZE` throws, empty input short-circuits, caller owns chunking + decompose-to-one-element-batches on failure): one `UPDATE … SET deleted_at = now() … AND deleted_at IS NULL … RETURNING slug` round-trip returning only the slugs that actually flipped active→soft-deleted — the `deleted_at IS NULL` predicate is load-bearing so a re-run never refreshes an already-soft-deleted row's 72h purge clock — and NOTHING cascades (chunks/links/timeline stay behind the read-side `deleted_at` filters; the autopilot purge phase hard-deletes after 72h; a re-import within the window revives via `putPage`'s upsert; `deletePage`/`deletePages` remain the purge/teardown primitives). `getStats(opts?)` / `getHealth(opts?)` take an optional `{sourceId?, sourceIds?}` scope (same shape as `sourceScopeOpts` output): omitted = brain-wide; scoped = EVERY counter/coverage/degree confines to the grant, including derived-table counts via their page joins, and link-derived numbers count only edges with BOTH endpoints in scope — so an excluded source's numbers can't be recovered by subtraction. Consumer is the remote-caller ladder in `src/core/ops/admin.ts`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number>` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional `findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>` (identity precedence is content_hash OR frontmatter->>'id', both with `deleted_at IS NULL`); (2) `resolveSlugs(partial, opts?)` extended with `{sourceId?, sourceIds?}` so the MCP fuzzy `get_page` path scopes by source (field names match `sourceScopeOpts(ctx)` output so handlers spread directly; no opts gives the unscoped behavior). Plus a stable tiebreaker `ORDER BY score DESC, page_id ASC, chunk_id ASC` in `searchVector` in both engines: on a score tie (basis-vector eval fixtures) older `page_id` wins, so a new index on `pages` cannot flip ranking on tied scores.
- `src/core/engine-constants.ts` — single source of truth for engine batch-sizing constants. Exports `DELETE_BATCH_SIZE = 500` consumed by both engines' `deletePages` + `resolveSlugsByPaths` and by the sync delete + rename loops. Lives outside `engine.ts` (the interface module) to avoid circular-import worry — bounded per-statement work for predictable lock hold time + write amplification. Also exports `TRAVERSE_PATH_ROW_CAP = 5000`, the raw-row bound on `traversePaths`/`traversePathsDetailed` (both engines `LIMIT CAP + 1`; the extra row is the truncation probe; counted before edge dedup).
- `src/core/background-work.ts` — process background-work registry: the single owner of "drain every fire-and-forget DB-write sink before the engine goes away," with TWO exit points. `registerBackgroundWorkDrainer({name, order, drain(timeoutMs, mode), abort?})` over a `Map<name, BackgroundWorkDrainer>` (idempotent registration by name; `__registerDrainerForTest` returns an unregister handle); `mode` is `'exit' | 'disconnect'` (`'exit'` = CLI teardown, engine still live, residual buffers may flush; `'disconnect'` = an engine is mid-disconnect, sinks await only IN-FLIGHT work and never start new writes). `drainAllBackgroundWorkForCliExit({timeoutMs})` runs mode `'exit'` with abort allowed; `drainBackgroundWorkBeforeDisconnect({timeoutMs})` is called by BOTH engines' `disconnect()` so an in-flight statement settles before the underlying handle closes — PGLite's `close()` deadlocks PERMANENTLY with a statement in flight — and it NEVER calls `abort()` (permanent process state, wrong for a long-lived `gbrain serve` disconnecting one engine); a partial disconnect-drain warns once per sink to stderr. The module stays a zero-import leaf on purpose (both engines import it statically). Drains in explicit `(order, name)` order — facts FIRST (order 0) so its abort-path DB `logIngest` runs against the freshest live engine — and AWAITS `abort()` only when `drain()` reports `unfinished>0` in `'exit'` mode. Best-effort per drainer: one sink's failure never blocks the others or the disconnect. SIX sinks register at module import: `facts/queue.ts` (order 0; `abort`=`shutdown()` cancels a hung facts:absorb Haiku via internalAbort), `last-retrieved.ts` (order 1), `search/hybrid.ts` (order 2; `awaitPendingSearchCacheWrites` bounded via `Promise.race`), `eval-capture.ts` (order 3; `captureEvalCandidate` self-tracks its promise via `awaitPendingEvalCaptures`), `context/volunteer-events.ts` (order 4 — batched volunteer-event INSERTs, drained like the rest), `search/telemetry.ts` (order 5 — `awaitPendingTelemetryFlush`: awaits the in-flight flush in both modes, flushes residual buckets only in `'exit'` mode so short-lived CLI calls land in `search_telemetry` on clean exit). Every cli.ts teardown site reaches it through `finishCliTeardown` (`src/core/cli-force-exit.ts`), which drains the registry before `engine.disconnect()`, so `db.close()` cannot race an in-flight job and pin the PGLite single-writer lock. Exports `backgroundWorkSinkCount()` so the teardown helper computes its backstop deadline from the registered sink count, plus the shared teardown budgets: `MAX_TIMER_DELAY_MS` (the 2^31−1 setTimeout ceiling; `process-watchdog.ts` aliases it as `MAX_WATCHDOG_TIMER_MS`), `SINK_DRAIN_TIMEOUT_MS` (the per-sink drain bound, used as the `runDrainers` default), and `pgliteCloseTimeoutMs()` (the env-tunable in-loop close bound, defined here so `cli-force-exit`'s computed deadline budgets the SAME bound the engine honors). CLI-EXIT-ONLY: the facts `shutdown()` abort is permanent process state, never call in a long-lived `gbrain serve`. Companion changes: `src/core/ai/gateway.ts` `withDefaultTimeout(caller, ms)` bounds every outbound AI call (chat 300s, embed+multimodal 60s; env `GBRAIN_AI_{CHAT,EMBED,MULTIMODAL}_TIMEOUT_MS`; composed with caller signals via `AbortSignal.any`) and the teardown backstop honors an errored op's exit code so a hung disconnect can't mask failure as success (see `cli-force-exit.ts`); `src/core/postgres-engine.ts` `reconnect()` module-mode branch re-establishes via idempotent `db.connect()` + `connectionManager.setReadPool` refresh instead of `db.disconnect()` (no null window for concurrent ops; fail-loud on real connect failure); `src/core/search/hybrid.ts` `embedQueryBounded` + a shared `QueryEmbedDeadline` (6s, floored 2s per embed via `MIN_QUERY_EMBED_BUDGET_MS`; env `GBRAIN_QUERY_EMBED_TIMEOUT_MS`) bounds the cache-lookup AND inner query embeds so a stalled provider falls back to keyword instead of stalling the whole op. Pinned by `test/core/background-work.test.ts`, `test/search/query-embed-deadline.test.ts`, `test/eval-capture-drain.test.ts`, `test/e2e/postgres-reconnect-singleton.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts`, `test/fix-wave-structural.test.ts`.
- `src/core/search/read-policy-sql.ts` — shared internal concrete-page SQL policy (`PageReadScope` in `types.ts`): nonempty federated grants precede scalar source; `excludePrivate` is resolved by `ops/context.ts:readPolicyOpts`, never an MCP override. Optional live-page filtering excludes deleted/quarantined pages and archived sources. Both engines apply policy inside content, version, timeline, graph and identity reads before limits. While page privacy is enforced, history requires both current-page and snapshot visibility. Links/timeline projections independently authorize originating pages.
@@ -34,7 +34,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/ops/insights.ts` — stored contradiction reports load only for explicitly trusted, unscoped local callers. Other callers receive the fixed availability note and an empty contradictions list before any report storage access. Expert search threads page and holder policy and performs final authorized-page admission after enrichment.
- `src/core/search/graph-signals.ts` — per-query graph-signals helper. `applyGraphSignals(results, engine, opts)` runs as the 4th post-fusion stage (after backlink/salience/recency). Three boosts: `ADJACENCY_BOOST=1.05` (page linked from 2+ OTHER top-K results — local hub for THIS query), `CROSS_SOURCE_BOOST=1.10` (page linked from 2+ DIFFERENT sources — corroborated across team brains, dormant in single-source brains), `SESSION_DEMOTE=0.95` (3+ results from same chat session — keep the highest-scoring at full score, demote the rest). All three inherit the floor-ratio gate preventing weak pages from being boosted past strong ones via popularity. `computeScoreDistribution(results)` emits min/p25/p50/p75/p95/max + `reorder_band_width`. `sessionPrefix(slug)` extracts the chat-session anchor (`chat/2026-05-15-...`). Pure `pairedBootstrapPValue(deltas, resamples, rng)` exported for eval gates. Test seam via `adjacencyFn` DI. Fail-open: any error logs via `logGraphSignalsFailure` (JSONL audit via `audit-writer`) and returns the input array unchanged. Pinned by `test/search/graph-signals.test.ts` (incl. the IRON-RULE floor-gate guard).
- `src/core/search/explain-formatter.ts` — renders `SearchResult[]` as a multi-line per-result breakdown for `gbrain search --explain`. Reads every boost-stamping field; also prints the raw query↔chunk cosine (`SearchResult.cosine`, the calibrated signal evidence keys off) next to the blended score when present — absent on keyword-only / no-embedding paths. Handles the "no boosts applied" empty path. 4-decimal precision with trailing-zero strip. `formatResultsExplain(results, meta?)` prepends header lines from the captured retrieval meta when present — `formatAutocutSummary` (the autocut decision) and `formatDegradedSummary(meta.degraded)`, which renders the closed `degraded[]` vocabulary as `degraded: reranker_skipped (no_key)` (null when the run was clean); `cli.ts:formatResult` threads `lastRetrievalMeta` into it, so a silently skipped reranker is visible from the CLI. Pinned by `test/search/explain-formatter.test.ts` + `test/cli-explain-degraded-render.test.ts`.
-- `src/core/search/mode.ts` — Named search-mode bundles and retained semantic-cache key machinery; persisted result reuse remains disabled. `MODE_BUNDLES` (conservative/balanced/tokenmax) and the resolution chain (per-call `SearchOpts` → per-key `search.*` config → bundle → balanced fallback) resolve every search knob; `knobsHash` folds registered search knobs into the `query_cache` key, and `KNOBS_HASH_VERSION` (exported from this file — the single source of truth for the current cache-key version) is bumped whenever a new knob shapes results so stale cache rows become unreachable. `graph_signals: boolean` knob in `ModeBundle` (defaults: `conservative=false`, `balanced=true`, `tokenmax=true`). `KNOBS_HASH_VERSION` appends a `gs=` parts entry per the cache-key contamination convention so a graph-on cache write can't be served to a graph-off lookup. `SearchKeyOverrides` + `SearchPerCallOpts` + `loadOverridesFromConfig` + `SEARCH_MODE_CONFIG_KEYS` + `resolveSearchMode` + `attributeKnob` all carry the field. Opt-out: `gbrain config set search.graph_signals false`. `query_cache` rows written under an older hash version hash differently — natural row segregation, cleared within `cache.ttl_seconds` (3600s default). `title_boost: number | undefined` knob in `ModeBundle` (default `1.25` for all three modes; multiplier for the post-fusion title-phrase boost). Override chain: per-call `SearchOpts` → `search.title_boost` config (clamped `[1.0, 5.0]`) → bundle. `KNOBS_HASH_VERSION` appends a `tib=` parts entry so a title-boost-on cache write can't be served to a title-boost-off lookup. `SEARCH_MODE_CONFIG_KEYS` gains `search.title_boost`. Cross-modal knobs in `ModeBundle`: `cross_modal_both_text_weight`/`cross_modal_both_image_weight` (weighted RRF for 'both' modality, defaults 0.6/0.4), `image_query_text_refinement_weight`/`image_query_image_refinement_weight` (hybrid intersect for `searchByImage` query refinement, defaults 0.4/0.6), `unified_multimodal` + `unified_multimodal_only` (unified-column routing flags), `cross_modal_llm_intent` (opt-in LLM escalation). `SEARCH_MODE_CONFIG_KEYS` carries the corresponding config keys, and the modality knobs participate in `knobsHash` so a cached text-mode result can't be served to an image-mode caller. Retrieval-quality knobs `autocut_min_top` (default 0.35 in all three bundles; config `search.autocut_min_top`; folds into `knobsHash` as an `acm=` part) and `evidence_cosine_floor` (default 0.8 in all three bundles; config `search.evidence_cosine_floor`; labels evidence — result-set-shape-neutral, so not hashed) ride the same bundle → config → per-call chain. `keywordOrFallback: boolean` knob in `ModeBundle` (default true in all three bundles; config `search.keywordOrFallback`): the keyword arm's AND→OR zero-recall retry — corpora the FTS config can't stem (CJK/agglutinative text under `'english'`) can turn it off because the OR retry has no IDF demotion and its common-token hits read as noise in the RRF blend; folds into `knobsHash` as a `kof=` part. `KnobsHashContext` additionally carries the EFFECTIVE per-call salience/recency boost modes (`sal=`/`rec=` — explicit `SearchOpts` ?? the classifier's auto-suggestion, resolved by the same chain bare `hybridSearch` uses) and the per-engine `search.intent_patterns` config fingerprint (`ipat=`, from `query-intent.ts`'s `intentPatternFingerprint`; threaded through ctx, never read process-globally, so a multi-engine process can't key one brain's rows under another brain's patterns) — a reordered or reclassified write can never serve a differently-configured lookup. Cache HITS slice the stored page to the same resolved result count as misses (per-call `limit` → the mode's `searchLimit`) in `hybridSearchCached`, so a mode's result-count knob holds on both paths; nonzero offsets (positive OR negative) skip the cache entirely. `expansion_variant_budget: number | null` knob in `ModeBundle` (`null` in all three bundles; config `search.expansion_variant_budget` accepts `legacy`/`null` or a number in (0, 4] through the ONE range contract `normalizeExpansionVariantBudget` in `fusion-lists.ts` — out-of-range falls through to the bundle; per-call `HybridSearchOpts.expansionVariantBudget`, normalized by the same function in both the inner search and the cache resolver): the total RRF weight the NON-EMPTY expansion variant/clause lists share at fusion (`weight_i = b / n_voting_arms`; the original list always keeps weight 1), `null` = legacy weight 1 on every list (byte-identical fusion), a no-op when `expansion` is off. It folds into `knobsHash` as the last, append-only `evb=` part (`legacy` or the budget to 3 decimals) — `KNOBS_HASH_VERSION` is 29 with that part in — so a budget-weighted write can never serve a legacy lookup. `KNOB_NULL_LABELS` + `formatKnobValue` in `modes-report.ts` render its legitimate null as `legacy (null)` in `gbrain search modes` (plain `(undefined)` stays reserved for genuinely unset knobs). `relational_rerank_pin: number` knob in `ModeBundle` (3 in all three bundles — a no-op under `conservative`, which has no reranker; config `search.relational_rerank_pin` accepts `off`/`0` or an integer in [0, 10] through the ONE range contract `normalizeRelationalRerankPin` in `relational-rerank-pin.ts`, out-of-range falls through to the bundle; per-call `SearchOpts.relationalRerankPin`, normalized by the same function in both the inner search and the cache resolver): how many relational-arm rows `pinRelationalRows` re-pins above the reranked text rows after `applyReranker`. It folds into `knobsHash` as the append-only `rrp=` part, riding `KNOBS_HASH_VERSION` 29 together with `evb=` (one bump per wave — both parts landed before v29 shipped; a partial-knobs literal without the field hashes as the bundle default), so a pin-3 write can never serve a pin-0 lookup. Pinned by `test/search-mode.test.ts` (bundle snapshots + hash pins), `test/search/knobs-hash-reranker.test.ts` (the version comment chain), `test/config-adaptive-return-keys.test.ts`, `test/search/modes-report-coverage.test.ts`.
+- `src/core/search/mode.ts` — Named search-mode bundles and retained semantic-cache key machinery; persisted result reuse remains disabled. `MODE_BUNDLES` (conservative/balanced/tokenmax) and the resolution chain (per-call `SearchOpts` → per-key `search.*` config → bundle → balanced fallback) resolve every search knob; `knobsHash` folds registered search knobs into the `query_cache` key, and `KNOBS_HASH_VERSION` (exported from this file — the single source of truth for the current cache-key version) is bumped whenever a new knob shapes results so stale cache rows become unreachable. `graph_signals: boolean` knob in `ModeBundle` (defaults: `conservative=false`, `balanced=true`, `tokenmax=true`). `KNOBS_HASH_VERSION` appends a `gs=` parts entry per the cache-key contamination convention so a graph-on cache write can't be served to a graph-off lookup. `SearchKeyOverrides` + `SearchPerCallOpts` + `loadOverridesFromConfig` + `SEARCH_MODE_CONFIG_KEYS` + `resolveSearchMode` + `attributeKnob` all carry the field. Opt-out: `gbrain config set search.graph_signals false`. `query_cache` rows written under an older hash version hash differently — natural row segregation, cleared within `cache.ttl_seconds` (3600s default). `title_boost: number | undefined` knob in `ModeBundle` (default `1.25` for all three modes; multiplier for the post-fusion title-phrase boost). Override chain: per-call `SearchOpts` → `search.title_boost` config (clamped `[1.0, 5.0]`) → bundle. `KNOBS_HASH_VERSION` appends a `tib=` parts entry so a title-boost-on cache write can't be served to a title-boost-off lookup. `SEARCH_MODE_CONFIG_KEYS` gains `search.title_boost`. Cross-modal knobs in `ModeBundle`: `cross_modal_both_text_weight`/`cross_modal_both_image_weight` (weighted RRF for 'both' modality, defaults 0.6/0.4), `image_query_text_refinement_weight`/`image_query_image_refinement_weight` (hybrid intersect for `searchByImage` query refinement, defaults 0.4/0.6), `unified_multimodal` + `unified_multimodal_only` (unified-column routing flags), `cross_modal_llm_intent` (opt-in LLM escalation). `KNOB_CONFIG_KEY` (a `Record<keyof ModeBundle, string>`, so every knob names the `search.*` key `loadOverridesFromConfig` reads it from) is the single knob→key map: `SEARCH_MODE_CONFIG_KEYS` derives from it, `attributeKnob` prints it as the override `source_detail`, and `KNOWN_CONFIG_KEYS` in `config.ts` hand-mirrors it (config.ts stays import-light; `test/config-search-registry.test.ts` pins the two equal), and the modality knobs participate in `knobsHash` so a cached text-mode result can't be served to an image-mode caller. Retrieval-quality knobs `autocut_min_top` (default 0.35 in all three bundles; config `search.autocut_min_top`; folds into `knobsHash` as an `acm=` part) and `evidence_cosine_floor` (default 0.8 in all three bundles; config `search.evidence_cosine_floor`; labels evidence — result-set-shape-neutral, so not hashed) ride the same bundle → config → per-call chain. `keywordOrFallback: boolean` knob in `ModeBundle` (default true in all three bundles; config `search.keywordOrFallback`): the keyword arm's AND→OR zero-recall retry — corpora the FTS config can't stem (CJK/agglutinative text under `'english'`) can turn it off because the OR retry has no IDF demotion and its common-token hits read as noise in the RRF blend; folds into `knobsHash` as a `kof=` part. `KnobsHashContext` additionally carries the EFFECTIVE per-call salience/recency boost modes (`sal=`/`rec=` — explicit `SearchOpts` ?? the classifier's auto-suggestion, resolved by the same chain bare `hybridSearch` uses) and the per-engine `search.intent_patterns` config fingerprint (`ipat=`, from `query-intent.ts`'s `intentPatternFingerprint`; threaded through ctx, never read process-globally, so a multi-engine process can't key one brain's rows under another brain's patterns) — a reordered or reclassified write can never serve a differently-configured lookup. Cache HITS slice the stored page to the same resolved result count as misses (per-call `limit` → the mode's `searchLimit`) in `hybridSearchCached`, so a mode's result-count knob holds on both paths; nonzero offsets (positive OR negative) skip the cache entirely. `expansion_variant_budget: number | null` knob in `ModeBundle` (`null` in all three bundles; config `search.expansion_variant_budget` accepts `legacy`/`null` or a number in (0, 4] through the ONE range contract `normalizeExpansionVariantBudget` in `fusion-lists.ts` — out-of-range falls through to the bundle; per-call `HybridSearchOpts.expansionVariantBudget`, normalized by the same function in both the inner search and the cache resolver): the total RRF weight the NON-EMPTY expansion variant/clause lists share at fusion (`weight_i = b / n_voting_arms`; the original list always keeps weight 1), `null` = legacy weight 1 on every list (byte-identical fusion), a no-op when `expansion` is off. It folds into `knobsHash` as the last, append-only `evb=` part (`legacy` or the budget to 3 decimals) — `KNOBS_HASH_VERSION` is 29 with that part in — so a budget-weighted write can never serve a legacy lookup. `KNOB_NULL_LABELS` + `formatKnobValue` in `modes-report.ts` render its legitimate null as `legacy (null)` in `gbrain search modes` (plain `(undefined)` stays reserved for genuinely unset knobs). `relational_rerank_pin: number` knob in `ModeBundle` (3 in all three bundles — a no-op under `conservative`, which has no reranker; config `search.relational_rerank_pin` accepts `off`/`0` or an integer in [0, 10] through the ONE range contract `normalizeRelationalRerankPin` in `relational-rerank-pin.ts`, out-of-range falls through to the bundle; per-call `SearchOpts.relationalRerankPin`, normalized by the same function in both the inner search and the cache resolver): how many relational-arm rows `pinRelationalRows` re-pins above the reranked text rows after `applyReranker`. It folds into `knobsHash` as the append-only `rrp=` part, riding `KNOBS_HASH_VERSION` 29 together with `evb=` (one bump per wave — both parts landed before v29 shipped; a partial-knobs literal without the field hashes as the bundle default), so a pin-3 write can never serve a pin-0 lookup. Pinned by `test/search-mode.test.ts` (bundle snapshots + hash pins), `test/search/knobs-hash-reranker.test.ts` (the version comment chain), `test/config-adaptive-return-keys.test.ts`, `test/search/modes-report-coverage.test.ts`.
- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, sunset_passed, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`.
- `src/core/context-engine.ts` + `src/openclaw-context-engine.ts` — the deterministic context engine OpenClaw loads on every turn (`assemble()` injects the Live Context block, zero-LLM). `createGBrainContextEngine({workspaceDir, resolveEntities?})` accepts an OPTIONAL host-injected resolver (`ENGINE_API_VERSION` 0.3.0, additive — older hosts work unchanged; the plugin entry maps `ctx.resolveEntities`/`ctx.brainQuery` onto it). Checkpoint compaction: `compact()` runs a time-bounded (8s), fail-open, lazily-imported checkpoint step BEFORE delegating — spools the since-last-boundary window (openclaw tail reader over the exported adapter mapper, 40-turn cap = the no-prior-boundary fallback) as a content-addressed corpus segment + ledger entry, then rung 2 (PGLite: one `bankOnly`+`flushCorpusFile` IPC round trip to serve) or rung 3 (Postgres: inline harvest over the reflex ladder's exported `getDirectPostgresEngine` singleton, under sweep claim fencing + capability/kill-switch gates, abort post-check) — and rides an additive `result.gbrain_checkpoint` bag on the delegate's return (`ownsCompaction` stays false). After the segment is spooled, the Memorable receipt lane runs (gate + stamp via `memorableGateAllowed`, span-filtered redacted tool calls, `recordAndRelayReceipt` with `harness: 'openclaw'` — per-compaction capture, content-hash dedup on retries, fail-open for the checkpoint; the whole block is skipped once the host's compact() deadline has fired; the rendered segment text is re-scanned with highEntropy at receipt time and the relay REFUSED fail-closed on any hit — the segment rendering feeds the ledger hash and cannot change, so the next compaction window re-evaluates; this lane NEVER compacts the receipts file — the hook lane is the ONE compactor, single-rewriter rule — but DOES trim the relay file, since an openclaw-only host has no hook lane and converging newest-keeping trims make concurrent trims safe). `assemble()` consumes `sessionId ?? sessionKey` and splices a deterministic envelope-bearing Compaction-checkpoint block at parts[1] (after Live Context) from the banked manifest via an in-process memo + hash-keyed polls (≤5; stale manifests can't satisfy a poll for the new segment; no manifest ⇒ byte-identical output). `assemble()` runs the Retrieval Reflex after the Live Context block: extracts the current turn's user text, builds prior-context text (every message EXCEPT the current turn — suppression must not see the triggering mention), passes the rolling window (`getWindowTurns`, last 12 user/assistant turns; the reflex slices to its configured `retrieval_reflex_window_turns`), and appends the pointer block. `warmReflex()` fires at construction.
- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract) — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT.
@@ -63,12 +63,13 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/doctor/checks/search-eval.ts` — search, model, and AI-config health checks. `checkChatFallbackChainInert` returns one warning when either the effective file/environment config or the DB plane has a non-empty `chat_fallback_chain`; it returns `null` when both are empty, so clean doctor reports add no line. The local and remote doctor registries both consume the check. `checkSearchMode` (`search_mode`) reports the resolved mode and its `search.*` overrides; when the only override is an explicit `search.reranker.model` row equal to the mode bundle's own default (a row an init may have written on Voyage installs) it is called redundant with the precise `gbrain config unset search.reranker.model` — never a `--reset`, which would also wipe every other tuned search knob — and overrides that keep a brain OFF a sunsetting bundle default are never reset-nagged (a reset would re-arm a dying provider).
- `src/core/default-source-path-check.ts` — pure `assessDefaultSourcePath(input)` verdict for the `default_source_local_path` doctor check (no DB/FS access — caller supplies gathered inputs, the npm-squat-check.ts shape). INVARIANT: `default.local_path: null` is the DESIGNED fallback topology (write-through nests under `sync.repo_path`), NOT an error — the check warns ONLY when the null pointer provably breaks something: the fallback repo is another source's own working tree (the leak-guard collision: every unscoped default write-through silently skipped), or default has file-backed pages and no resolvable root. Everything else (no pages, resolvable fallback, deliberate DB-only brain) is ok. The repair it names is the non-destructive `gbrain sources set-path default <path>`.
- `src/commands/doctor/checks/default-source-path.ts` — the gathering wrapper on the doctor surface: reads the `default` sources row, page counts (live + file-backed), `sync.repo_path` resolution, and the leak-guard collision, then delegates the verdict to `assessDefaultSourcePath`. Only gathers the fallback-topology inputs when the pointer is actually null; returns null for the skip verdict.
+- `src/commands/doctor/checks/fts-reindex.ts` — `ftsReindexIncompleteCheck(engine)`: the `fts_reindex_incomplete` check. Reads the `fts.reindex_in_progress` config row that `reindex-search-vector` sets before its trigger-language flip and clears only after both backfills finish; null (nothing pushed) when absent, `fail` naming the language and the resume command (`GBRAIN_FTS_LANGUAGE=<lang> gbrain reindex-search-vector --yes`) when set, because un-backfilled rows are unreachable by keyword search under the new configuration. Registered in doctor.ts inside the `engine !== null` lazy-import guard (skipped on `--fast` / DB-down); category `brain`. Pinned by `test/doctor-fts-reindex-incomplete.test.ts`.
- `src/commands/doctor/checks/home-worktree.ts` — the `home_dir_in_worktree` check: walks up from the gbrain home looking for an enclosing `.git` (dir or linked-worktree file), warning that a `git add` from the worktree root could stage the brain; stops at $HOME. Both anchors (`GBRAIN_HOME`, `$HOME`) are `path.resolve()`d before the containment test, so a trailing-slash `HOME=/home/user/` (a common shell/launchd spelling) cannot make a brain inside a worktree grade ok. `isValidGitMarker` structurally validates a candidate before it counts (a `.git/` dir must contain HEAD; a `.git` file must start with `gitdir:` — git itself rejects anything else), and invalid candidates CONTINUE the walk so a valid repo higher up still warns. Cheap (stat + read, no subprocess) — runs on every doctor invocation including `--fast`.
- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/postgres-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — a superset of PGLite's probe set: the shared column-only forward-reference cases (`files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`/`archived_at`/`archive_expires_at`, `timeline_entries.event_page_id`) plus Postgres-blob-only probes for state the PGLite blob doesn't carry (`dream_verdicts.expires_at` — see the forward-reference-bootstrap.ts entry); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-ownership.test.ts`. `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). Test seam `__resetFactsEmbeddingCastCacheForTest()` clears the per-engine cache. `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`.
- `src/commands/doctor/checks/integrations-memorable.ts` — `memorable_relay_health` (OPS category), the doctor surface for the optional third-party relay. Engine-free (file-plane reads only), pushed unconditionally so it survives `--fast`/`--scope`. Rung ladder: gate off → quiet ok; enabled WITHOUT the gbrain disclosure stamp → FAIL naming the exact fix (the `memorable enable` out-of-band state); CLI-side consent absent → warn; no runnable binary → FAIL; last relay run failed → warn with the CLAMPED cause (the shared `clampRelayCause`; child text never lands in a doctor message verbatim) — EXCEPT the documented openclaw `no_decisive_steps` rejection, which becomes an ok-with-note (`expected_openclaw_rejection`, name-only capture refused until argument capture lands) held as a DEFERRED note that surfaces only after the codex rung below passes: on a mixed openclaw+codex host the rejection is the persistent last-relay state, and an early return would paint the check green while a trust-stale codex hook sits silently dead; receipts written but the child never reported → warn; codex hooks wired but no codex-harness receipt in the recent receipt window (tail-200 read) → warn (`codex_hooks_never_fired` — codex hooks fail silently on a stale trust entry); healthy → ok with structured details (`out_of_band_settable: true` always rides — the enable flag can be flipped by the external CLI, which is exactly why the gate also demands the stamp). Pinned by `test/doctor-memorable.test.ts`.
-- `src/core/postgres-engine/` + `src/core/pglite-engine/` — narrow-deps engine module directories, mirrored in lockstep (the engine-parity discipline applies to these dirs exactly as to the façades). Each holds `facts.ts`, `takes.ts`, `code-edges.ts`, and `salience.ts`: the corresponding BrainEngine method clusters implemented as free functions over a typed deps interface (e.g. `PgliteFactsDeps`) that the engine class satisfies, so each module depends only on the narrow slice it uses. The façade methods delegate to them via static top-level imports (the engine-live no-runtime-dynamic-import rule applies) and keep the full public surface.
+- `src/core/postgres-engine/` + `src/core/pglite-engine/` — narrow-deps engine module directories, mirrored in lockstep (the engine-parity discipline applies to these dirs exactly as to the façades). Each holds `facts.ts`, `takes.ts`, `code-edges.ts`, and `salience.ts`: the corresponding BrainEngine method clusters implemented as free functions over a typed deps interface (e.g. `PgliteFactsDeps`) that the engine class satisfies, so each module depends only on the narrow slice it uses. `code-edges.ts` `getCalleesOf` takes an opt-in `bareFallback` (set ONLY by the `code_callees` op + `gbrain code-callees`, never by the code_flow/code_blast BFS): a zero-row exact miss for a delimiter-free input re-keys the same UNION on `content_chunks.symbol_name` (exact, indexed, never LIKE), so the documented "bare or qualified name" contract holds for namespace/class-qualified chunks (C#/Java/Ruby/Rust, TS class methods) whose edges are emitted bare. The façade methods delegate to them via static top-level imports (the engine-live no-runtime-dynamic-import rule applies) and keep the full public surface.
- `src/core/postgres-engine/forward-reference-bootstrap.ts` — `applyPostgresForwardReferenceBootstrap(conn)`: the forward-reference bootstrap for the RAW `SCHEMA_SQL` replay path (probe + patch every column/table the embedded schema blob forward-references but older brains don't have yet — single probe round-trip, idempotent, fast no-op when nothing is missing). Peeled out of `PostgresEngine` so BOTH replay entrypoints run it before the blob: `PostgresEngine.initSchema()` AND the standalone module-singleton `db.ts:initSchema()` (replaying with no bootstrap would wedge an upgrade-boundary brain on `CREATE INDEX` over a column the replayed blob forward-references). Callers MUST hold the initSchema advisory lock (key 42) on `conn` so concurrent bootstraps can't race on a transaction pooler. Mirror of `PGLiteEngine#applyForwardReferenceBootstrap` in shape — keep in sync; covered by `test/schema-bootstrap-coverage.test.ts` (PGLite A2 static check + the Postgres-blob CREATE-INDEX class-closure gate, which parses `SCHEMA_SQL` and requires every migration-added blob-indexed column to have a probe here or an explicit exemption) + `test/e2e/postgres-bootstrap.test.ts` (Postgres side, live convergence cases). Probes are column-only (nullable `ADD COLUMN`, plus `SET DEFAULT` where hardening the upgrade window needs it — `dream_verdicts.expires_at`); the owning migration stays the source of truth for backfill/constraints/indexes: on the engine path it runs right after the bootstrap under the same advisory lock, while the standalone `db.ts:initSchema` path replays the blob WITHOUT running migrations — safe because the NULL-tolerant read predicates treat pre-backfill rows as valid until the next full engine init.
-- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `isCJKDominant(s)` (the ONE density test: CJK chars ≥ 30% of non-whitespace chars), `countCJKAwareWords(s)` (routes through `isCJKDominant` — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), and `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS + extractTrailingContext` (the overlap extractor branches on `isCJKDominant` so it counts the same unit `countWords` does), `pglite-engine.ts:searchKeyword + searchKeywordChunks`.
+- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `SLUG_WORD_CHARS` + `PAGE_SLUG_SEG` (the shared slug-grammar fragments) and `SLUG_VARIATION_SELECTORS_RE` (the Mn-invisible emoji-VS16 / ideographic-IVS strip that BOTH `sync.ts:slugifySegment` and its twin `link-extraction.ts:normalizeBasename` apply, so the two grammars cannot drift on selectors), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `isCJKDominant(s)` (the ONE density test: CJK chars ≥ 30% of non-whitespace chars), `countCJKAwareWords(s)` (routes through `isCJKDominant` — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), and `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS + extractTrailingContext` (the overlap extractor branches on `isCJKDominant` so it counts the same unit `countWords` does), `pglite-engine.ts:searchKeyword + searchKeywordChunks`.
- `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.
- `src/core/chunkers/recursive.ts` — base chunker: 300-word chunks, 50-word sentence-aware overlap, 5-level delimiter hierarchy. Applies `sanitizeRemoteBody` before splitting so only world Facts and ordinary prose enter retrieval text; all Takes and malformed protected sections are omitted. Non-overlapping portions reassemble to that sanitized input. The overlap extractor counts chars (not whitespace tokens) for CJK-dominant chunks — same unit as `countWords` — and aligns to `。!?` or a whitespace-followed ASCII `.!?`; the L4 char-slice fallback advances through `safeSplitIndex` so astral pairs (emoji, non-BMP CJK) are never halved. Both are gated on `isCJKDominant`, so English output is byte-identical (pinned by `test/chunkers/recursive-cjk-overlap.test.ts`). The markdown chunker version records the current index format.
- `src/core/chunkers/semantic.ts` — embedding-based topic-boundary detection: embeds sentences, computes cosine-similarity valleys, smooths with a Savitzky-Golay filter (5-window, 3rd-order polynomial) to find chunk boundaries. Sanitizes the full body before sentence embedding and boundary detection.
@@ -78,10 +79,10 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/embedding-pricing.ts` — `EMBEDDING_PRICING` map keyed `provider:model` for the post-upgrade reindex cost estimate. Sibling to `anthropic-pricing.ts`; EMBEDDINGS only — chat/completion pricing lives in `model-pricing.ts` (different unit) and is never mixed in. Every entry carries its official source URL + the date it was last read. Entries: OpenAI text-embedding-3-large ($0.13/1M), 3-small ($0.02/1M), ada-002 ($0.10/1M); Voyage 4-large ($0.12/1M), 4 ($0.06/1M), 4-lite ($0.02/1M), legacy 3-large ($0.18/1M), 3 ($0.06/1M); ZeroEntropy zembed-1 ($0.05/1M), zerank-2 ($0.025/1M); Mistral mistral-embed ($0.10/1M); Perplexity pplx-embed-v1-4b ($0.03/1M), 0.6b ($0.004/1M). `voyage-4-nano` is deliberately unpriced (open-weight variant, no published hosted rate) so it degrades to "estimate unavailable" rather than a fabricated 0. `lookupEmbeddingPrice(modelString)` returns a tagged union (`known` with price + `unknown` with provider name); `estimateCostFromChars(charCount, pricePerMTok)` uses 3.5 chars/token. Unknown providers degrade to "estimate unavailable" instead of fabricating numbers.
- `src/core/post-upgrade-reembed.ts` — Pure functions backing the `gbrain upgrade` chunker-bump cost prompt. `computeReembedEstimate(engine, model)` queries real SQL (`COUNT(*)` + `COALESCE(SUM(LENGTH(compiled_truth)) + SUM(LENGTH(timeline)), 0)`) on `pages WHERE chunker_version < MARKDOWN_CHUNKER_VERSION`. `formatReembedPrompt(est, graceSeconds)` is the stderr-line formatter. `runPostUpgradeReembedPrompt(engine, model, opts)` orchestrates the 10-second Ctrl-C window; TTY-only wait (non-TTY auto-proceeds for CI / cron); `GBRAIN_NO_REEMBED=1` bails with a doctor-warning marker; `GBRAIN_REEMBED_GRACE_SECONDS=0` skips the wait.
- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--dry-run] [--json] [--no-embed] [--repo PATH]`. Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`.
-- `src/commands/reindex-code.ts` — `gbrain reindex --code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks `pages WHERE type = 'code'` in 100-row batches, replays through `importCodeFile` for chunk + embed + content_hash folding. Idempotent unless `--force` bypasses the content_hash early-return. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). When `--yes` is absent and the caller is non-TTY or passed `--json`, the cost gate refuses (exit 2, no spend) via the pure exported `buildCostRefusal({json, previewMsg, preview, costUsd, model}): {stdout?, stderr?}` — JSON envelope only when `--json` is explicit, otherwise a human refusal on stderr (the spend guardrail is independent of the output format). `spend.posture=tokenmax` OR an explicit `--max-cost off`/`unlimited` makes the gate informational and proceeds; `--max-cost off` also disables the runtime BudgetTracker cap. Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE guard for the cost-preview model source), `test/reindex-cost-refusal.test.ts`.
+- `src/commands/reindex-code.ts` — `gbrain reindex-code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks `pages WHERE type = 'code'` in 100-row batches, replays through `importCodeFile` for chunk + embed + content_hash folding. Idempotent unless `--force` bypasses the content_hash early-return. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). When `--yes` is absent and the caller is non-TTY or passed `--json`, the cost gate refuses (exit 2, no spend) via the pure exported `buildCostRefusal({json, previewMsg, preview, costUsd, model}): {stdout?, stderr?}` — JSON envelope only when `--json` is explicit, otherwise a human refusal on stderr (the spend guardrail is independent of the output format). `spend.posture=tokenmax` OR an explicit `--max-cost off`/`unlimited` makes the gate informational and proceeds; `--max-cost off` also disables the runtime BudgetTracker cap. Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE guard for the cost-preview model source), `test/reindex-cost-refusal.test.ts`.
- `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/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). Confirmation gate: `--yes`, or an interactive TTY [y/N]; `--json` does NOT bypass the gate (non-TTY without `--yes` refuses with a ConfirmationRequired envelope, exit 2). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts`.
-- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). `performSyncInner` resolves the source's persisted `config.strategy` (`markdown`/`code`/`auto`) when the caller passes no `strategy` — the autopilot lane, the dream cycle, the MCP `sync` op and the single-source CLI path all omit it, and without this the walk fell back to `markdown`, importing nothing from a code source while still advancing the anchor and soft-deleting its modified code pages; an explicit `--strategy` still wins, so the `--all` fan-out is unchanged. Pinned by `test/sync-index-matches-tree.serial.test.ts` (index == working tree across first/incremental/full sync). Six pure-function clusters live in `src/core/sync-{cost-gate,git,anchor,lock,reconcile,status-report}.ts` (see the grouped entry below) and are re-exported through this façade, so the full import surface is unchanged. `performSync` runs under a writer lock: per-source `gbrain-sync:<sourceId>` whenever `opts.sourceId` is set, wrapped in `withRefreshingLock` from `src/core/db-lock.ts` so long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; the bare no-source path uses the SAME refreshing lock; `SyncOpts.lockId?: string` is the explicit override. The lock refresh AND its health probe route through the DIRECT session pool so Supavisor transaction-pool exhaustion (`EMAXCONNSESSION`) can't kill renewal; takeover is heartbeat-aware (it will NOT steal a holder whose `last_refreshed_at` is within `GBRAIN_LOCK_STEAL_GRACE_SECONDS`, defending an alive-but-starved holder); the import loop yields the event loop every `GBRAIN_SYNC_YIELD_EVERY` files (`setTimeout(0)`, not `setImmediate` — Bun starves the timers phase) so the refresh `setInterval` heartbeat fires mid-import. This lock-identity invariant prevents a `sync --all` per-source worker racing `sync --source foo` on the global lock from corrupting the same source. `performSync` throws a typed `SyncLockBusyError` when the writer lock is held; the Minion `sync` handler (`src/commands/jobs.ts`) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics. `performSyncInner` is RESUMABLE (incremental path): it drains a PINNED target commit (`lastCommit..pin`), banking drained file paths via `appendCompleted` (append-only delta into the `op_checkpoint_paths` child table, migration v115 — one row per path, O(delta) rather than an O(N²) full-array rewrite), keyed by `syncFingerprint({sourceId, lastCommit})` from `src/core/op-checkpoint.ts` (paths under `op:'sync'`; the pinned target under `op:'sync-target'`), and advances `last_commit`/`last_sync_at` ONLY at full import completion. Checkpoint writes route through the DIRECT session pool + bounded retry so they survive `EMAXCONNSESSION`; the flush cadence is first-file then every `GBRAIN_SYNC_CHECKPOINT_EVERY` (default 1000) files OR `GBRAIN_SYNC_CHECKPOINT_SECONDS` (default 10s), with a race-safe `pendingCheckpointPaths` delta (single-flight swap, re-merge on failure) under parallel workers; a SIGTERM banks the in-flight delta via a no-retry one-shot (`appendCompletedOnce`, ordered before lock release through `registerCleanup`); and sustained flush failure aborts the run with `reason:'checkpoint_unavailable'` after `GBRAIN_SYNC_MAX_CHECKPOINT_FAILURES` consecutive fails rather than importing work it can never bank (every partial/blocked exit logs the banked-file count). A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler — `last_sync_at` is never bumped on a partial), and the next run `resumeFilter`s the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff and there is no cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) decides: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and do not block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added in `lastCommit..pin` but gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only for `totalChanges <= 100`; large syncs defer to the resumable `extract --stale` watermark + `embed --stale`/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`) validated via `parseWorkers` (explicit bypasses the file-count floor; auto path defers to `autoConcurrency()`). The newest-first descending-lex order uses `sortNewestFirst(addsAndMods)` from `src/core/sort-newest-first.ts` (shared with `gbrain import`). `gbrain sync --all` runs a continuous worker pool: `parseWorkers`-validated `--parallel N` (default `min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)`), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source `withSourcePrefix(src.id, ...)` so every `slog`/`serr` line carries `[<source-id>]`; `--skip-failed`/`--retry-failed` are scoped per source (`acknowledgeFailures(sourceId)`; `--all` acks every source, single-source acks only its own) and run UNDER parallel — the failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so recovery syncs never need `--serial`; a connection-budget stderr warning fires when `parallel × workers × 2 > 16` (the `× 2 per-file pool` factor: each per-file worker opens its own `PostgresEngine` with `poolSize=2`). Exports `resolveParallelism`, `syncOneSource`, `buildSyncStatusReport`, `printSyncStatusReport`, `SyncStatusReport` back the `gbrain sources status` dashboard. `--json` envelope `{schema_version: 1, sources, parallel, ok_count, error_count, skipped_count}` on stdout; human banners route to stderr via `humanSink` so `jq` parses cleanly. Exit matrix: 0 all ok (sources skipped by `--missing-path skip` count as ok), 1 any error. `--missing-path <fail|skip>` (default fail) handles sources whose `local_path` does not exist on this machine — machine-specific state in a brain-wide table, so a brain registered from several machines fails every foreign source on every run; `skip` classifies them `skipped_missing_path` (⊘ line, envelope entry with `local_path`, excluded from `error_count` and the rc gate) via the exported pure helpers `parseMissingPathMode` + `partitionMissingPathSources`, pinned by `test/sync-all-missing-path.test.ts`; default `fail` stays loud because on a single-machine brain a missing path usually means an unmounted volume. (The non-TTY cost gate does not exit 2: a worker-backed engine can auto-defer, while a runtime without a worker surface reports a manual drain instead of claiming a queued job.) The dashboard SQL is `content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL` with `archived = false` at the caller; embedding column resolved via `resolveEmbeddingColumn(undefined, cfg)` from `src/core/search/embedding-column.ts` so Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). Every sync delete lane (removed-file drain, full-sync reconcile, un-syncable-page cleanup, rename-stale reconcile) SOFT-deletes via `engine.softDeletePages`: `deleted_at` is set for a 72h recovery window, the autopilot purge phase owns the eventual hard delete, and a re-import within the window revives the page through `putPage`'s upsert (lanes without a threaded `sourceId` fall back to `DEFAULT_SOURCE_ID`, matching `deletePage`'s `'default'` scope). The removed-file drain is interleaved per-batch resolve+soft-delete using `engine.resolveSlugsByPaths` + `engine.softDeletePages` from `src/core/engine.ts` (a 73K-delete commit takes ~292 SQL round-trips instead of ~146K, so one big-delete commit cannot jam every other source's sync); per-batch try-catch decomposes batch failures to one-element `softDeletePages` batches per slug (same primitive, per-slug isolation), unrecoverable per-slug failures land in `failedFiles` and the run continues; `pagesAffected` filters to slugs that actually transitioned (phantom slugs and already-soft-deleted rows are excluded by the primitive's `deleted_at IS NULL` predicate). The rename loop gets the same batched slug-resolve; a rename whose destination is un-syncable folds the source path into the delete set so the old page can't orphan. An entry-time bookmark-reachability guard distinguishes a gc'd anchor (`cat-file` fails → `performFullSync`) from a history-rewrite anchor that is merely no-longer-an-ancestor but still on disk: the latter is diffed tree-to-tree directly (`git diff lastCommit..pin` is an endpoint-tree compare, ancestry not required) so a force-push / `master`→`main` consolidation imports only the real delta instead of re-walking the whole tree forever; an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it soft-deletes file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists (same `softDeletePages` + 72h-window semantics as the incremental lanes; already-soft-deleted rows don't inflate the reconcile count), sparing `put_page`/manual pages (null `source_path`) and metafiles. The stale-file decision routes through the pure, exported `planReconcileDeletes(rows, currentFiles, isSyncablePath)`: it normalizes path separators on both sides of the membership test (a Windows `path.relative` backslash path vs a git-derived forward-slash `source_path` would otherwise mark every page stale and wipe the source) and computes a mass-delete signal — when the reconcile would delete more than `MASS_RECONCILE_RATIO` (50%) of the file-backed pages the strategy manages, on a source holding more than `MASS_RECONCILE_MIN_PAGES` (20) of them, the delete is REFUSED with a loud stderr warning (that shape is almost always a path-comparison bug or the wrong repo path, not a genuine bulk deletion); `GBRAIN_ALLOW_MASS_RECONCILE=1` restores the unguarded delete for genuinely intended bulk removals. Pinned by `test/sync-reconcile-mass-delete.test.ts`. Below the valve, stale pages are partitioned by git history via exported `listEverCommittedPaths(repoPath)` (one `git log --all --no-renames --diff-filter=A --name-only` pass; null on non-git dirs → unchanged behavior): a stale path that EVER existed in history was genuinely deleted → reconciled; a path with NO history is DB-only write-through (never committed/pushed, e.g. lost to a fresh clone) → the page is KEPT and its markdown re-exported to the working tree via `writePageThrough`, with a stderr hint to commit it ("absent from git" is the symptom of the missing write-through commit, not evidence the content is disposable). Pinned by `test/sync-reconcile-db-only.serial.test.ts`. `resolveSlugByPathOrSourcePath` (in `src/core/sync-git.ts` — see its dedicated entry below) delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping the legacy `executeRaw` fallback for the no-sourceId path. `failedFiles` is hoisted to the top of `performSyncInner` so both delete-decompose and import loops feed the same bookmark gate. The cost gate is the shared `runInlineCostGate` (one implementation on BOTH the `--all` and single-source paths; runs at the command layer, never inside `performSync`), mode-aware via `resolveWorkerBackedSyncEmbedMode` + posture-aware `shouldBlockSync` from `src/core/embedding.ts`. The DEFERRED path (v2 on, explicitly Postgres/worker-backed, and not `--serial`; source count controls fan-out only) is INFORMATIONAL (embedding goes to per-source `embed-backfill` jobs with their own `$X/source/24h` cap, default $25 via `SPEND_CAP_CONFIG_KEY` from `embed-backfill-submit.ts`; prints the cap + backlog + queued-job count, NEVER exits 2). The INLINE path (v2 off, `--serial`, or PGLite/unknown engine) gates on the DELTA estimate vs `sync.cost_gate_min_usd` (default $0.50): below floor proceeds; above floor in a TTY prompts `[y/N]`; above floor in a non-TTY/`--json` session auto-defers only when a worker-backed queue is actually available. Without that worker surface it exits 0 without wedging import convergence, writes no queue row, reports `manual_drain_required` with reason `no_worker_surface`, and emits one exact `gbrain embed --stale --source <id>` command per source; a worker-backed runtime with `--no-auto-embed` reports the distinct `auto_submit_disabled` policy reason without denying queue capability; intrinsic >100-file incremental deferral reaches the same final manual outcome on no-worker runtimes; `spend.posture=tokenmax` makes it informational and proceeds inline. The estimate MIRRORS EXECUTION instead of pricing the whole tree: `estimateInlineNewTokens` routes through the shared `computeSyncDelta` (`src/core/sync-delta.ts`) — fetch-first against `origin/<branch>`, prices only the committed delta (a dirty-but-caught-up tree → $0), with a full-tree CEILING only on the fail-open rungs (chunker drift, first sync, git-unavailable) honestly labeled; `--full` adds the stale backlog (full sync sweeps it inline). Return shape carries `estimateKind: 'delta'|'ceiling'|'mixed'|'unchanged'` + `ceilingReasons`. Helpers `resolveCostGateFloorUsd(engine)` + `resolveBackfillCapUsd(engine)` resolve via `parseUsdLimit` (`off`/`unlimited` → `Infinity`; floor accepts `0` = block-on-any-spend). JSON envelopes carry `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | auto_deferred_embeds | manual_drain_required | posture_tokenmax`) + a paste-ready `hint`; terminal single-source and `--all` envelopes carry per-source `embed_backfill` outcomes so machine readers see queued/manual/skipped state; `Infinity` floors/caps render as the string `'unlimited'` (never raw, which JSON-serializes to `null`); `SyncStatusReportSource` gains `backfill_queued`/`backfill_active`/`backfill_last_completed_at`; cost previews read `getEmbeddingModelName()` (no hardcoded OpenAI). Format splits on the explicit `--json` flag only (human text otherwise). `SyncOpts.noSchemaPack` (CLI `--no-schema-pack`, threaded through `performSync` AND `syncOneSource`) skips `loadActivePack` so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat `if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')` fires BEFORE `importFile` (the `progress.tick` fires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc: `docs/architecture/serve-sync-concurrency.md` (serve-delegated sync + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). On a PGLite host brain with a live `gbrain serve`, the cli.ts pre-connect hook routes `gbrain sync` through `src/commands/sync-delegate.ts` (delegation over the resolve-IPC socket; default-deny flag gate; 1s status polls; Ctrl-C → `sync_abort`; embeds always deferred to the serve's drain) — `SyncOpts.onProgress` is the seam performSync fires at phase boundaries and checkpoint flushes so the serve-side job record carries live progress; `printSyncResult` is exported for the delegated result path. Pinned by `test/e2e/sync-status-pglite.test.ts` (IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column), `test/sync-cost-gate.serial.test.ts`, `test/sync-cost-preview.test.ts`. Runaway-sync protection: `resolveSyncHardDeadline(args, {isTty, env, defaultNonTtySec?})` resolves a wall-clock hard deadline (precedence `--no-hard-deadline` > `--hard-deadline <s>` > `--timeout <s>`(non-`--all`, which auto-arms the backstop) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none; `HARD_DEADLINE_GRACE_SEC=30`). `src/cli.ts` installs the out-of-band watchdog (see `src/core/process-watchdog.ts`) for the sync command BEFORE `connectEngine` and disposes it in the dispatch `finally`, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron. `runSync` registers a SIGINT handler that aborts an interrupt `AbortController` composed via `composeAbortSignals(...)` (an `AbortSignal.any` wrapper over the defined signals) with the per-source `--timeout` signal, so Ctrl-C returns a clean `partial` and releases the lock through the normal `finally` (process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill). `withRefreshingLock` `unref()`s its refresh `setInterval`. The spin's own root cause is not yet pinned (leading lead is catastrophic-backtracking in a pack link-inference regex, bounded by the redos-guard); the watchdog heartbeat plus the existing `[gbrain phase]` breadcrumbs are the diagnosis surface. Pinned by `test/sync-hard-deadline.test.ts` (resolution precedence + `composeAbortSignals`). Monorepo subdir sources: `--src-subpath <dir>` (or a repo path that IS a subdir — auto-discovery via `discoverGitRoot`, i.e. `git rev-parse --show-toplevel`) splits the repo path into `gitContextRoot` (all git ops: pull/diff/rev-parse/cat-file) and `syncScopeRoot` (walk/import/delete/rename scope); scoped syncs use git-root-relative slugs + `source_path` (full sync threads `slugRoot` into `runImport`) so full and incremental agree; NAV-1/NAV-2 realpath containment rejects `../`-traversal and symlinked scopes resolving outside the repo BEFORE any git op, and a per-file realpath guard (`isPathSafe`) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed into `failedFiles`, so the bookmark can't advance past an escape); the full-sync reconcile is scope-restricted so a scoped sync never sweeps out-of-scope pages. `--exclude <glob>` (repeatable) filters scope-relative paths in both full and incremental paths; exclusion never deletes previously-imported pages (conservative, matching the metafile posture); an all-excluded run warns loudly (NAV-4). The persisted `sync.exclude` config key (comma- or newline-separated patterns; a trailing `/` normalizes to a `<dir>/**` subtree glob) is UNIONED with per-call `--exclude` on EVERY sync path — union, not override, so an ad-hoc flag narrows further but never silently re-opens a scope the operator persisted, and internal callers with no flag surface (autopilot, minion sync jobs, dream cycle) inherit the same indexing scope. CAVEAT: the key is BRAIN-GLOBAL — one exclude list scopes EVERY source, including `sync --all` (where the per-call flag is forbidden), so a pattern meant for repo A silently narrows repo B; per-source scoping is a filed follow-up. The union resolves at the top of `performSyncInner`, ABOVE the `performFullSync` early returns — position is load-bearing: the first sync's full walk is exactly where ignoring the persisted scope would permanently import excluded files that no later incremental revisits. Best-effort config read (an unreadable config never breaks a sync). A warn-and-continue internal `git pull` failure (non-timeout class — e.g. a local-path origin rejected by `protocol.file.allow=never`) still falls through to sync the local working tree, but a ZERO-import run after a failed pull returns `partial` with `reason: 'pull_failed'` instead of `up_to_date`: `last_commit` AND the `last_sync_at` heartbeat stay frozen (so doctor `sync_freshness` / `sources status` staleness fires), the single-source CLI exits non-zero, `sync --all` exits non-zero if any source hit it (JSON envelope carries the per-source `reason`), and the autopilot cycle's sync phase maps it to `warn`. Timeout-class partials keep their pre-existing exit-0 / phase-`ok` semantics (they converge on retry; a failing pull does not). Pinned by `test/sync-pull-failed-anchor.serial.test.ts`. `resolveSlugByPathOrSourcePath` is threaded into all 4 delete/rename call sites — see its dedicated `src/core/sync-git.ts` entry below for the resolution contract. Above the size gate (totalChanges > 100) the deferred link/timeline extraction is DURABLY QUEUED, not just hinted — the defer branch submits an `extract` Minion job `{stale: true, sourceId?, deferred_commit: pin}` keyed `extract-stale:<sourceId|default>:<pin>` (repeat submissions toward the same drained pin coalesce; deliberately NO maxWaiting — an unscoped payload's coalesce filter matches ANY waiting extract job and would silently drop the sweep), `timeout_ms` derived from extract.ts's exported `STALE_TIME_BUDGET_MS` + headroom. The returned row is verified to be a live `{stale:true}` job (waiting/delayed/active) before the log claims "queued"; a finished row occupying the key slot (a prior sweep toward the same pin that completed before this run's pages landed — the checkpoint-resume / blocked-advance re-sync case) triggers a fresh submission under a run-unique key so those pages never strand stale. Submission is best-effort (failure falls back to the hint; pages stay stale + doctor-visible, never mis-stamped). Pinned by `test/sync-deferred-extract-queue.serial.test.ts`. Unscoped default-write guard: when the resolver lands on tier `seed_default` for a single-source sync (not `--all`) and `GBRAIN_ALLOW_DEFAULT_WRITE` is unset, `assessDefaultWriteGuard` (`src/core/source-resolver.ts`) decides whether the brain's pages overwhelmingly live outside `default`; if so the run prints `formatDefaultWriteRefusal('sync', …)` and exits 1 — except under `--dry-run`, which prints the same text prefixed `[dry-run] a real run would be refused:` and still previews (a dry run writes nothing; refusing it only hides information). Escapes: `--source default` (tier `flag`), `--all`, or `GBRAIN_ALLOW_DEFAULT_WRITE=1`; a failed assessment is fail-open. Pinned by `test/sync-default-write-guard.serial.test.ts` + `test/sync-default-write-guard-dry-run.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`, streaming phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Confirmation gate: `--yes`, or an interactive TTY [y/N]; `--json` does NOT bypass the gate (non-TTY without `--yes` refuses with a ConfirmationRequired envelope, exit 2). 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/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). `performSyncInner` resolves the source's persisted `config.strategy` (`markdown`/`code`/`auto`) when the caller passes no `strategy` — the autopilot lane, the dream cycle, the MCP `sync` op and the single-source CLI path all omit it, and without this the walk fell back to `markdown`, importing nothing from a code source while still advancing the anchor and soft-deleting its modified code pages; an explicit `--strategy` still wins, so the `--all` fan-out is unchanged. Pinned by `test/sync-index-matches-tree.serial.test.ts` (index == working tree across first/incremental/full sync). Six pure-function clusters live in `src/core/sync-{cost-gate,git,anchor,lock,reconcile,status-report}.ts` (see the grouped entry below) and are re-exported through this façade, so the full import surface is unchanged. `performSync` runs under a writer lock: per-source `gbrain-sync:<sourceId>` whenever `opts.sourceId` is set, wrapped in `withRefreshingLock` from `src/core/db-lock.ts` so long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; the bare no-source path uses the SAME refreshing lock; `SyncOpts.lockId?: string` is the explicit override. The lock refresh AND its health probe route through the DIRECT session pool so Supavisor transaction-pool exhaustion (`EMAXCONNSESSION`) can't kill renewal; takeover is heartbeat-aware (it will NOT steal a holder whose `last_refreshed_at` is within `GBRAIN_LOCK_STEAL_GRACE_SECONDS`, defending an alive-but-starved holder); the import loop yields the event loop every `GBRAIN_SYNC_YIELD_EVERY` files (`setTimeout(0)`, not `setImmediate` — Bun starves the timers phase) so the refresh `setInterval` heartbeat fires mid-import. This lock-identity invariant prevents a `sync --all` per-source worker racing `sync --source foo` on the global lock from corrupting the same source. `performSync` throws a typed `SyncLockBusyError` when the writer lock is held; the Minion `sync` handler (`src/commands/jobs.ts`) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics. `performSyncInner` is RESUMABLE (incremental path): it drains a PINNED target commit (`lastCommit..pin`), banking drained file paths via `appendCompleted` (append-only delta into the `op_checkpoint_paths` child table, migration v115 — one row per path, O(delta) rather than an O(N²) full-array rewrite), keyed by `syncFingerprint({sourceId, lastCommit})` from `src/core/op-checkpoint.ts` (paths under `op:'sync'`; the pinned target under `op:'sync-target'`), and advances `last_commit`/`last_sync_at` ONLY at full import completion. Checkpoint writes route through the DIRECT session pool + bounded retry so they survive `EMAXCONNSESSION`; the flush cadence is first-file then every `GBRAIN_SYNC_CHECKPOINT_EVERY` (default 1000) files OR `GBRAIN_SYNC_CHECKPOINT_SECONDS` (default 10s), with a race-safe `pendingCheckpointPaths` delta (single-flight swap, re-merge on failure) under parallel workers; a SIGTERM banks the in-flight delta via a no-retry one-shot (`appendCompletedOnce`, ordered before lock release through `registerCleanup`); and sustained flush failure aborts the run with `reason:'checkpoint_unavailable'` after `GBRAIN_SYNC_MAX_CHECKPOINT_FAILURES` consecutive fails rather than importing work it can never bank (every partial/blocked exit logs the banked-file count). A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler — `last_sync_at` is never bumped on a partial), and the next run `resumeFilter`s the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff and there is no cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) decides: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and do not block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added in `lastCommit..pin` but gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only for `totalChanges <= 100`; large syncs defer to the resumable `extract --stale` watermark + `embed --stale`/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`) validated via `parseWorkers` (explicit bypasses the file-count floor; auto path defers to `autoConcurrency()`). The newest-first descending-lex order uses `sortNewestFirst(addsAndMods)` from `src/core/sort-newest-first.ts` (shared with `gbrain import`). `gbrain sync --all` runs a continuous worker pool: `parseWorkers`-validated `--parallel N` (default `min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)`), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source `withSourcePrefix(src.id, ...)` so every `slog`/`serr` line carries `[<source-id>]`; `--skip-failed`/`--retry-failed` are scoped per source (`acknowledgeFailures(sourceId)`; `--all` acks every source, single-source acks only its own) and run UNDER parallel — the failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so recovery syncs never need `--serial`; a connection-budget stderr warning fires when `parallel × workers × 2 > 16` (the `× 2 per-file pool` factor: each per-file worker opens its own `PostgresEngine` with `poolSize=2`). Exports `resolveParallelism`, `syncOneSource`, `buildSyncStatusReport`, `printSyncStatusReport`, `SyncStatusReport` back the `gbrain sources status` dashboard. `--json` envelope `{schema_version: 1, sources, parallel, ok_count, error_count, skipped_count}` on stdout; human banners route to stderr via `humanSink` so `jq` parses cleanly. Exit matrix: 0 all ok (sources skipped by `--missing-path skip` count as ok), 1 any error. `--missing-path <fail|skip>` (default fail) handles sources whose `local_path` does not exist on this machine — machine-specific state in a brain-wide table, so a brain registered from several machines fails every foreign source on every run; `skip` classifies them `skipped_missing_path` (⊘ line, envelope entry with `local_path`, excluded from `error_count` and the rc gate) via the exported pure helpers `parseMissingPathMode` + `partitionMissingPathSources`, pinned by `test/sync-all-missing-path.test.ts`; default `fail` stays loud because on a single-machine brain a missing path usually means an unmounted volume. (The non-TTY cost gate does not exit 2: a worker-backed engine can auto-defer, while a runtime without a worker surface reports a manual drain instead of claiming a queued job.) The dashboard SQL is `content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL` with `archived = false` at the caller; embedding column resolved via `resolveEmbeddingColumn(undefined, cfg)` from `src/core/search/embedding-column.ts` so Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). Every sync delete lane (removed-file drain, full-sync reconcile, un-syncable-page cleanup, rename-stale reconcile) SOFT-deletes via `engine.softDeletePages`: `deleted_at` is set for a 72h recovery window, the autopilot purge phase owns the eventual hard delete, the un-syncable-page sweep counts the rows it actually transitioned into `result.deleted` (a sweep-only run reports `synced`, never `up_to_date`; #4786), and a re-import within the window revives the page through `putPage`'s upsert (lanes without a threaded `sourceId` fall back to `DEFAULT_SOURCE_ID`, matching `deletePage`'s `'default'` scope). The removed-file drain is interleaved per-batch resolve+soft-delete using `engine.resolveSlugsByPaths` + `engine.softDeletePages` from `src/core/engine.ts` (a 73K-delete commit takes ~292 SQL round-trips instead of ~146K, so one big-delete commit cannot jam every other source's sync); per-batch try-catch decomposes batch failures to one-element `softDeletePages` batches per slug (same primitive, per-slug isolation), unrecoverable per-slug failures land in `failedFiles` and the run continues; `pagesAffected` filters to slugs that actually transitioned (phantom slugs and already-soft-deleted rows are excluded by the primitive's `deleted_at IS NULL` predicate). The rename loop gets the same batched slug-resolve; a rename whose destination is un-syncable folds the source path into the delete set so the old page can't orphan. An entry-time bookmark-reachability guard distinguishes a gc'd anchor (`cat-file` fails → `performFullSync`) from a history-rewrite anchor that is merely no-longer-an-ancestor but still on disk: the latter is diffed tree-to-tree directly (`git diff lastCommit..pin` is an endpoint-tree compare, ancestry not required) so a force-push / `master`→`main` consolidation imports only the real delta instead of re-walking the whole tree forever; an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it soft-deletes file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists (same `softDeletePages` + 72h-window semantics as the incremental lanes; already-soft-deleted rows don't inflate the reconcile count), sparing `put_page`/manual pages (null `source_path`) and metafiles. The stale-file decision routes through the pure, exported `planReconcileDeletes(rows, currentFiles, isSyncablePath)`: it normalizes path separators on both sides of the membership test (a Windows `path.relative` backslash path vs a git-derived forward-slash `source_path` would otherwise mark every page stale and wipe the source) and computes a mass-delete signal — when the reconcile would delete more than `MASS_RECONCILE_RATIO` (50%) of the file-backed pages the strategy manages, on a source holding more than `MASS_RECONCILE_MIN_PAGES` (20) of them, the delete is REFUSED with a loud stderr warning (that shape is almost always a path-comparison bug or the wrong repo path, not a genuine bulk deletion); `GBRAIN_ALLOW_MASS_RECONCILE=1` restores the unguarded delete for genuinely intended bulk removals. Pinned by `test/sync-reconcile-mass-delete.test.ts`. Below the valve, stale pages are partitioned by git history via exported `listEverCommittedPaths(repoPath)` (one `git log --all --no-renames --diff-filter=A --name-only` pass; null on non-git dirs → unchanged behavior): a stale path that EVER existed in history was genuinely deleted → reconciled; a path with NO history is DB-only write-through (never committed/pushed, e.g. lost to a fresh clone) → the page is KEPT and its markdown re-exported to the working tree via `writePageThrough`, with a stderr hint to commit it ("absent from git" is the symptom of the missing write-through commit, not evidence the content is disposable). Pinned by `test/sync-reconcile-db-only.serial.test.ts`. `resolveSlugByPathOrSourcePath` (in `src/core/sync-git.ts` — see its dedicated entry below) delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping the legacy `executeRaw` fallback for the no-sourceId path. `failedFiles` is hoisted to the top of `performSyncInner` so both delete-decompose and import loops feed the same bookmark gate. The cost gate is the shared `runInlineCostGate` (one implementation on BOTH the `--all` and single-source paths; runs at the command layer, never inside `performSync`), mode-aware via `resolveWorkerBackedSyncEmbedMode` + posture-aware `shouldBlockSync` from `src/core/embedding.ts`. The DEFERRED path (v2 on, explicitly Postgres/worker-backed, and not `--serial`; source count controls fan-out only) is INFORMATIONAL (embedding goes to per-source `embed-backfill` jobs with their own `$X/source/24h` cap, default $25 via `SPEND_CAP_CONFIG_KEY` from `embed-backfill-submit.ts`; prints the cap + backlog + queued-job count, NEVER exits 2). The INLINE path (v2 off, `--serial`, or PGLite/unknown engine) gates on the DELTA estimate vs `sync.cost_gate_min_usd` (default $0.50): below floor proceeds; above floor in a TTY prompts `[y/N]`; above floor in a non-TTY/`--json` session auto-defers only when a worker-backed queue is actually available. Without that worker surface it exits 0 without wedging import convergence, writes no queue row, reports `manual_drain_required` with reason `no_worker_surface`, and emits one exact `gbrain embed --stale --source <id>` command per source; a worker-backed runtime with `--no-auto-embed` reports the distinct `auto_submit_disabled` policy reason without denying queue capability; intrinsic >100-file incremental deferral reaches the same final manual outcome on no-worker runtimes; `spend.posture=tokenmax` makes it informational and proceeds inline. The estimate MIRRORS EXECUTION instead of pricing the whole tree: `estimateInlineNewTokens` routes through the shared `computeSyncDelta` (`src/core/sync-delta.ts`) — fetch-first against `origin/<branch>`, prices only the committed delta (a dirty-but-caught-up tree → $0), with a full-tree CEILING only on the fail-open rungs (chunker drift, first sync, git-unavailable) honestly labeled; `--full` adds the stale backlog (full sync sweeps it inline). Return shape carries `estimateKind: 'delta'|'ceiling'|'mixed'|'unchanged'` + `ceilingReasons`. Helpers `resolveCostGateFloorUsd(engine)` + `resolveBackfillCapUsd(engine)` resolve via `parseUsdLimit` (`off`/`unlimited` → `Infinity`; floor accepts `0` = block-on-any-spend). The gate's `--json` status object carries `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | auto_deferred_embeds | manual_drain_required | posture_tokenmax`) + a paste-ready `hint`; on every proceed path it is RETURNED (`CostGateOutcome.notice`), never printed, and nested as `cost_gate` inside the ONE terminal envelope (stop paths — dry-run, cancelled — print their object as the only document); terminal single-source and `--all` envelopes carry per-source `embed_backfill` outcomes so machine readers see queued/manual/skipped state; `Infinity` floors/caps render as the string `'unlimited'` (never raw, which JSON-serializes to `null`); `SyncStatusReportSource` gains `backfill_queued`/`backfill_active`/`backfill_last_completed_at`; cost previews read `getEmbeddingModelName()` (no hardcoded OpenAI). Format splits on the explicit `--json` flag only (human text otherwise). `SyncOpts.noSchemaPack` (CLI `--no-schema-pack`, threaded through `performSync` AND `syncOneSource`) skips `loadActivePack` so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat `if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')` fires BEFORE `importFile` (the `progress.tick` fires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc: `docs/architecture/serve-sync-concurrency.md` (serve-delegated sync + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). On a PGLite host brain with a live `gbrain serve`, the cli.ts pre-connect hook routes `gbrain sync` through `src/commands/sync-delegate.ts` (delegation over the resolve-IPC socket; default-deny flag gate; 1s status polls; Ctrl-C → `sync_abort`; embeds always deferred to the serve's drain) — `SyncOpts.onProgress` is the seam performSync fires at phase boundaries and checkpoint flushes so the serve-side job record carries live progress; `printSyncResult` is exported for the delegated result path. Pinned by `test/e2e/sync-status-pglite.test.ts` (IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column), `test/sync-cost-gate.serial.test.ts`, `test/sync-cost-preview.test.ts`. Runaway-sync protection: `resolveSyncHardDeadline(args, {isTty, env, defaultNonTtySec?})` resolves a wall-clock hard deadline (precedence `--no-hard-deadline` > `--hard-deadline <s>` > `--timeout <s>`(non-`--all`, which auto-arms the backstop) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none; `HARD_DEADLINE_GRACE_SEC=30`). `src/cli.ts` installs the out-of-band watchdog (see `src/core/process-watchdog.ts`) for the sync command BEFORE `connectEngine` and disposes it in the dispatch `finally`, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron. `runSync` registers a SIGINT handler that aborts an interrupt `AbortController` composed via `composeAbortSignals(...)` (an `AbortSignal.any` wrapper over the defined signals) with the per-source `--timeout` signal, so Ctrl-C returns a clean `partial` and releases the lock through the normal `finally` (process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill). `withRefreshingLock` `unref()`s its refresh `setInterval`. The spin's own root cause is not yet pinned (leading lead is catastrophic-backtracking in a pack link-inference regex, bounded by the redos-guard); the watchdog heartbeat plus the existing `[gbrain phase]` breadcrumbs are the diagnosis surface. Pinned by `test/sync-hard-deadline.test.ts` (resolution precedence + `composeAbortSignals`). Monorepo subdir sources: `--src-subpath <dir>` (or a repo path that IS a subdir — auto-discovery via `discoverGitRoot`, i.e. `git rev-parse --show-toplevel`) splits the repo path into `gitContextRoot` (all git ops: pull/diff/rev-parse/cat-file) and `syncScopeRoot` (walk/import/delete/rename scope); scoped syncs use git-root-relative slugs + `source_path` (full sync threads `slugRoot` into `runImport`) so full and incremental agree; NAV-1/NAV-2 realpath containment rejects `../`-traversal and symlinked scopes resolving outside the repo BEFORE any git op, and a per-file realpath guard (`isPathSafe`) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed into `failedFiles`, so the bookmark can't advance past an escape); the full-sync reconcile is scope-restricted so a scoped sync never sweeps out-of-scope pages. `--exclude <glob>` (repeatable) filters scope-relative paths in both full and incremental paths; exclusion never deletes previously-imported pages (conservative, matching the metafile posture); an all-excluded run warns loudly (NAV-4). The persisted `sync.exclude` config key (comma- or newline-separated patterns; a trailing `/` normalizes to a `<dir>/**` subtree glob) is UNIONED with per-call `--exclude` on EVERY sync path — union, not override, so an ad-hoc flag narrows further but never silently re-opens a scope the operator persisted, and internal callers with no flag surface (autopilot, minion sync jobs, dream cycle) inherit the same indexing scope. The persisted `sync.include_hidden` key is the dot-directory WAIVER's twin, read at the same spot with the same dialect and trailing-`/` normalization and unioned with per-call `--include-hidden` — the only way to express the waiver on `sync --all` (which refuses the flag), autopilot and the dream cycle; unset admits nothing, so the dot-directory default does not move. CAVEAT: both keys are BRAIN-GLOBAL — one exclude (or admit) list scopes EVERY source, including `sync --all` (where the per-call flags are forbidden), so a pattern meant for repo A silently narrows (or widens) repo B; admission is the riskier direction; per-source scoping is a filed follow-up. The union resolves at the top of `performSyncInner`, ABOVE the `performFullSync` early returns — position is load-bearing: the first sync's full walk is exactly where ignoring the persisted scope would permanently import excluded files that no later incremental revisits. Best-effort config read (an unreadable config never breaks a sync). A warn-and-continue internal `git pull` failure (non-timeout class — e.g. a local-path origin rejected by `protocol.file.allow=never`) still falls through to sync the local working tree, but a ZERO-import run after a failed pull returns `partial` with `reason: 'pull_failed'` instead of `up_to_date`: `last_commit` AND the `last_sync_at` heartbeat stay frozen (so doctor `sync_freshness` / `sources status` staleness fires), the single-source CLI exits non-zero, `sync --all` exits non-zero if any source hit it (JSON envelope carries the per-source `reason`), and the autopilot cycle's sync phase maps it to `warn`. Timeout-class partials keep their pre-existing exit-0 / phase-`ok` semantics (they converge on retry; a failing pull does not). Pinned by `test/sync-pull-failed-anchor.serial.test.ts`. `resolveSlugByPathOrSourcePath` is threaded into all 4 delete/rename call sites — see its dedicated `src/core/sync-git.ts` entry below for the resolution contract. Above the size gate (totalChanges > 100) the deferred link/timeline extraction is DURABLY QUEUED, not just hinted — the defer branch submits an `extract` Minion job `{stale: true, sourceId?, deferred_commit: pin}` keyed `extract-stale:<sourceId|default>:<pin>` (repeat submissions toward the same drained pin coalesce; deliberately NO maxWaiting — an unscoped payload's coalesce filter matches ANY waiting extract job and would silently drop the sweep), `timeout_ms` derived from extract.ts's exported `STALE_TIME_BUDGET_MS` + headroom. The returned row is verified to be a live `{stale:true}` job (waiting/delayed/active) before the log claims "queued"; a finished row occupying the key slot (a prior sweep toward the same pin that completed before this run's pages landed — the checkpoint-resume / blocked-advance re-sync case) triggers a fresh submission under a run-unique key so those pages never strand stale. Submission is best-effort (failure falls back to the hint; pages stay stale + doctor-visible, never mis-stamped). Pinned by `test/sync-deferred-extract-queue.serial.test.ts`. Unscoped default-write guard: when the resolver lands on tier `seed_default` for a single-source sync (not `--all`) and `GBRAIN_ALLOW_DEFAULT_WRITE` is unset, `assessDefaultWriteGuard` (`src/core/source-resolver.ts`) decides whether the brain's pages overwhelmingly live outside `default`; if so the run prints `formatDefaultWriteRefusal('sync', …)` and exits 1 — except under `--dry-run`, which prints the same text prefixed `[dry-run] a real run would be refused:` and still previews (a dry run writes nothing; refusing it only hides information). Escapes: `--source default` (tier `flag`), `--all`, or `GBRAIN_ALLOW_DEFAULT_WRITE=1`; a failed assessment is fail-open. Pinned by `test/sync-default-write-guard.serial.test.ts` + `test/sync-default-write-guard-dry-run.test.ts`.
- `src/core/sync-git.ts:resolveSlugByPathOrSourcePath` — Resolves a slug by `pages.source_path` first (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back to `resolveSlugForPath(path)`. Three call sites: the un-syncable cleanup (which passes `opts.sourceId`), and the bare no-`sourceId` delete and rename-source paths; when `sourceId` IS set the delete and rename loops batch through `engine.resolveSlugsByPaths` instead. The `source_path` lookup is scoped to the DEFAULT source on the bare path, matching every write that path performs (`updateSlug`, `deletePage`, the rename bookkeeping repair are all default-scoped) — an unscoped lookup could return a row from another source sharing the `source_path`, and the rename loop consumes this value directly as its cheap-move source slug. Without the helper, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (that path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path.
- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`. `assertNoOverlappingPath(engine, id, path)` is the ONE overlapping-path guard shared by every surface that binds a `local_path` (`addSource`, `gbrain sources set-path`): a path equal to, nested inside, or enclosing another source's `local_path` throws `SourceOpError('overlapping_path')` — overlapping trees make sync/write-through attribute files to the wrong source, so no add or repair path may skip it. The guard compares by spelling AND by realpath (both the candidate and each sibling `local_path` are `realpathSync`'d when they exist, fail-open to the spelling otherwise), so a symlink resolving into or over another source's tree cannot slip past it; the stored pointer and the error message keep the operator's spelling.
- `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.
@@ -89,11 +90,12 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/db.ts` — Connection management, schema initialization. `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT`/`GBRAIN_IDLE_TX_TIMEOUT`/`GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (`setSessionDefaults` kept as a back-compat no-op shim). `connect()` returns `Promise<boolean>` — `true` iff THIS call created the module singleton, `false` if it joined an existing one; the decision is atomic (no `await` between the `if (sql)` null-check and the synchronous `sql = postgres(...)` assignment), so two concurrent module connects can't both claim creation. `PostgresEngine` stores the return as its `_ownsModuleSingleton` token and only the creating engine may `db.disconnect()` the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module `sql` is only ever nulled by `db.disconnect()` (postgres.js auto-reconnects its own internal pool and never touches our reference). `disconnect()` snapshots + nulls `sql` before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through `endPoolBounded(pool)` — a gbrain-owned `Promise.race` of `pool.end({ timeout: POOL_END_TIMEOUT_SECONDS })` against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the CLI teardown contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. `connection-manager.ts` ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack. `resolveMaxLifetimeSeconds(env?)` — explicit client-pool `max_lifetime` for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; `GBRAIN_POOL_MAX_LIFETIME_S` overrides, 0 disables; warn-once on invalid). Pinned by `test/db-pool-max-lifetime.test.ts`.
- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`.
- `src/commands/migrate-engine.ts` — Bidirectional engine migration (`gbrain migrate --to supabase/pglite`). Copies the complete source catalog FIRST (`copyMigrationSources` — every `sources` row incl. archived rows and sync/routing metadata, `ON CONFLICT (id) DO UPDATE`, `default` ordered first) so every page write has a valid `pages.source_id` FK parent and the target preserves per-source behavior; pages copy afterward, tracked in the resume manifest by composite `(source_id, slug)` key. Link copy preserves each row's `to_source_id` (falling back to the origin source only for legacy rows without it), and failed-target filtering uses that same target composite key, so cross-source links migrate without being rebound to the origin source. The resume manifest is target-aware: `migrationTargetId(config)` hashes `(engine, locator)` (`database_url` for Postgres, resolved `database_path` for PGLite) and `manifestMatchesTarget` requires `schema_version === 2` plus a matching `target_id` — a legacy engine-only manifest, or one from a DIFFERENT target of the same engine kind, starts fresh instead of skipping "completed" pages the new target never received. After links, `copyMigrationFacts` carries the facts table verbatim (conversation facts have no markdown fence to re-sync from): source∩target column intersection via information_schema (older source schemas still copy), delete-and-recopy so every re-run converges to source truth, two-pass `superseded_by` restore (the self-FK points old→newer id, so id-ordered single-pass inserts would violate it), embeddings round-tripped as text into whichever physical type (`vector`/`halfvec`) the target column has with a NULL-embedding retry on per-row cast failure, and a `setval` bump so post-migration inserts don't collide with copied ids; fact-row failures block the config flip and force a non-zero exit, same contract as page failures. Takes are deliberately NOT copied (fence-canonical, keyed on target-reassigned `page_id`; the next extract cycle rebuilds them). `copyMigrationConfig` then copies EVERY DB-plane config row except the explicit engine-local denylist `MIGRATE_CONFIG_ENGINE_LOCAL_KEYS` (`engine`, `version` = target-owned schema ledger, `embedding_columns` + `search_embedding_column` = physical-column registry the copy doesn't materialize); skipped keys print in the end-of-run per-table copied-count summary, so nothing is dropped silently. Pinned by `test/migrate-engine-resume.test.ts` (manifest identity) + `test/e2e/migrate-engine-sources-postgres.test.ts` (source catalog lands before overlapping-slug pages, PGLite → real Postgres) + `test/e2e/multi-source-bug-class.test.ts` (cross-source links) + `test/migrate-engine-completeness.serial.test.ts` (facts chains/embeddings/sequence, config copy-all + denylist, summary).
-- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent`'s tag reconciliation is ADD-ONLY: it only `addTag` (idempotent, ON CONFLICT DO NOTHING). The `tags` table has no provenance column and frontmatter tags are stripped from stored `pages.frontmatter` (markdown.ts:118), so a frontmatter-origin tag can't be distinguished from a DB-enrichment tag (auto-tag / dream synthesize / signal-detector) at re-import — deletion is unsafe (would wipe enrichment under `gbrain reindex --markdown`). Accepted trade-off: removing a tag from frontmatter does not remove it from the DB on next sync (needs a `tag_source` provenance column). Pinned by `test/reindex-preserve-tags.test.ts` + `test/import-file.test.ts`. identity-based dedup pre-check at `:427-490`. Calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId})` (optional `?` so test doubles compile). Posture: SKIP when `frontmatter.id` matches (true external duplicate from overlapping ingest roots), WARN-ALWAYS on content_hash collision with different/missing `frontmatter.id` (templates and daily logs may legitimately share text), FAIL CLOSED on lookup error, bypass via `--force-rechunk`. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Pinned by `test/import-dedup-frontmatter-id.test.ts` (11 cases). `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes, `sync --force`, or `gbrain reindex-code --force`.
+- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex-code --force` / `embed --stale` handle those). `importFromContent`'s tag reconciliation is ADD-ONLY: it only `addTag` (idempotent, ON CONFLICT DO NOTHING). The `tags` table has no provenance column and frontmatter tags are stripped from stored `pages.frontmatter` (markdown.ts:118), so a frontmatter-origin tag can't be distinguished from a DB-enrichment tag (auto-tag / dream synthesize / signal-detector) at re-import — deletion is unsafe (would wipe enrichment under `gbrain reindex --markdown`). Accepted trade-off: removing a tag from frontmatter does not remove it from the DB on next sync (needs a `tag_source` provenance column). Pinned by `test/reindex-preserve-tags.test.ts` + `test/import-file.test.ts`. identity-based dedup pre-check at `:427-490`. Calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId})` (optional `?` so test doubles compile). Posture: SKIP when `frontmatter.id` matches (true external duplicate from overlapping ingest roots), WARN-ALWAYS on content_hash collision with different/missing `frontmatter.id` (templates and daily logs may legitimately share text), FAIL CLOSED on lookup error, bypass via `--force-rechunk`. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Pinned by `test/import-dedup-frontmatter-id.test.ts` (11 cases). `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes or `gbrain reindex-code --force`.
- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the four canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The `commands/sync.ts` cleanup loop guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.serial.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`.
- `src/core/sync-failure-ledger.ts` — the bounded auto-skip sync failure ledger. A LEAF module (imports only fs/path/crypto/config) so `sync.ts` can re-export it without a circular dependency. State lives in `~/.gbrain/sync-failures.jsonl`, one JSON object per line, keyed by `(source_id, path)` with a per-key `attempts` count and a 3-state machine: `open` (fresh/blocking) → `auto_skipped` (chronic, still doctor-visible) or `acknowledged` (human resolved via `gbrain sync --skip-failed` from either unresolved state). `classifyErrorCode(errorMsg)` regex classifier with 23 named codes (`RENAME_RECONCILE`, `SLUG_MISMATCH`, `DB_DUPLICATE_KEY`, `STATEMENT_TIMEOUT`, `YAML_PARSE`, `YAML_DUPLICATE_KEY`, `MISSING_OPEN`, `MISSING_CLOSE`, `EMPTY_FRONTMATTER`, `NULL_BYTES`, `NESTED_QUOTES`, `INVALID_UTF8`, `FILE_TOO_LARGE`, `SYMLINK_NOT_ALLOWED`, `TAKES_TABLE_MALFORMED`, `TAKES_HOLDER_INVALID`, `EMBEDDING_NO_CREDS`, `EMBEDDING_NO_TOUCHPOINT`, `EMBEDDING_TIMEOUT`, `EMBEDDING_RATE_LIMIT`, `EMBEDDING_QUOTA`, `EMBEDDING_OVERSIZE`, `PAGE_JUNK_PATTERN`) plus `UNKNOWN` (the default fallthrough); `summarizeFailuresByCode(failures)` returns sorted `[{code, count}]`; `MISSING_OPEN`/`EMPTY_FRONTMATTER` regexes match the `markdown.ts` validator strings; `MISSING_CLOSE`'s regex is stale against current `markdown.ts` output — it matches the no-heading-hint case (`No closing --- delimiter found`) but not the heading-hint case (`No closing --- before heading at line N`), which falls through to `UNKNOWN`. `FILE_TOO_LARGE` covers `import-file.ts:395, 1236, 1436` (markdown/text, plain-file, and code-file import paths), `SYMLINK_NOT_ALLOWED` covers `:1231, 2038` (file and image import paths). `EMBEDDING_INFRA_CODES` is the subset (`EMBEDDING_TIMEOUT`/`EMBEDDING_RATE_LIMIT`/`EMBEDDING_QUOTA`) that means the embedding PROVIDER is unhealthy rather than the file being poison — `isEmbeddingInfraCode(code)` is consulted inside `decideGateAction`'s chronic-eligibility loop so these three are never counted toward auto-skip (treated as fresh, forcing `block` instead of `advance_then_autoskip`); an explicit `--skip-failed` still advances past them like any other failure, since that check runs before the loop. All mutations run under `withLedgerLock` (cross-process file lock) with an atomic rename write. The auto-skip threshold resolves via `resolveAutoSkipThreshold()` from `GBRAIN_SYNC_AUTOSKIP_AFTER` (default `DEFAULT_AUTOSKIP_AFTER = 3`; `0` disables the valve = pure fail-closed). Two pure decision functions are the unit-test surface: `decideGateAction({fileFailures, sentinels, attemptsByPath, threshold, skipFailed})` returns `hard_block | block | advance | advance_then_autoskip` (sentinels like `<head>` ALWAYS hard-block, even with `--skip-failed`, so a history rewrite can't auto-skip; any FRESH failure with `attempts < threshold` blocks fail-closed; only when ALL failures are chronic does it `advance_then_autoskip`), and `decideSyncFailureSeverity({entries, nowMs, failHours})` returns the `sync_failures` doctor status (`ok` when zero unresolved; `fail` when ≥10 OPEN-blocking or the oldest OPEN failure's `ts` (last attempt, NOT `first_seen`) is older than `failHours` — a failure retried inside that window keeps refreshing `ts` and never trips this leg even if `first_seen` is much older; otherwise `warn` — `auto_skipped`-only rows stay WARN-visible regardless of count because the bookmark already advanced). `applySyncFailureGate(input)` is the one orchestrator BOTH sync paths (incremental + full/`runImport`) call: it records/clears ledger rows, runs `decideGateAction`, then executes effects in the crash-safe order (advance the bookmark FIRST via the injected `advance()` callback, THEN auto-skip the chronic set) so a crash can never mark a file skipped while leaving sync wedged. `isSkippablePath` rejects `<…>` sentinels. Pinned by `test/sync-failure-ledger.serial.test.ts` + `test/sync-failures.test.ts`.
- `src/core/sync-cost-gate.ts` + `sync-git.ts` + `sync-anchor.ts` + `sync-lock.ts` + `sync-reconcile.ts` + `sync-status-report.ts` — six pure-function clusters behind the `src/commands/sync.ts` façade, which re-exports them; `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps exactly these six (NOT the other `sync-*` siblings, which are ordinary deps) on the sync command's flag-scan surface. `sync-cost-gate.ts`: the inline-embed cost gate + token estimation for `gbrain sync`. `sync-git.ts`: git plumbing — invocation building, repo discovery, baseline-commit self-heal, path-containment guards, and the delete/rename slug resolvers (`resolveSlugByPathOrSourcePath` — see its dedicated entry above — plus the verified `resolveSlugsForRemovedPaths`/`resolveRemovedPathSlug`). `sync-anchor.ts`: sync anchor + chunker-version state helpers (source-scoped vs legacy global-config storage). `sync-lock.ts`: the lock layer — typed lock-busy error, the rich busy message, `--break-lock` handling, the partial-result envelope (`performSync` itself stays in the façade). `sync-reconcile.ts`: full-sync reconcile planning (the mass-delete valve and ever-committed gate) + sync deadline/stall resolution. `sync-status-report.ts`: the per-source sync status report backing `gbrain sources status` and the `get_status_snapshot` op. Its queue context is engine-aware: only an explicitly worker-backed surface may promise job deferral; otherwise non-interactive cost deferral returns `manual_drain_required` with exact per-source `gbrain embed --stale --source <id>` commands and never writes or claims an embed-backfill row.
-- `src/core/sync-embed-backfill.ts` — Sync command’s engine-aware embedding-delivery seam. It derives separate worker-backed deferral and multi-source fan-out eligibility, keeps automatic-submission policy distinct from capability, invokes the shared cost gate for `--all` and single-source runs, propagates intrinsic large-sync deferral into final delivery outcomes, resolves backfill results through the centralized submitter, formats one truthful human status, and builds the single-source JSON envelope. Keeping these pieces together prevents cost-gate, queue, human, and machine surfaces from drifting while the size-ratcheted `src/commands/sync.ts` façade stays at its committed ceiling.
+- `src/core/sync-policy.ts` — `isSyncDisabledConfig(config)`: the one predicate for `config.syncEnabled === false` ("excluded from AUTOMATIC/bulk sync"), unwrapping PGLite's JSON-string config scalar via `parseSourceConfig`. Read by the `sync --all` fan-out filter (`src/commands/sync.ts`), autopilot's per-source freshness dispatcher (`src/commands/autopilot.ts`, skip before `queue.add('sync')`) and the full-cycle fan-out (`src/commands/autopilot-fanout.ts`, which drops the `sync` phase + pull from a disabled source's `autopilot-cycle` payload but keeps lint/backlinks/extract and the freshness stamp) and the `sync_enabled` column of `buildSyncStatusReport` (`src/core/sync-status-report.ts`, whose callers pass RAW `SELECT config` rows — a JSON string on PGLite — so a raw cast there contradicted the fan-out filter). Deliberately does NOT gate `performSync()`: an explicit `gbrain sync --source <id>` still runs; `sync-cost-gate.ts` keeps its own inline check because it also feeds the explicit single-source cost preview. Pinned by `test/sync-policy.test.ts`, the `#4399` cases in `test/autopilot-fanout-wiring.test.ts` (source-text) and `test/autopilot-fanout.test.ts` (stubbed dispatch).
+- `src/core/sync-embed-backfill.ts` — Sync command’s engine-aware embedding-delivery seam. It derives separate worker-backed deferral and multi-source fan-out eligibility, keeps automatic-submission policy distinct from capability, invokes the shared cost gate for `--all` and single-source runs, propagates intrinsic large-sync deferral into final delivery outcomes, resolves backfill results through the centralized submitter, formats one truthful human status, and builds the single-source JSON envelope. `syncProducedEmbeddableContent` is the one content gate every automatic submit site (`sync --all`, single-source autodefer, the jobs `sync` handler) applies on top of status: a sweep-only or delete-only run reports `synced` but wrote no chunks, and minting a backfill for it would only arm the per-source cooldown against the next real import (the handler reports `embed_skip_reason: 'no_new_content'`). Keeping these pieces together prevents cost-gate, queue, human, and machine surfaces from drifting while the size-ratcheted `src/commands/sync.ts` façade stays at its committed ceiling.
- `src/core/storage.ts` — Pluggable storage interface (S3, Supabase Storage, local).
- `src/core/storage-config.ts` — Storage tiering: `loadStorageConfig` reads `gbrain.yml`, normalizes deprecated keys (`git_tracked`/`supabase_only`) to canonical (`db_tracked`/`db_only`) with once-per-process deprecation warning, and runs `normalizeAndValidateStorageConfig` (auto-fixes missing trailing `/`, throws `StorageConfigError` on tier overlap). Path-segment matcher: `media/x/` does NOT match `media/xerox/foo`. Uses a dedicated parser for the `gbrain.yml` shape rather than gray-matter (broken on delimiter-less YAML). Also carries `DERIVE_PHASE_DB_ONLY_DEFAULTS` (`life/events/`, `atoms/`, `extracts/`, `dream-cycle-summaries/`) + `effectiveDbOnlyDirs` — the engine's derive-phase output prefixes treated as implicitly-declared db_only by the `undeclared_db_only_pages` doctor check but deliberately NOT merged into `loadStorageConfig` (a global merge would auto-gitignore those dirs and silently kill ingestion for brains that file-back them) — and `findDbOnlyCollisions` (pure collector-output vs db_only overlap detector shared by the `db_only_collector_collision` doctor check and sync's `manageGitignore` warning). Pinned by `test/storage-config.test.ts` + `test/doctor-silent-death-checks.test.ts`.
- `src/core/disk-walk.ts` — `walkBrainRepo(repoPath)` returns `Map<slug, {size, mtimeMs}>` from one recursive `readdirSync`. Skips dot-dirs, `node_modules`, non-`.md` files. Used by `gbrain storage status` instead of per-page `existsSync + statSync` (~400K syscalls on 200K-page brains → tens).
@@ -102,7 +104,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/source-health.ts` — per-source health metrics for `gbrain sources status` + doctor's `federation_health`. Commit-relative staleness: `newestCommitMs(localPath)` = HEAD committer time via `git log -1 --format=%ct` (fail-open null; NO working-tree mtime parsing — committed content only, robust against the porcelain-mtime bug farm); `lagFromContentMs(contentMs|null, lastSyncMs|null, nowMs, ceilingSeconds?)` = remote/column comparator (null lastSync → null; negative wall-clock → skew passthrough; `contentMs <= lastSync` → **`max(0, wallClock - ceiling)`**; else/null-content → wall-clock). Core logic is pure; only the DEFAULT `ceilingSeconds` reads env, via `resolveStalenessCeilingSeconds()` (`GBRAIN_STALENESS_CEILING_HOURS` overriding `GBRAIN_SYNC_FRESHNESS_FAIL_HOURS`, default 72) — pass the 4th arg for determinism. The caught-up branch RAMPS rather than returning a flat 0: a flat 0 meant a source whose clone vanished reported fresh forever (the dead-daemon class), while a hard step to the ceiling would trip `federation_health` (24h) and `sync_freshness` (24h/72h) in the same instant and skip the warn tier — the alert-storm shape the caught-up branch exists to prevent. Ramping keeps the escalation ordered. `computeAllSourceMetrics(engine, sources, {probeContent?})`: LOCAL (`probeContent:true`, `gbrain sources status`) → `isSourceUnchangedSinceSync(..., {requireCleanWorkingTree:'ignore-untracked'}) ? 0 : wall-clock` (live commit-hash catches HEAD moving to an old-dated commit a timestamp compare would miss); REMOTE (default, `federation_health` on the HTTP MCP path) → `lagFromContentMs(row.newest_content_at, ...)`, NO git subprocess (trust boundary). `commitTimeMs(localPath, sha)` is the `newestCommitMs` sibling pinned to an arbitrary commit (committer time via `git show -s --format=%ct <sha>`, fail-open null, execFileSync array args) — the resumable sync stamps `newest_content_at` against its pinned target commit, not whatever HEAD raced to. Pinned by `test/source-health.test.ts`.
- `src/core/npm-squat-check.ts` — classifies `gbrain` PATH entries as real, foreign npm package, broken, or unknown for doctor's `npm_squat` check. On Windows it normalizes Git Bash/MSYS drive paths (`/c/...` → `C:/...`) and tries the native `.exe` suffix before reporting a broken entry; non-Windows classification keeps the original single-candidate behavior. Pinned by `test/npm-squat-check.test.ts`.
- `src/core/git-remote.ts` — SSRF-hardened git invocations for remote-source `cloneRepo`, `pullRepo`, and `fetchRemote(repoPath, branch)` (the last used by the sync cost-estimator's fetch-first path, so a cost preview / dry-run fetches through the same hardened flags + `GIT_TERMINAL_PROMPT=0` as real sync rather than a less-protected route). Exports two distinct flag constants because `git`'s argv grammar treats them differently: `GIT_SSRF_FLAGS` (3 `-c` config flags — `http.followRedirects=false`, `protocol.file.allow=never`, `protocol.ext.allow=never`) is global config, spread BEFORE the subcommand verb; `GIT_SSRF_SUBCOMMAND_FLAGS = ['--no-recurse-submodules']` is subcommand-scoped, spread AFTER the verb (a combined array would spread `--no-recurse-submodules` before the verb where real git rejects it exit 129). `cloneRepo` argv: `git <GIT_SSRF_FLAGS> clone <GIT_SSRF_SUBCOMMAND_FLAGS> --depth=1 [--branch X] <url> <dir>`. `pullRepo` argv: `git -C <dir> <durableSsrfFlags()> pull <GIT_SSRF_SUBCOMMAND_FLAGS> --ff-only` — `durableSsrfFlags()`, not the hardcoded `GIT_SSRF_FLAGS`: identical `-c` flags except `protocol.file.allow` honors the `GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1` escape hatch. `fetchRemote` uses the same helper. Pinned by `test/git-remote.test.ts` position-anchored guard (`argv.indexOf('--no-recurse-submodules') > argv.indexOf(verb)`). Also exports the durability-side helpers that power `gbrain sources harden/pull`: `GIT_ENV_AUTH` (the no-prompt env minus the askpass `/bin/false` overrides, so an auth'd push/fetch can consult the repo's configured credential helper while `GIT_TERMINAL_PROMPT=0` still fails fast on a missing credential), `divergenceSafePull(repoPath, branch)` (fetch + `pull --rebase`; returns `skipped_dirty` on a dirty tree, `conflict_aborted` on ANY `pull --rebase` failure (the catch doesn't classify the cause — it's treated as a conflict) after up to two best-effort `rebase --abort` attempts (each swallows its own failure; `conflict_aborted` is still returned even if rebase state remains), else `up_to_date`/`advanced`), `detectDefaultBranch` (origin/HEAD → current branch → `main`), `pushProbe(repoPath, branch)` (authenticated `push --dry-run` that proves push access and classifies `auth`/`protected`/`unreachable`), and `isWorkingTreeDirty`. These auth'd paths route their `protocol.file.allow` through `GBRAIN_GIT_ALLOW_FILE_TRANSPORT` (default `never`; set `=1` for self-hosted filesystem remotes), unlike `cloneRepo`, which still uses the hardcoded `GIT_SSRF_FLAGS` and stays strict.
-- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a confirmed push and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`. `GBRAIN_PUSH_LOCK_WAIT_SECONDS` (default 30, env-only) tunes the `flock -w` wait in the rendered push-retry block that both the committed helper and the local hook share; on lock timeout the synchronous helper returns rc 1 (fail-loud, no push was attempted) while the detached post-commit hook returns rc 0 (another holder is already pushing — the designed coalescing outcome).
+- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a confirmed push and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. `isDurabilityHardened(repoPath)` (the durability hook banner is installed) and `commitWriteThroughFile(repoPath, absPath, slug, action = 'write-through')` are the shared helpers every write-through sink (page write/delete, facts fence, timeline, lint --fix) uses to best-effort commit ONE file path-limited on a hardened repo — never throws, false on any failure; `action` only labels the subject (`gbrain: <action> <slug>`; `'delete write-through'` for removals). Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`. `GBRAIN_PUSH_LOCK_WAIT_SECONDS` (default 30, env-only) tunes the `flock -w` wait in the rendered push-retry block that both the committed helper and the local hook share; on lock timeout the synchronous helper returns rc 1 (fail-loud, no push was attempted) while the detached post-commit hook returns rc 0 (another holder is already pushing — the designed coalescing outcome).
- `src/commands/storage.ts` — `gbrain storage status [--repo P] [--json]`. Split into pure data (`getStorageStatus`) + JSON formatter + human formatter (ASCII-only) matching the `orphans.ts` pattern. `PageCountsByTier` and `DiskUsageByTier` are distinct nominal types so swaps fail at compile time.
- `gbrain.yml` (brain repo root) — Optional storage tiering config. Top-level `storage:` section with `db_tracked:` and `db_only:` array-valued keys. `gbrain sync` auto-manages `.gitignore` for `db_only` paths on successful sync (skips on dry-run, blocked-by-failures, submodule context, or `GBRAIN_NO_GITIGNORE=1`). `gbrain export --restore-only [--repo P] [--type T] [--slug-prefix S]` repopulates missing `db_only` files from the database.
- `src/core/supabase-admin.ts` — Supabase Management-API client (`listProjects`, `discoverPoolerUrl`, `extractProjectRef` — refs are lowercase ALPHANUMERIC, `[a-z0-9]+`). Consumed by the `init --prefer-postgres` ladder's rung 2 (DISCOVERY only — project creation stays dashboard guidance; discovered URLs are candidates, connect-probed before persisting) and by the classifier's Supabase hints. The access token is never persisted, logged, or written to receipts/config.
@@ -185,27 +187,27 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/embedding-input-limit.ts` — per-model embedding INPUT token caps. Some hosted encoders reject any single input over a hard per-input limit far below their batch budget (a 512-token model would otherwise leave ~35% of a typical vault's chunks permanently unembeddable, re-failing every sweep). `resolveMaxChunkTokens(env?)` resolves the effective chunk-token cap for the ACTIVE embedding model so the chunkers SPLIT (never truncate) at a size the model accepts: `GBRAIN_MAX_CHUNK_TOKENS` env (escape hatch for models not in a recipe; warn-once per distinct invalid value) → recipe per-model `max_input_tokens` × `EMBED_INPUT_SAFETY` (0.6 — covers the cl100k-based `estimateEmbedTokens` overestimate vs BERT-wordpiece tokenizer mismatch) → `DEFAULT_MAX_CHUNK_TOKENS` (2000 for every other provider). `MIN_CHUNK_TOKENS` floor of 64 so a tiny declared limit can't produce confetti chunks; fail-open on any resolver error (a resolver bug must never change chunking for unaffected installs). `maxInputTokensForModel(recipe, modelId)` mirrors `model_dims`' case-fold lookup rule (exact match first, then case-insensitive scan). Consumed at `import-file.ts`'s chunk step. Pinned by `test/embedding-input-limit.test.ts`.
- `src/core/embed-oversize-heal.ts` — heals ALREADY-STORED chunks that exceed the active embedding model's per-input token cap (new imports respect `resolveMaxChunkTokens()`, but `--stale` re-embeds existing `chunk_text` rows chunked under looser caps, which fail every sweep forever). `healOversizedChunks` splits oversized rows in place (never truncates; char-based hard split as the pathological fallback), re-indexes contiguously, carries each piece's modality/code-symbol metadata, and leaves embeddings unset so `upsertChunks` preserves vectors for unchanged `(chunk_index, chunk_text)` pairs and NULLs the split/shifted ones; `healOversizedPageChunks` is the load-split-upsert-reload wrapper. `healedChunksToStaleRows(chunks, slug, sourceId)` remaps a post-heal chunk list back into the stale-row shape — the shared seam between `src/commands/embed.ts:embedAllStale` and `src/core/embed-stale.ts:embedStaleForSource` so the two drains cannot drift; `chunk_source` passes through UNCHANGED (coercing `fenced_code` to `compiled_truth` would make `wrapChunkTextsForStoredMode` prefix code chunks, violating the D20-T4 never-wrap convention). Pinned by `test/embed-oversize-heal.test.ts`.
- `src/core/stall-env.ts` — shared env resolver for the stall-watchdog knobs (`resolveStallAbortSecondsFromEnv(envVar, defaultSec)`): one parameterized implementation behind BOTH `GBRAIN_SYNC_STALL_ABORT_SECONDS` and `GBRAIN_EMBED_STALL_ABORT_SECONDS` so the two surfaces' semantics cannot drift — unset/empty/garbage → the caller's default; any finite number returned as-is (`<= 0` disables the watchdog). Deliberately a leaf module (neither the sync nor the embed cluster imports the other's machinery just to parse an env var); env-only incident knobs by design, no config-dashboard surface.
-- `src/core/embed-stall.ts` — progress-keyed stall watchdog for embed drains (mirror of sync's stall watchdog; bounds embed drains that hang without a pinned root cause). Two clocks, one trigger: LIVENESS ticks via `noteEmbedApiResponse()` on EVERY settled embed API attempt — success, error, or retry (hooked in `embed-retry.ts:embedBatchWithBackoff`; diagnostic only, distinguishes "fully wedged" from "live but failing" in the abort message, scoped to the armed run); the TRIGGER is no SUCCESSFUL forward progress (`readProgress()`, wired to chunks embedded) for `GBRAIN_EMBED_STALL_ABORT_SECONDS` (env-only knob; default 900 via `DEFAULT_EMBED_STALL_ABORT_SEC`, `<= 0` disables, garbage falls back to default) — a retry storm that never lands a chunk trips it BY DESIGN. A stall produces an ERROR RESULT (`reason: 'stall_timeout'`), never a `process.exit`: only the CLI wrapper (`src/commands/embed.ts:runEmbed`) maps it to a non-zero exit, and minion handlers convert it to a failed job via `assertEmbedNotStalled`. The abort path runs an idempotent, deadline-bounded cleanup (`EMBED_STALL_CLEANUP_DEADLINE_MS`) that releases only the run's self-acquired single-flight locks and banks partial progress, so the next run resumes cleanly. The check interval is deliberately NOT unref'd — for non-single-flight callers it can be the only handle keeping a lost-promise hang loud; `stop()` clears it on every normal path. Pinned by `test/embed-stall.test.ts`.
+- `src/core/embed-stall.ts` — progress-keyed stall watchdog for embed drains (mirror of sync's stall watchdog; bounds embed drains that hang without a pinned root cause). Two clocks, one trigger: LIVENESS ticks via `noteEmbedApiResponse()` on EVERY settled embed API attempt — success, error, or retry (hooked in `embed-retry.ts:embedBatchWithBackoff`; diagnostic only, distinguishes "fully wedged" from "live but failing" in the abort message, scoped to the armed run); the TRIGGER is no SUCCESSFUL forward progress (`readProgress()`, wired to chunks embedded) for `GBRAIN_EMBED_STALL_ABORT_SECONDS` (env-only knob; default 900 via `DEFAULT_EMBED_STALL_ABORT_SEC`, `<= 0` disables, garbage falls back to default) — a retry storm that never lands a chunk trips it BY DESIGN. A stall produces an ERROR RESULT (`reason: 'stall_timeout'`), never a `process.exit`: only the CLI wrapper (`src/commands/embed.ts:runEmbed`) maps it to a non-zero exit, and minion handlers and the cycle's embed phase (`cycle.ts:runPhaseEmbed`) convert it to a failure via `assertEmbedNotStalled`. The abort path runs an idempotent, deadline-bounded cleanup (`EMBED_STALL_CLEANUP_DEADLINE_MS`) that releases only the run's self-acquired single-flight locks and banks partial progress, so the next run resumes cleanly. The check interval is deliberately NOT unref'd — for non-single-flight callers it can be the only handle keeping a lost-promise hang loud; `stop()` clears it on every normal path. Pinned by `test/embed-stall.test.ts`.
- `src/core/sync-delta.ts` — the single "what changed since last_commit" helper, consumed by BOTH `performSyncInner` (sync executor) and `estimateInlineNewTokens` (cost estimator) so the gate's dollar figure can't drift from what the sync imports. `computeSyncDelta(repoPath, fromCommit, toCommit, {detachedManifest?, detached?})` → `{status:'ok', manifest}` | `{status:'unavailable', reason:'anchor_missing'|'diff_failed'}`. Anchor reachability via `git cat-file -t` (a gc'd bookmark is `anchor_missing`, but a present-but-non-ancestor bookmark is still diffed tree-to-tree), then `git diff --name-status -M from..to` parsed by `buildSyncManifest`; merges the detached working-tree manifest when detached (`buildDetachedWorkingTreeManifest`). NO dirty/untracked probe in the estimator — pricing dirty files would create phantom costs on a busy brain. The executor imports only the commit diff on attached HEADs BY DEFAULT, but counts uncommitted working-tree files (untracked + dirty) as `SyncResult.uncommitted` drift and, with `--working-tree` / config `sync.include_working_tree`, merges the working-tree manifest into the delta so attached repos can import uncommitted state (the estimator does not price that opt-in). `execFileSync` array-args (shell-injection safe), 30s / 100 MiB budget. Test seam `_setGitRunnerForTests`. Pinned by `test/sync-delta.test.ts`.
- `src/core/spend-posture.ts` — spend-control surface. `resolveSpendPosture(engine): 'gated'|'tokenmax'` (DB-plane `spend.posture`, fail-open `gated`); `tokenmax` makes every cost gate informational across sync/reindex/enrich/onboard (spend still ledgered — removes the ceiling, not the accounting). `parseUsdLimit(raw, def, {allowZero?})` accepts `off`/`unlimited`/`none` → `Infinity`; `formatUsdLimit(n)` renders `Infinity` as the string `'unlimited'` (never raw — `JSON.stringify(Infinity)` is `null`); `usdLimitToCap(n)` maps `Infinity` → `undefined` at the BudgetTracker boundary so ledger rows never serialize null. `normalizeSpendPosture`/`isValidSpendPosture` back the `config set` validation. Doc: `docs/operations/spend-controls.md`. Pinned by `test/sync-cost-preview.test.ts` + `test/spend-off-switch.test.ts`.
- `src/core/ai/dims.ts` — per-provider `providerOptions` resolver for embed-time dimension passthrough; the single source of truth for "which provider needs which knob to produce `vector(N)`". Exports `dimsProviderOptions(implementation, modelId, dims)` (called by `embed()` in `gateway.ts`), `VOYAGE_OUTPUT_DIMENSION_MODELS` (private const — the 7 hosted Voyage models that accept `output_dimension`: `voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3` — nano deliberately excluded), `VOYAGE_VALID_OUTPUT_DIMS = [256, 512, 1024, 2048] as const`, `supportsVoyageOutputDimension(modelId)`, `isValidVoyageOutputDim(dims)`. Voyage path uses the SDK-supported `dimensions` field (`{ openaiCompatible: { dimensions: N } }`), NOT Voyage's `output_dimension` wire-key — the `voyageCompatFetch` shim in `gateway.ts:541` translates `dimensions → output_dimension` before the HTTP body is built (the AI SDK's openai-compatible adapter doesn't recognize the wire-key, so sending it from here would be silently dropped and Voyage would return its default 1024-dim). Runtime guard: when a Voyage flexible-dim model is configured with `dims` outside `VOYAGE_VALID_OUTPUT_DIMS`, throws `AIConfigError` with a paste-ready `gbrain config set embedding_dimensions <256|512|1024|2048>` hint at the embed boundary (most common trigger: `embedding_model: voyage:voyage-4-large` without `embedding_dimensions`, falling back to `DEFAULT_EMBEDDING_DIMENSIONS=1536`, an OpenAI default not a Voyage one). Every lookup in this module folds through the private `modelMatchKey` (trim + lowercase) so cased hub-form ids (`Qwen/Qwen3-Embedding-4B`) match the all-lowercase tables — the folded key is a MATCH key only, never sent to a provider (wire model ids are case-sensitive; error messages keep the original id so they stay paste-ready); the Qwen3-Embedding native-width table lives at module scope alongside the other dim tables. Consequence, deliberate: a cased Voyage/ZeroEntropy/Perplexity config matches and fails loudly at init when its `dims` is invalid, rather than skipping validation and silently producing wrong-width vectors.
- `src/core/ai/types.ts` — provider/recipe types. `EmbeddingTouchpoint` has optional `chars_per_token` (default 4, matching OpenAI tiktoken on English) and `safety_factor` (default 0.8, budget-utilization ceiling), both consulted only when `max_batch_tokens` is also set; Voyage declares `chars_per_token=1` + `safety_factor=0.5` to handle dense payloads (CJK/JSON/base64). Pre-split budget = `max_batch_tokens × safety_factor / chars_per_token`. `EmbeddingTouchpoint.multimodal_models?: string[]` model-level allow-list for recipes mixing text-only + multimodal models under one touchpoint (Voyage's 12 models share `supports_multimodal: true` but only `voyage-multimodal-3` accepts `/multimodalembeddings`); when omitted, recipe-level `supports_multimodal` is sufficient. `AIGatewayConfig.embedding_multimodal_model?: string` lets `embedMultimodal()` route to a different model than `embedding_model` (OpenAI text + Voyage images without flipping the primary pipeline). `AIGatewayConfig.embedding_image_ocr_model?: string` is its OCR sibling: `generateOcrText()` routes to it instead of the expansion model; a direct `provider:model` string, never `models.tier`-resolved. `EmbeddingTouchpoint.trust_custom_dims?: true` — passthrough tier for a user-declared `--embedding-dimensions` on local / bring-your-own-backend recipes (ollama, llama-server, litellm) where the model catalog can't be enumerated; consumed by `isCustomDimValidForProvider` in `src/core/embedding-dim-check.ts` AFTER Tier 1 (recipe `dims_options`) and Tier 2 (provider Matryoshka allowlists), so a recipe that declares fixed options (openrouter) is still governed by those and fixed-dim hosted providers (openai/voyage/zeroentropy) stay fail-closed; the provider's `/embeddings` response-dim validation catches a genuine mismatch pre-storage. `Recipe.default_headers?: Record<string, string>` (static) and `Recipe.resolveDefaultHeaders?(env)` (env-templated) seam for per-recipe headers riding alongside auth on every openai-compat touchpoint; mutually exclusive (declaring both throws `AIConfigError` at gateway-configure time); keys conflicting with the resolved auth header (`Authorization`, the resolver's custom header) rejected at `applyResolveAuth` call time so defaults can't shadow auth. Used by OpenRouter for the `HTTP-Referer` + `X-OpenRouter-Title` + `X-Title` attribution triple.
- `src/core/ai/defaults.ts` — leaf module holding the embedding/reranker default constants (no gateway import, so schema + registry helpers can read them without loading provider SDKs). Split-default: `NEW_INSTALL_DEFAULT_EMBEDDING_MODEL` (`voyage:voyage-4`) + `NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS` (1024) feed every new-install surface — init auto-pick canonical tiebreak, the interactive picker default, the no-keys hint, keyless fresh-install schema sizing (passed as an explicit init param), and all recommendation copy (playbook, banners, doctor fix-hints, advisor). `DEFAULT_RERANKER_MODEL` (= `NEW_INSTALL_DEFAULT_RERANKER_MODEL` = `voyage:rerank-2.5`) is the ONE runtime/mode-bundle reranker default: the three `MODE_BUNDLES.*.reranker_model` values and the gateway's `rerank()` fallback import it, so a brain with no `search.reranker.model` row reranks with Voyage on `VOYAGE_API_KEY`. `LEGACY_DEFAULT_RERANKER_MODEL` (`zeroentropyai:zerank-2`) is not a default anywhere; it names the `RERANKER_SUNSETS` row (which STAYS while the recipe exists, so an explicit `zeroentropyai:*` config still short-circuits past the date instead of hanging 5s per query), the short-circuit tests and the migration copy. Init (`init.ts:writeNewInstallRerankerDefault`, shared by the PGLite + Postgres paths) writes NO reranker row when the default is ready (`reranker-readiness.ts` against the file-plane + process env — an explicit row equal to the bundle value would only earn doctor's `search_mode` reset nag), writes explicit `search.reranker.enabled false` for keyed installs WITHOUT a Voyage key (no key for the default; silence beats a `no_key` audit row per process), writes nothing for keyless installs (the documented keyless-recovery re-init must find virgin reranker config; keyless brains take the no-embedding search path, which never reaches `applyReranker`), treats a ZeroEntropy embedding pick as any other keyed non-Voyage install (evaluated against env > file > DB-plane keys via `loadConfigWithEngine`, so a `--force` re-init sees a config-table key), and never clobbers an existing explicit choice. `DEFAULT_EMBEDDING_MODEL` (`zeroentropyai:zembed-1`) + `DEFAULT_EMBEDDING_DIMENSIONS` (1280) serve ONLY as the configless runtime fallback for brains with no `embedding_model` in file config — their stored vectors live in ZE's 1280d space, so flipping the fallback under them would break retrieval before the provider dies; the fallback is slated for removal after the sunset, at which point unmigrated configless brains hard-error with the migrate command. `ZEROENTROPY_SUNSET_DATE` (`'2026-09-04'`) is the single source of truth for the upgrade banners, the `provider_sunset` doctor check, and the ZE recipe's `sunset` metadata.
- `src/core/ai/reranker-readiness.ts` — pure leaf answering "is the reranker actually going to run?" for `gbrain search modes` (`buildModesReport.reranker_readiness`), doctor's `reranker_health`, and init's reranker-default write. `rerankerReadiness(model, env, { now?, baseUrlOverrides? })` → `{model, provider, modelId (alias-canonical), recipeKnown, hasTouchpoint, modelListed, requiredKey (the first MISSING key, else the first required key — this is how `Reranker: … VOYAGE_API_KEY present` renders; null only for keyless recipes), keyPresent, sunset, sunsetPassed, selfHosted, sunsetBlocks, ready}`; the env snapshot comes from the CALLER — the leaf never reads `process.env` and never imports the gateway (init runs before `configureGateway` and passes `mergedProviderEnv(cfg, process.env)` where `cfg` is `loadConfigFileOnly()` merged with the brain's DB-plane provider keys via `loadConfigWithEngine` — file plane alone if that read fails — so a `--force` re-init sees a Voyage key that lives only in the config table). A recipe with a custom `resolveAuth` needs no env key (mirrors the gateway); a `provider_base_urls` override marks the provider self-hosted so a passed sunset does not block. `describeRerankerFix(r)` renders the paste-ready one-liner (sunset switch > unknown-model > missing key + disable command). `src/core/ai/reranker-readiness-engine.ts` is the engine-plane wrapper doctor and `gbrain search modes` share: `rerankerReadinessForEngine(engine, model, { now? })` reads the LIVE gateway snapshot (env + base_urls — exactly what `rerank()` consults, so the verdict cannot disagree with search and a mounted brain's DB plane cannot steer it) and falls back to env > file > DB-plane provider keys + `provider_base_urls` via `loadConfigWithEngine` only when no gateway is configured; `redactReadinessForRemote` (modes-report.ts) strips `required_key`/`key_present`/`fix` from the `search_modes` op for untrusted callers. `test/ai/reranker-readiness.test.ts` pins agreement with `isAvailable('reranker', m)` on an env × model matrix (`recipeKnown && hasTouchpoint && keyPresent`) so the two predicates cannot drift.
-- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / ZeroEntropy / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `zeroEntropyCompatFetch` shim (sibling to `voyageCompatFetch`) handles ZE's non-OpenAI-compatible wire shape — rewrites the request URL `/embeddings → /models/embed`, injects `input_type` (default `'document'`; the threaded `'query'|'document'` crosses the SDK boundary via the module-level `__embedInputTypeStore` AsyncLocalStorage populated in `embedSubBatch()`, because the AI SDK's openai-compatible adapter strips `input_type` from `providerOptions` before building the wire body; `voyageCompatFetch` injects it opt-in the same way, and `openAICompatAsymmetricFetch` is the fallthrough shim for every other openai-compat recipe — llama-server/litellm/ollama — a strict pass-through when nothing was threaded) and explicit `encoding_format: 'float'`, and rewrites the response `{results: [{embedding}], usage: {total_bytes, total_tokens}}` → `{data: [{embedding, index}], usage: {prompt_tokens, total_tokens}}` so the SDK's openai-compatible Zod schema validates. Layer 1 (Content-Length) + Layer 2 (per-embedding) OOM caps via tagged `ZeroEntropyResponseTooLargeError` (kept separate from `VoyageResponseTooLargeError` because `test/voyage-response-cap.test.ts` does structural source-text greps pinning the Voyage name). Wired in `instantiateEmbedding()` via the `recipe.id === 'zeroentropyai'` branch. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/models/rerank`; Voyage declares `/rerank`) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `warnSunsetOnce(recipe, touchpoint)`: once-per-(recipe,touchpoint) stderr DEPRECATED warning for recipes carrying `sunset` metadata, fired on actual use (embedding resolution + the rerank path) so brains still riding a dying provider hear about it on every process, not only at upgrade time; prints the sunset date plus the migrate / `search.reranker.model` fix, never throws, `_resetSunsetWarningsForTest()` is the test seam. Past a `RERANKER_SUNSETS` date (`rerankerSunset()` from `ai/defaults.ts`), `rerank()` short-circuits BEFORE the HTTP call: the check runs where the EFFECTIVE model is resolved (`input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` — the main case is an absent per-call model landing on the configured/legacy default) and throws `RerankError('sunset_short_circuit')` so `applyReranker` fails open at once instead of burning the 5s timeout per query; suppressed under a `base_urls` recipe override (self-hosted wire-compatible endpoints outlive the hosted shutdown, same rule as `warnSunsetOnce`); traceability is ONE `sunset_short_circuit` audit row per process per model (written by the gateway to the rerank-failures JSONL, feeding doctor's reranker_health) plus one stderr line with the replacement-model switch command — per-query rows would flood the audit file until the user migrates; `__setSunsetClockForTests` is the injected-clock seam for date-matrix tests, reset alongside `_resetSunsetWarningsForTest()`. `no_key` preflight: after the sunset check and `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` (mirror of `sunsetShortCircuitOnce` MINUS the stderr line; memo `_noKeyNoticed`, cleared by `_resetSunsetWarningsForTest()`) writes ONE `no_key` audit row per process per model and nothing is printed (shell-per-query agents would otherwise see a line per search). `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | sunset_short_circuit | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (an assertion in `test/voyage-response-cap.test.ts` pins the `instanceof ⇒ throw err` line). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts`
+- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / ZeroEntropy / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `zeroEntropyCompatFetch` shim (sibling to `voyageCompatFetch`) handles ZE's non-OpenAI-compatible wire shape — rewrites the request URL `/embeddings → /models/embed`, injects `input_type` (default `'document'`; the threaded `'query'|'document'` crosses the SDK boundary via the module-level `__embedInputTypeStore` AsyncLocalStorage populated in `embedSubBatch()`, because the AI SDK's openai-compatible adapter strips `input_type` from `providerOptions` before building the wire body; `voyageCompatFetch` injects it opt-in the same way, and `openAICompatAsymmetricFetch` is the fallthrough shim for every other openai-compat recipe — llama-server/litellm/ollama — a strict pass-through when nothing was threaded) and explicit `encoding_format: 'float'`, and rewrites the response `{results: [{embedding}], usage: {total_bytes, total_tokens}}` → `{data: [{embedding, index}], usage: {prompt_tokens, total_tokens}}` so the SDK's openai-compatible Zod schema validates. Layer 1 (Content-Length) + Layer 2 (per-embedding) OOM caps via tagged `ZeroEntropyResponseTooLargeError` (kept separate from `VoyageResponseTooLargeError` because `test/voyage-response-cap.test.ts` does structural source-text greps pinning the Voyage name). Wired in `instantiateEmbedding()` via the `recipe.id === 'zeroentropyai'` branch. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/models/rerank`; Voyage declares `/rerank`) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `warnSunsetOnce(recipe, touchpoint)`: once-per-(recipe,touchpoint) stderr DEPRECATED warning for recipes carrying `sunset` metadata, fired on actual use (embedding resolution + the rerank path) so brains still riding a dying provider hear about it on every process, not only at upgrade time; prints the sunset date plus the migrate / `search.reranker.model` fix, never throws, `_resetSunsetWarningsForTest()` is the test seam. Past a `RERANKER_SUNSETS` date (`rerankerSunset()` from `ai/defaults.ts`), `rerank()` short-circuits BEFORE the HTTP call: the check runs where the EFFECTIVE model is resolved (`input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` — the main case is an absent per-call model landing on the configured/legacy default) and throws `RerankError('sunset_short_circuit')` so `applyReranker` fails open at once instead of burning the 5s timeout per query; suppressed under a `base_urls` recipe override (self-hosted wire-compatible endpoints outlive the hosted shutdown, same rule as `warnSunsetOnce`); traceability is ONE `sunset_short_circuit` audit row per process per model (written by the gateway to the rerank-failures JSONL, feeding doctor's reranker_health) plus one stderr line with the replacement-model switch command — per-query rows would flood the audit file until the user migrates; `__setSunsetClockForTests` is the injected-clock seam for date-matrix tests, reset alongside `_resetSunsetWarningsForTest()`. `no_key` preflight: after the sunset check and `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` (mirror of `sunsetShortCircuitOnce` MINUS the stderr line; memo `_noKeyNoticed`, cleared by `_resetSunsetWarningsForTest()`) writes ONE `no_key` audit row per process per model and nothing is printed (shell-per-query agents would otherwise see a line per search). `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | sunset_short_circuit | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (an assertion in `test/voyage-response-cap.test.ts` pins the `instanceof ⇒ throw err` line). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts`
- `src/core/ai/recipes/zeroentropyai.ts` — ZeroEntropy openai-compatible recipe declaring BOTH `embedding` (`zembed-1`, 7 Matryoshka dims: 2560/1280/640/320/160/80/40) AND `reranker` (`zerank-2` flagship + `zerank-1` + `zerank-1-small`, 5MB payload cap) touchpoints. `implementation: 'openai-compatible'` (pinned by `test/ai/zeroentropy-recipe.test.ts`). `base_url_default: 'https://api.zeroentropy.dev/v1'` already ends with `/v1`, so the `zeroEntropyCompatFetch` URL rewrite `/embeddings → /models/embed` produces `…/v1/models/embed` (NOT `…/v1/v1/…` — pinned there too). `chars_per_token: 1` + `safety_factor: 0.5` match Voyage's dense-content hedge. Carries `sunset` metadata (`ZEROENTROPY_SUNSET_DATE` + replacement models from `ai/defaults.ts`) that drives init picker/auto-pick exclusion, the gateway's once-per-process warn-on-use, and every `gbrain providers` rendering via the shared `sunsetMarker` in `src/commands/providers.ts` (`list` status cell, ⚠ `explain` rows, and the `env` deprecation block that replaces the signup funnel); the recipe itself is slated for removal after the sunset date.
- `src/core/ai/recipes/llama-server-reranker.ts` — sibling of `llama-server` (the embedding recipe) for llama.cpp in `--reranking` mode. Distinct recipe rather than dual-touchpoint extension because `--reranking` and `--embeddings` are mutually exclusive at server-launch time, so the two backends need independent base URLs (default 8081 here vs 8080 there). Declares `reranker` touchpoint with `models: []` (user-provided id matching the `--alias` the user launched with), `path: '/rerank'` (leaf-only; consumes `RerankerTouchpoint.path` override; gateway concatenates with `base_url_default` which ends in `/v1`, producing `…/v1/rerank`), `default_timeout_ms: 30_000` (consumed by `src/core/search/mode.ts`'s reranker timeout chain — CPU-only first-call warmup headroom; the 5s mode-bundle default would fail-open as `timeout`), `cost_per_1m_tokens_usd: 0` (recognized by `FREE_LOCAL_RERANK_PROVIDERS` in `src/core/budget/budget-tracker.ts` so `--max-cost` callers don't hard-fail on local rerank). Setup hint emphasizes `--alias` because llama-server's `/v1/models` defaults model id to the gguf file path without it. Covers Qwen3-Reranker via llama.cpp AND self-hosted ZE weights via llama.cpp — same recipe, different `--model` at launch. Pinned by `test/ai/recipe-llama-server-reranker.test.ts`. Voyage / Cohere / vLLM rerankers stay out of scope (different wire shapes). Companion surfaces: `path?: string` + `default_timeout_ms?: number` on `RerankerTouchpoint` in `src/core/ai/types.ts`; consumed by the URL build at `src/core/ai/gateway.ts:rerank()` and by mode-resolution at `src/core/search/mode.ts:resolveSearchMode` (precedence: per-call > config-key > recipe touchpoint default > mode bundle); `LLAMA_SERVER_RERANKER_BASE_URL` env passthrough in `src/cli.ts:buildGatewayConfig`; `FREE_LOCAL_RERANK_PROVIDERS` set in `src/core/budget/budget-tracker.ts:lookupPricing` (rerank-kind-only zero-pricing for the local provider prefix); doctor-fix at `src/commands/models.ts:probeRerankerConfig` reads `search.reranker.model` via `loadSearchModeConfig` + `resolveSearchMode` (so doctor and live search read the same resolution and the file plane / DB plane cannot diverge — the field-plane `getRerankerModel()` reads nothing writes); `probeRerankerReachability` reads the recipe's `default_timeout_ms` so CPU-only cold-start doesn't false-fail.
- `src/core/ai/recipes/nan.ts` — nan.builders openai-compatible reranker recipe. `POST {base}/v1/rerank` → `results[{index, relevance_score}]`, leaf-only (`base_url_default` ends `/v1`; bare `/rerank` and `/compatible-api/v1/reranks` both 404). Model id is the literal `rerank` (a Qwen3-Reranker-8B deployment). `auth_env.required: ['NAN_API_KEY']`.
- `src/core/ai/recipes/openrouter.ts` — OpenRouter openai-compatible recipe: single key, many providers via `openrouter:<provider>/<model>` strings. `base_url_default: 'https://openrouter.ai/api/v1'`. Embedding touchpoint: default model `openai/text-embedding-3-small`; per-model `model_dims` carries verified native widths (text-embedding-3-small 1536, text-embedding-3-large 3072, qwen/qwen3-embedding-8b 4096, bge-m3 + baai/bge-m3 1024) with `default_dims: 0` so an UNLISTED proxied id has NO silent default — it errors until the user supplies explicit dims (`--embedding-dimensions` / `embedding_dimensions`), which `trust_custom_dims: true` accepts (gemini-embedding-2-preview is deliberately unlisted — width unverified). Matryoshka `dims_options: [512, 768, 1024, 1536]` still governs the default model's shrink steps; `max_batch_tokens: 300_000` = OpenAI's aggregate-per-request token cap (NOT per-input). Chat touchpoint declares 8 curated entry points (gpt-5.2, gpt-5.2-chat, gpt-5.5, claude-haiku-4.5, claude-sonnet-4.6, claude-opus-4.7, gemini-3-flash-preview, deepseek-chat) but openai-compat tier accepts any model ID; deliberately no `max_context_tokens` because OR's catalog spans 128K to 1M+. `supports_subagent_loop: false` is enforced by `classifyCapabilities()` in `src/core/ai/capabilities.ts` (verdict `unusable:no_subagent_loop` — `enforceSubagentCapable()` in `src/core/model-config.ts` consumes the verdict: tool-less/unknown models fall back to `TIER_DEFAULTS.subagent` with a warn; tool-capable providers without prompt caching run with a once-per-model cost warn); the legacy Anthropic-direct path additionally gates on `isAnthropicProvider()` in `src/core/model-config.ts` when `agent.use_gateway_loop` is off. Declares `resolveDefaultHeaders(env)` returning OR's three attribution headers: `HTTP-Referer` (required for OR app-attribution), `X-OpenRouter-Title` (preferred), `X-Title` (back-compat alias); defaults to `https://gbrain.ai` / `gbrain`; forks override via `OPENROUTER_REFERER` / `OPENROUTER_TITLE` env vars. Smoke-tested by `test/ai/recipe-openrouter.test.ts` (incl. the shape guard: every model in the chat list matches `^[a-z0-9-]+\/[a-z0-9._-]+$`).
- `src/core/ai/openrouter-families.ts` — single source of truth for which OpenRouter model families may drive the subagent (tool) loop: `OPENROUTER_SUBAGENT_FAMILIES` (currently `anthropic/` + `deepseek/`, each backed by a live abort/retry replay pin under `test/e2e/`) + `openrouterModelSupportsSubagentLoop(modelId)` (takes the bare OpenRouter id, no `openrouter:` prefix). Shared by the openrouter recipe's predicate and the subagent handler's auto-route so the two can never disagree; a new family gets its own live pin before joining the list.
- `src/core/ai/recipes/lmstudio.ts` — LM Studio local OpenAI-compatible recipe (embedding touchpoint only; default base URL `http://localhost:1234/v1`, env `LMSTUDIO_BASE_URL`). Ships `models: []` like llama-server — the model identity is whatever the user loaded in the app, so `--embedding-model lmstudio:<id>` + `--embedding-dimensions <N>` are required (the wizard refuses implicit defaults). Its own provider id keeps `openai:` pointed at OpenAI (complement of the keyless `OPENAI_BASE_URL` route). Documented operational failure mode: a degraded loaded instance passes the reachability probe but misses the query-embed deadline — queries degrade to keyword-only with the `embed_timeout` stamp, reload the model to recover.
-- `src/core/ai/recipes/ollama.ts` — the Ollama local recipe. `thinking_by_default` is a per-family predicate over the model id (qwen3 with a boundary so `qwen2.5-*` is never swallowed and a `-coder` exclusion — the instruct-only variant has no thinking mode; deepseek-r*, gpt-oss, magistral, phi*-reasoning including the `-mini-reasoning` tags), not a recipe-wide boolean, so non-reasoning local models keep the conservative default.
+- `src/core/ai/recipes/ollama.ts` — the Ollama local recipe. `thinking_by_default` is a per-family predicate over the model id (qwen3 with a boundary so `qwen2.5-*` is never swallowed and a `-coder` exclusion — the instruct-only variant has no thinking mode; deepseek-r*, gpt-oss, magistral, phi*-reasoning including the `-mini-reasoning` tags), not a recipe-wide boolean, so non-reasoning local models keep the conservative default. The chat touchpoint declares `supports_structured_outputs: true` (Ollama enforces `response_format: json_schema` server-side via grammar-constrained decoding, model-independent — unlike tools, which stay `false`), so `chat()` sends a caller's `responseSchema` to Ollama (facts extraction) and `expand()` routes `ollama:*` expansion models through the strict generateObject lane with its existing rejected-recipe fallback.
- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `sunset_short_circuit` and `no_key` reasons are written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the reranker's hosted API passed its announced shutdown date / the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / sunset passed without a self-host override / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key`/`sunset_short_circuit` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.
- `src/core/search/embedding-column.ts` — single source of truth for "which `content_chunks.*` column does this query rank against?" Pure functions, no engine I/O: `loadRegistry(cfg)` walks the `embedding_columns` config (DB plane, JSON map keyed by column name with `{provider, dimensions, type}` entries), seeds the OpenAI `embedding` builtin when unset, validates everything before it lands (column-name regex, type ∈ `vector | halfvec`, dims in [1, 8192], provider format) using `Object.create(null)` + `Object.hasOwn` so a key like `constructor` rejects instead of resolving to `Object.prototype.constructor`. `resolveColumn(registry, override?, cfg)` is the boundary call: returns a frozen `ResolvedColumn` descriptor (`{name, provider, dimensions, type}`) honoring per-call override → `search_embedding_column` config → `'embedding'` default; throws `UnknownEmbeddingColumnError` with the list of registered names on miss. `isCacheSafe(resolved, cfg)` compares the full embedding SPACE (provider + dimensions + name) against cfg's default so a repointed `embedding` builtin doesn't serve OpenAI-shaped cache rows. `validateResolvedColumn(descriptor)` re-validates hand-rolled descriptors that bypass the registry (internal-SDK passthrough) so the SQL-injection escape hatch through the descriptor field is closed. Consumed by `hybridSearch`, `gateway.embedQuery(text, {embeddingModel, dimensions})`, `cosineReScore`, and the `query` MCP op (per-call `embedding_column` param). Pinned by `test/search/embedding-column.test.ts` (prototype-pollution, descriptor passthrough, env-only Postgres install, empty-brain coverage gate, cache-space comparison). Write side: `resolveWriteColumnFromConfigRows({searchEmbeddingColumn, embeddingColumnsJson})` resolves upsertChunks's active write target from the raw DB-plane config rows through the same registry/validation chain (legacy `embedding` descriptor when neither row routes elsewhere; `embedding_image` falls back to the legacy text column since image vectors travel in their own INSERT column; malformed registry JSON is forgiven like loadConfigWithEngine; unregistered names throw the paste-ready error), and `vectorCastSuffix(resolved)` is the placeholder-free `'::vector' | '::halfvec(N)'` cast shared by the read fragment builder and the write path so the two casts can't drift. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts`.
- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc, appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the two SKIP classes `sunset_short_circuit` and `no_key` (`RerankSkipReason`), which return the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fire `opts.onSkip(reason)`; `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.
- `src/core/search/return-policy.ts` (default OFF) — intent-aware adaptive return-sizing. Pure, dependency-light module that trims the final ranked candidate set to an intent-driven cap instead of returning the full top-K. `entity` intent gets a tight cap; `temporal`/`event`/`general` get a recall-preserving cap (`concept` is coerced to `general` by `hybrid.ts` before the call — concept queries want breadth). A `minKeep` failsafe (≥1) guarantees a human never gets a silent blank when candidates exist. WHY a cap, not a score-cliff detector: PrecisionMemBench instrumentation (gbrain-evals) measured the rank1→rank2 RRF gap is ~identical whether rank-1 is correct (0.602) or wrong (0.569) — mechanical decay, not a separatrix; rank-1 is right in 94% of single-answer cases, so "return a tight set" is the whole win and cliff-cutting just adds noise. Exports `AdaptiveReturnConfig`, `DEFAULT_ADAPTIVE_RETURN` (frozen: `enabled=false`, `entityMax=2`, `otherMax=6`, `minKeep=1`), `AdaptiveReturnDecision` (`{applied, intent, cap, kept, total}`), `AdaptiveReturnInput` (`boolean | Partial<AdaptiveReturnConfig> | undefined`), `adaptiveReturnFromConfig(cfg)`, `resolveAdaptiveReturn(perCall, fromConfig)` (defaults → config → per-call merge), `adaptiveReturnEnabled(...)` (cache-skip gate check), `applyAdaptiveReturn(results, intent, cfg)` (the trim). Config knobs (DB or file plane): `search.adaptive_return` (master switch), `search.adaptive_return_entity_max`, `search.adaptive_return_other_max`, `search.adaptive_return_min_keep` (each clamped ≥1). Wired into `hybridSearch` AFTER `applyReranker`, BEFORE the `limit` slice, and ONLY on the first page (`offset===0`) — paginating a confidence-gated set is incoherent, so paginated calls fall through to the fixed limit. Stamps the decision onto `HybridSearchMeta.adaptive_return` for `gbrain search --explain`. `hybridSearchCached` SKIPS the cache when the gate is on (a trimmed set must not be served to a gate-off lookup and vice versa). `SearchOpts.adaptiveReturn` + `HybridSearchMeta.adaptive_return` declared in `src/core/types.ts`. Agent-facing: the `query` op (`src/core/operations.ts`) exposes an `adaptive_return` boolean param whose description instructs the agent WHEN to set it (single-answer → on; breadth/exploration → off; pass `limit:1` for a hard single-answer cap), threaded into `hybridSearchCached` — end users never touch the config knob; their agent decides per query (same pattern as `salience`/`recency`). Pinned by `test/search/return-policy.test.ts` (mechanism) + `test/search/query-op-adaptive-return.test.ts` (agent surface: param exists + description teaches both directions + the never-empty contract).
- `src/core/search/autocut.ts` (OFF in every bundle since rule R2; `search.autocut true` re-enables it where the reranker runs) — Weaviate-style autocut: score-discontinuity result-sizing on the cross-encoder rerank separatrix. `applyAutocut(results, scoreOf, cfg)` normalizes the reranker scores, finds the largest consecutive gap, and cuts there when it clears `jumpRatio` (default 0.20); robust to unsorted provider output (cuts on a sorted copy, keeps items in INPUT order via a score threshold), guards `top<=0`/non-finite, never returns empty, and no-ops when <2 results carry a finite `rerank_score` (covers the reranker fail-open path). WHY rerank_score and NOT RRF/cosine: gbrain measured (see `return-policy.ts`) that the RRF rank1→rank2 gap is ~flat whether rank-1 is right or wrong — not a separatrix; the cross-encoder score IS. So autocut, when enabled, runs ONLY where the reranker ran (`balanced`+`tokenmax`; `conservative` is a documented no-op). Weak-top floor: when the top rerank score is below `minTopScore` (default 0.35; config `search.autocut_min_top`; scale-calibrated to the default reranker; a default-reranker change must re-tune it), cliff trimming is skipped entirely so a low-confidence list returns the full cluster instead of collapsing to one result. Exports `AutocutConfig`, `DEFAULT_AUTOCUT` (frozen: `enabled=true, jumpRatio=0.20, minKeep=1, minTopScore=0.35`), `AutocutDecision` (`{applied, signal:'rerank'|'none', cut, kept, total, gapRatio}`), `AutocutInput`, `autocutFromConfig`, `resolveAutocut`, `applyAutocut`. Cache-key integration (clean path, not the adaptive-return cache-skip hack): enable+sensitivity flow through `ModeBundle` → `ResolvedSearchKnobs` → `knobsHash` exactly like `graph_signals`. `mode.ts` adds `autocut`/`autocut_jump`/`autocut_min_keep` (`autocut` false in every bundle since rule R2 — the LongMemEval replay from the captured post-rerank pool found no floor that beat autocut off; jump 0.20 stays the sensitivity when re-enabled; floor 1 in every mode — `search.autocut_min_keep` sets the minimum result count a cut may leave, resolved through the same bundle → config → per-call chain) AND sets `reranker_top_n_in = searchLimit` for reranked modes (so the reranker scores the full returned set; there is no un-scored tail for autocut to wrongly drop). Autocut folds into `knobsHash` as its own parts entry (`mode.ts:KNOBS_HASH_VERSION` is the single source of truth for the current hash version; every bump is a one-time global cache cold-miss on upgrade). Wired into `hybridSearch` AFTER adaptive-return, BEFORE the limit slice, first page only; emits `HybridSearchMeta.autocut`. BOTH the cache-miss `finalMeta` and cache-HIT `cachedMeta` rebuilds carry `autocut`+`adaptive_return`+`mode`+`embedding_column`. Preserves alias-hop exact matches: `applyAutocut` takes an optional `preserve` predicate; hybrid passes `r => r.alias_hit === true || r.exact_lookup !== undefined || r.relational_pinned === true` so a canonical page injected by `applyAliasHop` after reranking (no `rerank_score`), an exact-lookup tier hit, or a relational row re-pinned by `pinRelationalRows` (low cross-encoder score by construction; ALSO excluded from the cliff computation through `scoreOf`, so text-row autocut is unchanged by the pin) is never cut. Agent surface: `query` op `autocut` boolean (ceiling override — `false` forces full top-K); `SearchOpts.autocut`; `--explain` shows per-result `rerank_score`, `formatAutocutSummary` renders the decision when search meta is threaded; `gbrain search modes` attribution; metric glossary `autocut.signal`/`autocut.gap_ratio`. Config: `search.autocut`, `search.autocut_jump`, `search.autocut_min_keep`. The `DEFAULT_AUTOCUT` module constant is unchanged (`enabled=true`) for operators who re-enable it; the cliff logic is backed by an in-repo eval gate — `test/search/autocut-eval.test.ts` (also `bun run eval:autocut`) measures precision-lift-without-recall-regression over labeled qrels fixtures with modeled cross-encoder distributions (no API key, no sibling repo; runs in CI): mean precision 0.33→0.94, recall 1.00→0.95, ZERO recall loss on enumeration queries. Env-overridable floors. Pinned by `test/search/autocut.test.ts` (pure-fn), `test/search/query-op-autocut.test.ts` (agent surface), `test/search/autocut-integration.serial.test.ts` (IRON-RULE behavioral via `rerankerFn` DI seam: cliff trims, flat doesn't, no-reranker no-ops, `autocut:false` ceiling, composes with adaptive-return), `test/search/autocut-eval.test.ts` (the precision/recall gate), and the knobsHash assertions in `test/search-mode.test.ts`.
-- `src/core/ai/recipes/voyage.ts` — Voyage AI openai-compatible recipe, home of the new-install default stack. Embedding touchpoint declares `default_model: 'voyage-4'` + `default_dims: 1024` — the canonical pick for every "choose a model for the user" surface (`models[0]` stays `voyage-4-large` in quality order; the new-install default is `voyage-4` for price/quality balance and the shared v4 embedding space — see `NEW_INSTALL_DEFAULT_EMBEDDING_MODEL` in `ai/defaults.ts`). Reranker touchpoint (the mode-bundle default via `DEFAULT_RERANKER_MODEL`, same `VOYAGE_API_KEY` as embeddings) allowlists `rerank-2.5` ($0.05/M) + `rerank-2.5-lite` ($0.02/M) and Voyage's preview `rerank-3` ($0.05/M) + `rerank-3-lite` ($0.02/M) (2.5 pair verified 2026-08-15, rerank-3 pair 2026-09-06); `default_model` stays `rerank-2.5` deliberately — the array is the opt-in surface for every enforcement point (`gateway.rerank()`'s `tp.models.includes` guard, `gbrain models doctor`'s `reranker_config` probe, `rerankerReadiness`), and flipping the default would migrate every install that resolves it instead of an explicit config row. All four share one wire: `path: '/rerank'`, `top_param: 'top_k'` (Voyage's response wire matches ZE's `{results: [{index, relevance_score}]}`; only the request's top-N key differs), 5MB byte-proxy payload cap. Declares `chars_per_token=1` + `safety_factor=0.5` so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio), since tiktoken-grounded budgeting undercounts Voyage's actual token usage. Declares `multimodal_models: ['voyage-multimodal-3']` so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear `AIConfigError` instead of waiting for Voyage's HTTP 400. The hosted flexible-dim models that accept `output_dimension` live in `VOYAGE_OUTPUT_DIMENSION_MODELS` in `src/core/ai/dims.ts` (v4 trio, `voyage-code-4`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3`; valid widths 256/512/1024/2048); `voyage-4-nano` is the open-weight variant fixed at 1024-dim that does NOT accept the parameter (negative assertion in `test/ai/gateway.test.ts`: `dimsProviderOptions` returns `undefined` for `voyage-4-nano`). `voyage-code-3` is the recommended embedding model for gstack per-worktree code brains (Topology 3 in `docs/architecture/topologies.md`; `voyage-code-4` is the flexible-dim hosted code model, $0.12/M); discoverability surfaces: decision-tree branch in `docs/integrations/embedding-providers.md`, Topology 3 "Recommended embedding model" subsection, runtime nudge from `gbrain reindex --code` against non-code-tuned models. Recipe shape pinned by `test/ai/voyage-code-3-recipe.test.ts`.
+- `src/core/ai/recipes/voyage.ts` — Voyage AI openai-compatible recipe, home of the new-install default stack. Embedding touchpoint declares `default_model: 'voyage-4'` + `default_dims: 1024` — the canonical pick for every "choose a model for the user" surface (`models[0]` stays `voyage-4-large` in quality order; the new-install default is `voyage-4` for price/quality balance and the shared v4 embedding space — see `NEW_INSTALL_DEFAULT_EMBEDDING_MODEL` in `ai/defaults.ts`). Reranker touchpoint (the mode-bundle default via `DEFAULT_RERANKER_MODEL`, same `VOYAGE_API_KEY` as embeddings) allowlists `rerank-2.5` ($0.05/M) + `rerank-2.5-lite` ($0.02/M) and Voyage's preview `rerank-3` ($0.05/M) + `rerank-3-lite` ($0.02/M) (2.5 pair verified 2026-08-15, rerank-3 pair 2026-09-06); `default_model` stays `rerank-2.5` deliberately — the array is the opt-in surface for every enforcement point (`gateway.rerank()`'s `tp.models.includes` guard, `gbrain models doctor`'s `reranker_config` probe, `rerankerReadiness`), and flipping the default would migrate every install that resolves it instead of an explicit config row. All four share one wire: `path: '/rerank'`, `top_param: 'top_k'` (Voyage's response wire matches ZE's `{results: [{index, relevance_score}]}`; only the request's top-N key differs), 5MB byte-proxy payload cap. Declares `chars_per_token=1` + `safety_factor=0.5` so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio), since tiktoken-grounded budgeting undercounts Voyage's actual token usage. Declares `multimodal_models: ['voyage-multimodal-3']` so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear `AIConfigError` instead of waiting for Voyage's HTTP 400. The hosted flexible-dim models that accept `output_dimension` live in `VOYAGE_OUTPUT_DIMENSION_MODELS` in `src/core/ai/dims.ts` (v4 trio, `voyage-code-4`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3`; valid widths 256/512/1024/2048); `voyage-4-nano` is the open-weight variant fixed at 1024-dim that does NOT accept the parameter (negative assertion in `test/ai/gateway.test.ts`: `dimsProviderOptions` returns `undefined` for `voyage-4-nano`). `voyage-code-3` is the recommended embedding model for gstack per-worktree code brains (Topology 3 in `docs/architecture/topologies.md`; `voyage-code-4` is the flexible-dim hosted code model, $0.12/M); discoverability surfaces: decision-tree branch in `docs/integrations/embedding-providers.md`, Topology 3 "Recommended embedding model" subsection, runtime nudge from `gbrain reindex-code` against non-code-tuned models. Recipe shape pinned by `test/ai/voyage-code-3-recipe.test.ts`.
- `src/core/ai/recipes/anthropic.ts` — Anthropic recipe (chat + expansion touchpoints). Canonical id is `claude-sonnet-4-6` (no date suffix); a reverse alias `claude-sonnet-4-6-20250929 → claude-sonnet-4-6` keeps stale user configs working (rescues `facts.extraction_model` and `models.dream.synthesize`). Recipe shape pinned by `test/anthropic-model-ids.test.ts`.
- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter that shells out to the locally-installed `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt-instructed JSON emission: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt does not ask for an id, and a stray `id` field is deliberately ignored (nothing round-trips it — the loop pairs results in-memory within one turn). doStream not implemented; callers (gateway.toolLoop) use doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw NoObjectGeneratedError on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`.
- `src/core/ai/providers/claude-cli-scratch.ts` — the claude-cli provider's per-PID scratch dirs (`claudeCliCwdDir`/`claudeCliConfigDir` off the `CLAUDE_CLI_CWD_PREFIX`/`CLAUDE_CLI_CONFIG_PREFIX` basename constants, plus `sweepDeadClaudeCliScratchDirs`), split into a dependency-light module so transcript discovery (`src/core/transcripts/discover.ts`) can call `isClaudeCliSelfTranscriptPath(path)` WITHOUT importing the provider's @ai-sdk surface. Each `claude --print` subprocess runs with cwd = a per-PID scratch dir (context isolation — no local CLAUDE.md auto-discovery), and Claude Code records a session transcript for that cwd under `~/.claude/projects/<slugified-cwd>/`; those sessions are gbrain's OWN internal LLM calls, and importing them back is a self-ingestion feedback loop (prompt scaffolding + page content re-entering as "conversations"). The prefix is lowercase `[a-z-]` only, so it survives Claude Code's cwd slugification verbatim and a substring match on the discovered path is a reliable self-exclusion fingerprint. Pinned by `test/transcripts-self-exclusion.test.ts`.
@@ -216,7 +218,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/budget/budget-tracker.ts` — the keystone budget primitive. One typed error (`BudgetExhausted` with `reason: 'cost' | 'runtime' | 'no_pricing'`), one schema-stable audit JSONL at `~/.gbrain/audit/budget-YYYY-Www.jsonl`. Contracts: `record()` throws when cumulative spend exceeds cap (the cap is a real ceiling, not a suggestion); `reserve()` admission checks cumulative + OUTSTANDING spend — each admitted projection is held until its `record()` settles it, so N concurrent callers (skillopt's validation gate) can't all pass against the same cumulative and breach `--max-cost-usd` by (N-1)×per-call cost; `reserve()` hard-fails with `reason: 'no_pricing'` when `maxCostUsd` is set AND the model is missing from pricing maps (warn-once preserved when cap is unset); `lookupPricing` normalizes recipe aliases through `resolveRecipe` before consulting the pricing tables, so `claude-cli:haiku` prices exactly like `claude-cli:claude-haiku-4-5-20251001` at `reserve()`, `record()` and `isModelPriceable()` alike (the gateway reserves with the pre-resolution string the user configured); `extractUsageFromError(err, fallback)` returns `err.usage` when the SDK provides it, else the pessimistic fallback (caller passes `maxOutputTokens`, not the optimistic pre-call estimate). `onExhausted(cb)` fires once synchronously BEFORE the throw propagates so callers can persist checkpoints. Shared by brainstorm, cycle/budget-meter, and eval-contradictions; `BudgetMeter` keeps its public shape over it (`schema_version: 1` stamped on every dream-budget audit line). Pinned by 18 unit cases.
- `src/core/audit-week-file.ts` — single source of truth for ISO-week audit JSONL filename math. Exports `isoWeek(d)`, `isoWeekFilename(prefix, now?)`, `resolveAuditDir()` (honors `GBRAIN_AUDIT_DIR`). Year-boundary correctness pinned by tests at 2020-W53 (the 53-week year), 2025-W01 rolling in from 2024-12-30 (Monday), 2026-W01. Four call sites: `src/core/minions/handlers/shell-audit.ts`, `src/core/facts/phantom-audit.ts`, `src/core/audit-slug-fallback.ts`, `src/core/cycle/budget-meter.ts`. Each keeps its `compute<X>AuditFilename` thin wrapper.
- `src/core/diarize/payload-fitter.ts` — generic fit-arbitrarily-large-items-into-per-call-token-budget utility. `'batch'` strategy is deterministic token-budgeted chunking with no LLM calls. `'summarize'` strategy embed-clusters into ceil(items/4) groups via cheap deterministic nearest-neighbor on cosine, Haiku-summarizes each cluster via `Promise.allSettled` at parallelism=4. Each Haiku call composes the active BudgetTracker via the AsyncLocalStorage. Quality gate: when `success_ratio < min_success_ratio` (default 0.75), result is flagged `degraded: true` — the fitter preserves the successful subset; the caller decides whether to surface a partial result or abort.
-- `src/core/brainstorm/checkpoint.ts` — crash-resilient checkpoint for `gbrain brainstorm` and `gbrain lsd`. Persists FULL idea bodies (~50KB/run) so resume MERGES pre-crash ideas with post-resume ideas before the judge runs (a resume that produces only second-run output is silent partial output). `run_id = sha256(question + profile + sort(close_slugs) + sort(far_slugs)).slice(0,16)` — NO embedding bits, stable across embedding-model swaps. Atomic write via `.tmp + rename`. ONE resume flag (`--resume <run_id>` covers both failed AND never-attempted crosses); `--list-runs` prints run_ids mtime-newest-first; `--force-resume` bypasses the 7-day staleness gate. Cycle purge phase (`gbrain dream --phase purge`) GCs checkpoints older than 7 days via `gcStaleCheckpoints(7)`. Pinned by `test/e2e/brainstorm-resume.test.ts` (20 unit + 3 E2E cases incl. the merge contract).
+- `src/core/brainstorm/checkpoint.ts` — crash-resilient checkpoint for `gbrain brainstorm` and `gbrain lsd`. Persists FULL idea bodies (~50KB/run) so resume MERGES pre-crash ideas with post-resume ideas before the judge runs (a resume that produces only second-run output is silent partial output). `run_id = sha256(question + profile + sort(close_slugs) + sort(far_slugs)).slice(0,16)` — NO embedding bits, stable across embedding-model swaps. Atomic write via `.tmp + rename`. ONE resume flag (`--resume <run_id>` covers failed crosses, never-attempted crosses, AND a failed judge phase — the orchestrator keeps the checkpoint with `judge_done=false` whenever the judge throws, so `--resume` short-circuits every completed cross from disk and re-runs only the judge; there is no separate retry-judge flag); only a fully clean run (all crosses + judge) clears the file. The checkpoint also banks the CLI's saved-page slug (`idea_slug`, from `RunBrainstormOpts.ideaSlug`) and the orchestrator echoes it back as `BrainstormResult.idea_slug` on resume, so the re-scored page overwrites the one the failed run saved instead of forking a second page under a fresh nonce. `--list-runs` prints run_ids mtime-newest-first; `--force-resume` bypasses the 7-day staleness gate. Cycle purge phase (`gbrain dream --phase purge`) GCs checkpoints older than 7 days via `gcStaleCheckpoints(7)`. Pinned by `test/e2e/brainstorm-resume.test.ts` (20 unit + 5 E2E cases incl. the merge contract and judge-failed retention/re-score).
- `src/core/remediation-checkpoint.ts` — `doctor --remediate` checkpoint at `~/.gbrain/remediation/<plan_hash>.json`. `plan_hash = sha256(JSON.stringify(sorted recommendation ids)).slice(0,16)`. Schema-versioned, atomic `.tmp + rename`. `gbrain doctor --remediate --resume <plan_hash>` (no arg picks newest matching) loads it and skips completed steps. Mismatched plan_hash refuses with a paste-ready message. Cleared on clean completion. Pinned by 13 unit cases.
- `src/core/model-config.ts` — Model-string resolution (the seam every internal LLM call walks through). Four-tier system (`ModelTier = 'utility' | 'reasoning' | 'deep' | 'subagent'`) with `TIER_DEFAULTS` (utility→haiku-4-5, reasoning→sonnet-4-6, deep→opus-4-7, subagent→sonnet-4-6) and `tier?: ModelTier` on `ResolveModelOpts`. `resolveModelDetailed()` runs the 8-step chain and reports WHICH step won (`ResolveSource`): cliFlag → config key → deprecated key → `models.tier.<tier>` → `models.default` → env var (`GBRAIN_MODEL`) → key-aware tier default → caller fallback (the tier key sits ABOVE `models.default` — tier-specific beats generic, so setting a cheap utility tier is honored even when `models.default` is also set); `resolveModel()` is the thin wrapper for callers that only want the string. Step 7 is KEY-AWARE: `resolveTierDefault(tier, env?)` walks `PROVIDER_TIER_DEFAULTS` (anthropic first — zero change for keyed installs; openai second so an OPENAI_API_KEY-only install resolves servable defaults) over the merged provider env (`mergedProviderEnv`, config-file keys folded, env wins, empty strings dropped); injected `env` is used EXCLUSIVELY (no config read — hermetic for tests); when neither anthropic nor openai key is present, a SERVABLE file-plane pin for the tier (utility→`expansion_model`, other tiers→`chat_model`, checked via `providerKeyReady`, `PIN_KEY_BY_TIER` is the single tier→key map) wins over the floor so a single-provider install (DeepSeek-only, OpenRouter-only, ...) routes every bare-default caller — extract_atoms, facts classify, page-summary — to the provider it actually has a key for; no key and no servable pin → `TIER_DEFAULTS` unchanged. The openai entry carries NO literal model pins: it resolves per call through the latest-model discovery cache (`src/core/ai/openai-latest.ts`, account-discovered, priced-only) with `openaiStaticTierFallback()` — the openai recipe's chat list ranked by the same grammar — as the offline floor, so the recipe is the single human-updated source and the account is the runtime source. The `gpt` alias resolves dynamically through the same path (the map entry is a documentation floor). `resolveEffectiveChatModel(fileCfg, env)` / `resolveEffectiveExpansionModel` are the ENGINE-FREE shared effective-model resolvers (`GBRAIN_MODEL` > servable file pin per `providerKeyReady` (recipe `auth_env.required`) > key-aware tier default; unservable pins warn once and fall through) — used by BOTH `reconfigureGatewayWithEngine`'s fallback layer and `detectCapabilities`' extraction probe so runtime routing and the capability report cannot diverge; they read RAW `loadConfig()` output, never gateway state (the boot fold stamps defaults, making explicit pins indistinguishable there). `isAnthropicProvider(modelString)` checks `provider:model` prefix OR `claude-` bare-id pattern (routes through `splitProviderModelId` from `src/core/model-id.ts` so slash-form ids like `anthropic/claude-sonnet-4-6` classify correctly). `enforceSubagentCapable()` is the layer-2 runtime guard: `tier === 'subagent'` resolutions are classified via `classifyCapabilities()` — `unusable:no_tools`/`unknown` warn once and fall back to `TIER_DEFAULTS.subagent`; `degraded:no_caching` (e.g. OpenAI) passes with a once-per-`(source, model)` cost warn. `_resetDeprecationWarningsForTest()` clears all three warn memos (deprecation, subagent, unservable-pin). Pinned by `test/model-config.serial.test.ts`.
- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId)` checks the PROVIDER's capability only (anthropic has no embedding touchpoint; voyage/ollama have no chat) and never gates on the model id. Recipe `models:` arrays are informational — default-model selection (`models[0]` for `--model <provider>` shorthand and env-ready pickers), guard-test fixtures for the repo's own hardcoded defaults, and `gbrain providers list` display — NOT a runtime allowlist, so frontier models newer than a recipe work without a recipe PR. A nonexistent id surfaces as the provider's own `model_not_found` at call time; `gbrain models doctor` live-probes the configured models for a pre-flight check. Exception: `gateway.rerank()` keeps its own model-list check because each listed reranker id maps to a known request/response wire shape. `embeddingDimsForModel` matches recipe `model_dims` keys exactly first, then case-insensitively with BOTH sides folded (configured ids arrive cased, and user-editable recipe tables can carry cased keys; without the fold a cased id would fall through to `default_dims` and `gbrain init` would build a wrong-width column), before falling back to `default_dims`.
@@ -285,23 +287,25 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override] [--force-sunset-target]` (alias: `gbrain retrieval-upgrade`, slated for removal). ONE shared orchestrator for CLI and the `migrate_embeddings` op: `planMigrationFlow` (plan + `verifyMigrationComplete` + env presence + un-merged file plane + brain/DB identity via `redactPgUrl` + concurrent-writer census + reranker plan + in-flight-other marker) and `executeMigrationFlow` (global `gbrain-embedding-migration` DbLock → retarget gate under it → all-source embed locks sorted with `includeArchived` → live embed probe → apply → reranker probe + switch → drain via `runEmbedCore({heldLocks, …})` so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as `lock_lost` → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on `verify.complete` with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). `--status` is read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome). `persistEmbeddingFileConfig` writes through `loadConfigFileOnly` (never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 2 non-TTY without `--yes`. Pinned by `test/migrate-embeddings-flow.serial.test.ts`, `test/migrate-embeddings-boundary.serial.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`. Discovery surfaces all render the canonical command from `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`): gateway deprecation line, init warnings, upgrade ACTION REQUIRED banner, doctor `provider_sunset`, ze-switch refusal, advisor — drift-guarded by `test/canonical-migration-command.test.ts`; the shutdown date lives once as `ZEROENTROPY_SUNSET_DATE` in `defaults.ts`.
- `src/commands/ze-switch.ts` — pure refusal/redirect shim for the sunset ZeroEntropy switch. Every invocation refuses or redirects with exit 1 and `reason: 'provider_sunset'`, printing the off-ramp (`gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run`); the `--json` refusal envelope is `{status:'refused', reason:'provider_sunset', migrate, migrate_preview, message}` (live command + cost preview, each carrying an explicit `--brain` suffix); `--undo` REDIRECTS (reads the `ze_switch_previous_snapshot` config row and prints the exact migrate command that returns the brain to its pre-switch provider — `{status:'redirected', reason:'provider_sunset', undo_command, undo_preview, message}` in `--json`; missing/corrupt snapshot degrades to the refusal); `--help` answers engine-free via `CLI_ONLY_SELF_HELP` + the `SELF_HELP_WITHOUT_ENGINE` wrapper in cli.ts (exit 0, truthful sunset copy). Its flags stay REGISTERED (quoted literals feed the generated registry row) so existing scripts reach the refusal instead of a pre-dispatch unknown-flag error — the shim never consults them. Nothing here mutates the brain. The whole command is slated for removal after the sunset. Pinned by `test/ze-switch-cli.test.ts` + `test/cli-help-without-brain.serial.test.ts`.
- `src/commands/providers.ts` — `gbrain providers list | test [--touchpoint T] [--model ID] | env <id> | explain [--json]`: provider-recipe discovery + smoke-testing over the recipe registry. `list` renders `formatRecipeTable` against the SAME env the gateway actually sees (`buildGatewayConfig(cfg).env`, file-plane keys folded in) so the STATUS column matches what `providers test` and init would report. Home of the ONE shared sunset-marker primitive (`sunsetMarkerText`/`sunsetMarker`, generic on `recipe.sunset` — any future provider sunset inherits it) consumed by all three human-facing renderings so they can't drift: the `list` status cell, `explain` rows (lead marker is ⚠ regardless of key readiness — never a green ready-check on a sunsetting provider), and the `env` block, where the pure `formatEnvOutput(recipe, env)` (testable without spawning the CLI) replaces the signup funnel (`setup_url`/`setup_hint`) with the deprecation notice, replacement models, and the canonical migration command from `renderCanonicalMigrationCommands` — key STATUS still renders for existing users. Pinned by `test/providers.test.ts`.
-- `src/core/conversation-parser/` — 19-pattern built-in chat-format registry + opt-in LLM polish/fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning; also populates `ParseResult.unrecognized_headings` — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns `regex_match`, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind `opts.diagnostic` — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; `gbrain conversation-parser scan` surfaces the field in both human and JSON output), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; polish and fallback are thin wrappers), `llm-polish.ts` (opt-IN; headroom guard skips when tracker within $0.10 of cap; pure `applyPolish` for merge/drop/edit ops), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `chatgpt-export-you-chatgpt` (regex `/^\*\*(You|ChatGPT):\*\*\s*(.*)$/`, declared just before `bold-name-no-time` so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's `**You:**` / `**ChatGPT:**` anchor is followed by a blank line and a multi-paragraph reply; `bold-name-no-time` alone cannot absorb that shape (`multi_line: false` scores a long reply's density near zero and falls below `SCORING_MIN_ACCEPTANCE`), so this pattern sets `multi_line: true` + `score_continuations_as_body: true` (excludes non-`**`-prefixed reply lines from the density denominator) + `score_full_body: true` (belt-and-suspenders full-body recompute of the winner). The speaker capture is a closed two-value enumeration (`You` or `ChatGPT` exactly, never an arbitrary `(.+?)` label), so it cannot reopen `bold-name-no-time`'s BROAD-REGEX GUARD against notes pages. Because a bare `**You:**`/`**ChatGPT:**` heading (unlike `bold-time-dash`'s bold-name+time+dash anchor) is a plausible label in ordinary prose ABOUT ChatGPT, the pattern also sets the optional `PatternEntry.score_continuations_min_distinct_speakers: 2`: `scoreFromLines` only grants the continuation-density-exclusion score when the anchor lines that fully match `regex` collectively capture at least that many DISTINCT `speaker_group` values, so a page with only a solitary `**You:**` heading (or several repeats of the SAME role) falls back to the ordinary flat-density score instead of getting the same acceptance immunity a genuine two-party exchange gets. It ALSO sets `PatternEntry.score_continuations_max_preamble_lines: 5`, because distinct-speaker count alone still lets ONE genuine `**You:**`/`**ChatGPT:**` pair embedded anywhere inside an otherwise unrelated long document (both roles present) through: `scoreFromLines` tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (tolerating a short title/heading preamble, not an arbitrary amount of unrelated prose before the transcript). Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,llm-polish,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](conversation-parser-patterns.md).
+- `src/core/conversation-parser/` — 19-pattern built-in chat-format registry + opt-in LLM polish/fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning; also populates `ParseResult.unrecognized_headings` — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns `regex_match`, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind `opts.diagnostic` — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; `gbrain conversation-parser scan` surfaces the field in both human and JSON output; `applyPattern` never DROPS a matched anchor whose date it cannot reconstruct (a localized month name, malformed digits) — dropping it would fold that speaker's body into the previous turn on a multi_line pattern, so the message opens anyway, inheriting the previous anchor's timestamp (page fallback date at midnight for the first), and the count surfaces as `ParseResult.date_fallback_count`, undefined when zero), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; polish and fallback are thin wrappers), `llm-polish.ts` (opt-IN; headroom guard skips when tracker within $0.10 of cap; pure `applyPolish` for merge/drop/edit ops), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `chatgpt-export-you-chatgpt` (regex `/^\*\*(You|ChatGPT):\*\*\s*(.*)$/`, declared just before `bold-name-no-time` so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's `**You:**` / `**ChatGPT:**` anchor is followed by a blank line and a multi-paragraph reply; `bold-name-no-time` alone cannot absorb that shape (`multi_line: false` scores a long reply's density near zero and falls below `SCORING_MIN_ACCEPTANCE`), so this pattern sets `multi_line: true` + `score_continuations_as_body: true` (excludes non-`**`-prefixed reply lines from the density denominator) + `score_full_body: true` (belt-and-suspenders full-body recompute of the winner). The speaker capture is a closed two-value enumeration (`You` or `ChatGPT` exactly, never an arbitrary `(.+?)` label), so it cannot reopen `bold-name-no-time`'s BROAD-REGEX GUARD against notes pages. Because a bare `**You:**`/`**ChatGPT:**` heading (unlike `bold-time-dash`'s bold-name+time+dash anchor) is a plausible label in ordinary prose ABOUT ChatGPT, the pattern also sets the optional `PatternEntry.score_continuations_min_distinct_speakers: 2`: `scoreFromLines` only grants the continuation-density-exclusion score when the anchor lines that fully match `regex` collectively capture at least that many DISTINCT `speaker_group` values, so a page with only a solitary `**You:**` heading (or several repeats of the SAME role) falls back to the ordinary flat-density score instead of getting the same acceptance immunity a genuine two-party exchange gets. It ALSO sets `PatternEntry.score_continuations_max_preamble_lines: 5`, because distinct-speaker count alone still lets ONE genuine `**You:**`/`**ChatGPT:**` pair embedded anywhere inside an otherwise unrelated long document (both roles present) through: `scoreFromLines` tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (tolerating a short title/heading preamble, not an arbitrary amount of unrelated prose before the transcript). Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,llm-polish,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](conversation-parser-patterns.md).
- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).
- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd`; **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-workers.test.ts` + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`.
- `src/core/facts/conversation-types.ts` — single-source conversation-type allowlist (`ALLOWED_TYPES`: conversation, meeting, slack, email, imessage, imessage-daily + `AllowedType`). Every consumer derives from this frozen leaf module — `extract-conversation-facts.ts` (which re-exports both names verbatim for its existing importers), the cycle backfill phase, `doctor.ts` + `doctor/checks/search-eval.ts`, `sources.ts`, `jobs.ts` — so no hand-copied list can drift. It lives under `src/core/facts/` (not `src/commands/`) because `scripts/generate-flag-registry.ts` scans option-shaped literals one relative-import level deep — importing the constant straight from `extract-conversation-facts.ts` would transitively attribute that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry. Drift-guarded by `test/conversation-facts-type-allowlist-drift.test.ts`.
- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. Markdown links, bare-slug prose refs, and slash-shaped wikilinks match ANY dir-shaped path (`ANY_DIR_SEGMENT`), not a directory whitelist — nonexistent targets are dropped by the persist paths' page-existence checks (`resolveCandidateSources`, put_page's allSlugs filter, `addLinksBatch` INNER JOINs) and counted as `skippedMissingTarget` in the extract summaries; the `DIR_PATTERN` whitelist is only the typed fast-path for pass-2b wikilinks (non-whitelisted `[[dir/...]]` get an equivalent direct typed candidate in pass 2c, plus the flag-gated suffix rescue for non-exact matches). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEntityRefs`); `EntityRef.needsResolution: true` tags refs from this pass (the ref's `slug` is the wikilink TARGET, `name` the optional display alias). `SlugResolver` gains optional `resolveBasenameMatches(name): Promise<string[]>` (multi-match by design — emits one edge per matching page). The single shared basename matcher is `buildBasenameIndex(slugs)` + `queryBasenameIndex(index, name)` + `normalizeBasename` (keys raw/lower/slugified tail, stable-sorted shorter-first then lexical), used by `makeResolver`, the FS `resolveBasenameMatchesFromSlugs`, AND the doctor check so they cannot drift. `makeResolver(engine, {mode, sourceId})` builds the index lazily via `engine.getAllSlugs({sourceId})` — source-scoped so a bare `[[name]]` never resolves to a same-tail page in a different source. `extractPageLinks` gains `opts.globalBasename` (routes `needsResolution` refs through `resolveBasenameMatches` keyed on `ref.slug`, emits candidates tagged `linkType: 'wikilink_basename'` + `linkSource: 'wikilink-resolved'`, skips self-loops) and `opts.skipFrontmatter`. All three surfaces (FS extract, DB extract, `put_page` auto-link) tag provenance with `link_source='wikilink-resolved'`; `put_page` includes it in its reconcilable-edge set so stale basename edges are removed when the wikilink or the flag goes away. Exports `WIKILINK_BASENAME_LINK_TYPE` + `isGlobalBasenameEnabled(engine)` (resolution order: env `GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME` → DB config `link_resolution.global_basename` → default false). `gbrain doctor`'s `link_resolution_opportunity` check surfaces a paste-ready enable hint when ≥5 bare wikilinks would resolve AND ≥20% match. Migration v113 widens `links_link_source_check` to admit `'wikilink-resolved'`; v114 then opens it to any kebab-case provenance (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, ≤64 chars) so external derivers register their own tag (e.g. `citation-graph`) without a migration. `LINK_EXTRACTOR_VERSION_TS` also lives here (bump like `CHUNKER_VERSION` to invalidate prior extract-stale stamps). Pinned by `test/link-extraction.test.ts`, `test/extract-fs.test.ts`, `test/doctor.test.ts`, `test/e2e/global-basename-pglite.test.ts`.
-- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). No in-memory dedup pre-load — candidates buffered 100 at a time and flushed via `addLinksBatch` / `addTimelineEntriesBatch`; `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.generated.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` for `pagesAffected` at the inline-extract call site, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.
+- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). No in-memory dedup pre-load — candidates buffered 100 at a time and flushed via `addLinksBatch` / `addTimelineEntriesBatch`; `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs, and every other file looked deleted and was skipped in silence; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on directory-read order. Both return `ExtractForSlugsResult { created, processed }`; `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.generated.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.
- Extract CLI help — `EXTRACT_HELP` in `src/commands/extract.ts` is the canonical detailed usage shared by `--help` and invalid-subcommand errors. `src/cli.ts` routes `extract --help` before engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned by `test/cli-help-discoverability.test.ts`.
+- `src/core/extract-frontmatter.ts` — `resolveIncludeFrontmatter(engine, explicit?)`: the single answer for "extract `related:`/`sources:` frontmatter link edges too?" (`autopilot.incremental_extract_include_frontmatter`; explicit flag > file plane > DB plane via `isConfigTruthy` > false, fail-closed on an unreadable config table). Resolved INSIDE the shared helpers — `extractLinksForSlugs` and `extractStaleFromDB` default `opts.includeFrontmatter` through it, the same in-helper pattern as `isGlobalBasenameEnabled` — so sync's inline extract, the GitHub/Google source inline extracts, the `extract_stale` minion, `gbrain maintain`, the cycle's extract phase and `gbrain extract --stale` (flag absent → configured knob) all agree; no caller passes a literal `false`. Pinned by `test/extract-include-frontmatter-config.serial.test.ts` (resolver precedence + a source-text guard on the call sites + a PGLite link-row test through `extractLinksForSlugs`).
- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE receipt page per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; frontmatter stamps BOTH `type: extract_receipt` AND `dream_generated: true` (belt+suspenders against extraction-loop guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. `extract_health` doctor check reads last 7 days, warns at halt-rate > 10% AND when rollup_write_failures > 0; pre-v104 brains report `ok`. CLI: `gbrain extract status [--source-id ID] [--kind X] [--verbose] [--json]` (7-day rollup, sorted halt_rate desc + cost desc, top-5 + "more rows" hint, stable `schema_version: 1`); `gbrain extract --explain <kind>` (resolution chain pack-declared vs built-in cycle phase, prompt_template + fixture_corpus paths with `✓`/`(missing)`, last 7d rollup); `gbrain extract benchmark --pack X --kind Y` (loads pack fixture corpus through strict path validation — rejects absolute paths, `..` traversal, null bytes, AND symlinks resolving outside pack root; ships as a stub-reporter). `src/core/schema-pack/manifest-v1.ts` widens `extractable` from `z.boolean()` to `z.union([z.boolean(), ExtractableSpecSchema])` (carries `prompt_template`, `fixture_corpus`, `eval_dimensions`, `benchmark_min_recall`, plus reserved `verifier_path` — parses but refuses at runtime); `extractableSpecsFromPack` + `getExtractableSpec` + `refuseVerifierPathInV042` in `src/core/schema-pack/extractable.ts`; `gbrain schema scaffold-extractable <type> --pack <pack>` declares the type extractable, generates 5 placeholder fixtures + a prompt template stub under `packs/<pack>/{fixtures,prompts}/extract/`, refuses to overwrite without `--force`. Pinned by `test/extractable-spec-widening.test.ts` (22), `test/extract/receipt-writer.test.ts` (12, canonical PGLite block R3+R4), `test/extract/benchmark.test.ts` (17), `test/extract/status.test.ts` (15), `test/schema-pack/scaffold-extractable.test.ts` (15, privacy guards), `test/doctor-extract-health.test.ts` (8).
-- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with the path-set checkpoint. `runImport` contains NO `process.exit`: all five preflight/argv failure sites (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target) throw the exported typed `ImportAbortError` (carries `exitCode`; the user-facing message is printed at the throw site), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.serial.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Uses a path-set checkpoint via `src/core/import-checkpoint.ts` (the walk still applies `sortNewestFirst()` for embed-cost ordering, but checkpoint correctness does not depend on sort order). A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. This rules out three failure classes: parallel-import-with-slow-worker dropping the slow file on crash-resume (the slow file isn't in `completed` until its own `processFile` resolves), failed-file-bumps-counter-past-itself (failures don't add to `completed`), and sort-flip-drops-newest-N-on-cross-version-resume (order is not part of the checkpoint). Old positional checkpoints are detected and discarded with a stderr line on first resume (re-walking is cheap because `content_hash` short-circuits unchanged files). Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the resume checkpoint stays dir-relative per `resumeFilter`'s contract). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — returned per-file failures (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped` and `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for Git repositories, so the JSON failure list remains a non-Git caller's per-file channel. Pinned by `test/import-json-stdout.serial.test.ts`.
+- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with the path-set checkpoint. `runImport` contains NO `process.exit`: all five preflight/argv failure sites (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target) throw the exported typed `ImportAbortError` (carries `exitCode`; the user-facing message is printed at the throw site), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.serial.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Uses a path-set checkpoint via `src/core/import-checkpoint.ts` (the walk still applies `sortNewestFirst()` for embed-cost ordering, but checkpoint correctness does not depend on sort order). A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. This rules out three failure classes: parallel-import-with-slow-worker dropping the slow file on crash-resume (the slow file isn't in `completed` until its own `processFile` resolves), failed-file-bumps-counter-past-itself (failures don't add to `completed`), and sort-flip-drops-newest-N-on-cross-version-resume (order is not part of the checkpoint). Old positional checkpoints are detected and discarded with a stderr line on first resume (re-walking is cheap because `content_hash` short-circuits unchanged files). Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the resume checkpoint stays dir-relative per `resumeFilter`'s contract). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.serial.test.ts`.
- `src/core/import-checkpoint.ts` — `loadCheckpoint(brainDir)`, `saveCheckpoint(brainDir, completed)`, `resumeFilter(files, completed, brainDir)`, `clearCheckpoint()`, plus the `ImportCheckpoint` type. Path-set format `{schema_version, brainDir, completed: string[]}`. Atomic write via `.tmp` + `rename()` so a mid-write crash never leaves a partial JSON. `loadCheckpoint` returns `null` on: missing file, malformed JSON, brainDir mismatch (ran against a different brain), and the old positional format (logged to stderr before discard). `resumeFilter` returns `{toProcess, skippedCount}` — pure, no I/O, deterministic. `clearCheckpoint` is no-op-on-missing for clean-exit cleanup. Honors `GBRAIN_HOME` via `gbrainPath()` so `withEnv({GBRAIN_HOME: tmpdir})` test isolation works without monkey-patching fs. Best-effort persistence — `saveCheckpoint` logs warnings on write errors but never throws.
- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).
- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit}`. `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.
- `src/commands/sources-set-path.ts` — `gbrain sources set-path <id> <path> [--force]`: non-destructive `local_path` repair (a DB pointer update, never touches files on disk). Loud rejection on a missing source (never a silent 0-row UPDATE); prints the prior value before changing it so the change is visible/reversible; absolutizes relative paths + normalizes MSYS/Git-Bash drive spellings BEFORE the existence check and the UPDATE (storing `.` verbatim would plant the phantom-path class this command exists to fix). Enforces the shared `assertNoOverlappingPath` guard (`src/core/sources-ops.ts`) before the UPDATE — a repointed source nesting inside or swallowing another source's tree exits 6 with the same `overlapping_path` wording `sources add` uses; `--force` bypasses it. Lives in its own module (like sources-demo.ts) so sources.ts stays under its ratchet ceiling. The `default_source_local_path` doctor check names this as the repair.
+- `src/commands/frontmatter-install-hook.ts` — `gbrain frontmatter install-hook [--source <id>] [--force] [--uninstall]`: writes the frontmatter pre-commit hook at `<git root>/.githooks/pre-commit` and sets `core.hooksPath` when unset. The root comes from `discoverGitRoot` (the same `git rev-parse --show-toplevel` walk `gbrain sync` uses, realpath'd on both sides), so a source registered as a SUBDIRECTORY of a host repo (bootstrap's `<workspace>/brain`) is accepted rather than skipped: the hook lands at the host root with `git diff --cached` limited to that subdirectory via shell-quoted git pathspecs, recorded as `# gbrain-scope: <dir>/` marker lines (one per guarded scope). The script lists staged paths with `-z | tr '\0' '\n'` and walks them in a `while IFS= read -r` loop fed by a heredoc (POSIX sh, no subshell), so names with spaces or non-ASCII characters are validated instead of silently skipped by word-splitting or git's `core.quotePath` quoting; a newline inside a filename is the one unsupported shape. One hook per root — nested sources union their scopes on install and drop only their own on uninstall (the last one removes the file); a root-registered source renders the unscoped script (no marker, byte-identical to the single-repo form) and owns the whole hook. A foreign `.githooks/pre-commit` still needs `--force` (`.bak` saved, restored on uninstall). Both install and uninstall resolve the hook location through `hookPaths(root)`, which lstat-refuses a symlinked `.githooks/` or `pre-commit` (a committed link in a host repo would redirect the write/chmod/rm elsewhere); the CLI prints the refusal as a `skipped` line and continues with the other sources. Only a path outside any repo is otherwise skipped. Every branch that leaves a hook on disk — fresh write, `--force` overwrite, or a byte-identical refresh — reaches the wiring step, because the hook FILE travels with the repo while `core.hooksPath` is per-clone config: a fresh clone of a repo that committed the hook reports `installed` (and gets wired) rather than `unchanged` while inert; `unchanged` means current AND wired. Before wiring `core.hooksPath`, `hooksPathBlocker(root)` returns the operator-facing reason wiring is unsafe, or null: a `core.hooksPath` already set (any scope — a global/corporate value counts; `--type=path`-expanded and resolved against the root) to anywhere that does not realpath to `.githooks` (theirs to keep; git never reads `.githooks/` then, so `installed` would lie — one that resolves to `.githooks` is left alone and counts as wired), a foreign executable under `.githooks/` (wiring would start running it — third-party clones commit hooks there) or an active hook in the repo's own hooks dir (`activeGitHooks` — executable non-`*.sample` entries under `<git rev-parse --git-common-dir>/hooks`, worktree-safe and, unlike `--git-path hooks`, immune to a foreign `core.hooksPath`; wiring would make git ignore `.git/hooks/*` for every hook type). Every git spawn in the module goes through one `git(root, args)` helper that passes `env: process.env` (Bun's default child env is a startup snapshot; Node's is live), so `GIT_CONFIG_*` overrides from `withEnv` reach the child. Any blocker returns `installed_unwired` — the hook is written, `core.hooksPath` stays untouched, and the CLI prints the reason + the manual `git config core.hooksPath .githooks` step. Pinned by `test/frontmatter-install-hook.test.ts`.
- `src/commands/reindex-frontmatter.ts` — `gbrain reindex-frontmatter`. `reindexFrontmatterCli(engine, args)` takes the ALREADY-CONNECTED engine from cli.ts's dispatch; it must never build/connect its own engine — a second connect on the same PGLite data dir self-deadlocks on the data-dir lock (this process already holds it). Same rule applies to `runBackfillCommand(engine, args)` in `src/commands/backfill.ts` and any future command dispatched from cli.ts's engine-connected switch. Pinned by `test/reindex-frontmatter-connect.test.ts` (library path) and `test/reindex-frontmatter-pglite-spawn.serial.test.ts` (CLI dispatch seam, both commands).
- `src/core/source-config-sql.ts` + `src/core/sources-load.ts` — canonical recovery for non-object `sources.config` values. The application reader unwraps nested JSON strings and merges recoverable array fragments left-to-right; the shared SQL expression mirrors that policy atomically for both engines, source config updates, archive/restore, and the paste-ready `source_config_shape` doctor repair. `localFederatedSourceIds` reads config through the same parser so stdio/CLI federation cannot silently disagree with `sources list`. `sourceConfigHasRemoteUrl` uses that parser for autopilot pull policy, including PGLite's JSON-string config shape. Invalid fragments degrade to `{}` rather than throwing. Pinned by `test/sources-load.test.ts`, `test/job-pull-policy.test.ts`, `test/list-all-sources.test.ts`, `test/local-federated-search-scope.test.ts`, `test/destructive-guard.test.ts`, and `test/doctor-source-config-shape.test.ts`.
- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `src/commands/sync.ts:1497-1519` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed), with `maybeWarnUnscopedDefaultWrite` as its warning-only projection; `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating.
-- `src/core/migrate.ts` — schema-migration runner. Owns the `MIGRATIONS` array (source of truth for schema DDL). `Migration` interface carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; mirror in pglite-schema.ts + schema.sql + bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). The dedup-index self-heal (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) is NOT version-gated: `runMigrations` invokes `repairTimelineDedupIndex` on every pass (including the no-pending early-return path) because a merge-renumbered migration can leave the version counter past the index change while the index stays the old shape. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice).
+- `src/core/migrate.ts` — schema-migration runner. Owns the `MIGRATIONS` array (source of truth for schema DDL). `Migration` interface carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; mirror in pglite-schema.ts + schema.sql + bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice).
- `src/cli.ts` — no-DB fallbacks announce themselves on stderr instead of degrading silently. `dream` dispatch binds the caught engine-connect error and emits `[dream] WARNING: could not connect to DB (...)` before falling through to filesystem-only phases; the `runDream(null, ...)` no-DB fallback is preserved (pinned by `test/cli-dream-engine-warn.test.ts`, 2 subprocess cases against good + bad DATABASE_URL). `doctor` dispatch does the same: when `connectEngine` OR the DB-backed `runDoctor` run throws, it emits `[doctor] DB-backed doctor run failed (...) — falling back to filesystem-only checks`, scrubbing the error message through BOTH `url-redact.ts:redactUrlsInText` and `redact-connection-info.ts:redactConnectionInfo` first, because doctor output is exactly what users paste into issues and CI logs (pinned by the fallback case in `test/doctor-minions-check.test.ts`: stderr note present, credentials absent, stdout stays parseable `--json`).
- `skills/conventions/brain-routing.md` — agent-facing convention skill documenting the canonical 6-tier source resolution chain (flag → env → dotfile → local_path → brain_default → seed_default) with paste-ready decision tables. Linked from CLAUDE.md's "Two organizational axes" section and from `gbrain sources current`'s hint output.
- `test/operations-trust-boundary.test.ts` + `scripts/check-operations-filter-bypass.sh` — operations trust-boundary contract coverage. Pure assertions over all 74 ops (every op has a scope annotation; every mutating op has a non-read scope; `localOnly: true` ops are excluded from `operations.filter(op => !op.localOnly)`; the seven sensitive localOnly ops snapshot-pinned by name) plus targeted handler-invocation guards for the HTTP-callable classes: `submit_job` with `name='shell'` + `ctx.remote=true` MUST reject (shell-job RCE); `search_by_image` with `image_path` + `ctx.remote=true` MUST reject (image leak); and the list-op read-leak class — `find_orphans`/`get_recent_salience`/`find_anomalies`/`find_experts` invoked with `ctx.remote=true` over a seeded `visibility: private` page MUST NOT return its slug/title, with a local positive control proving the assertions non-vacuous, count self-consistency assertions pinning the no-count-oracle posture (both orphan denominators shrink with hidden rows; `excluded` untouched; anomaly `count` mirrors the visible slug list), and a soft-delete re-probe pinning the includeDeleted fail-closed path. `file_upload` and `sync_brain` omitted from handler-invocation tests because they're `localOnly: true` (that path would test an impossible production scenario). The shell guard greps `src/` for any module importing the `operations` value outside the canonical filter site at `src/commands/serve-http.ts` (three import shapes: destructured, aliased, namespace), with an explicit 10-entry allow-list + a literal-string check that `serve-http.ts` still contains `operations.filter(op => !op.localOnly)`. Wired into `bun run verify`. Dynamic sibling: `test/remote-privacy-sweep.test.ts` (next entry) — same doctrine, corpus-seeded, catches leaks in ops neither curated list has heard of yet.
@@ -354,7 +358,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/minions/wait-for-completion.ts` — poll-until-terminal helper for CLI callers. `TimeoutError` does NOT cancel the job; `AbortSignal` exits without throwing. Default `pollMs`: 1000 on Postgres, 250 on PGLite inline.
- `src/core/minions/transcript.ts` — renders `subagent_messages` + `subagent_tool_executions` to markdown. Tool rows splice under their owning assistant `tool_use` by `(message_idx, tool_use_id)` — raw provider tool ids may repeat across turns, so `tool_use_id` alone is not an identity; echoed `tool_result` blocks check ownership against the nearest preceding assistant turn's key. UTF-8-safe truncation; unknown block types fall through to fenced JSON.
- `src/core/minions/plugin-loader.ts` — `GBRAIN_PLUGIN_PATH` discovery. Absolute paths only, left-wins collision, `gbrain.plugin.json` with `plugin_version: "gbrain-plugin-v1"`, plugins ship DEFS only (no new tools), `allowed_tools:` validated at load time against the derived registry.
-- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (13-name allow-list, size pinned by `test/brain-allowlist.serial.test.ts`). Attachment tools `file_list` and `file_url` are excluded. Registry construction and execution reject every `localOnly` operation; `selectAllowedTools` rejects malformed bindings and preserves explicit empty lists as no tools. Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trusted local jobs receive these from the submitter; remote-owned jobs receive the grant intersection plus `delegatedAuth`. Their per-call operation contexts carry current source grants and retain remote visibility policy, without requiring direct read/write scopes for independently bound delegated tools. `BuildBrainToolsOpts.deferEmbeds` (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads `OperationContext.deferEmbeds` so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param). `execute()` runs the same `validateParams` the MCP dispatchers use before the op handler, so a call that omits a required parameter (or sends the wrong type / an unknown enum value) fails with `<tool>: Missing required parameter: <name>` the model can act on, instead of a handler crash.
+- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (153-name allow-list, size pinned by `test/brain-allowlist.serial.test.ts`). Attachment tools `file_list` and `file_url` are excluded. Registry construction and execution reject every `localOnly` operation; `selectAllowedTools` rejects malformed bindings and preserves explicit empty lists as no tools. Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trusted local jombs receive these from `PROTECTED_JOB_NAMES` gating subagent submission (MCP cannot reach this field); only cycle.ts (synthesize/patterns) and direct CLI submitter; remote-owned jobs sreceive the grant intersection plus `delegatedAuth`. Their per-call operation contexts carry current source grants and retain remote visibility policy, without requiring direct read/write scopes for independently bound delegated tools. `BuildBrainToolsOpts.deferEmbeds` (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads `OperationContext.deferEmbeds` so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param). `execute()` runs the same `validateParams` the MCP dispatchers use before the op handler, so a call that omits a required parameter (or sends the wrong type / an unknown enum value) fails with `<tool>: Missing required parameter: <name>` the model can act on, instead of a handler crash. Under a slug allow-list, `put_page` content is checked by `pinUndeclaredType()` before the handler: an EXPLICIT frontmatter `type:` the active pack classifies as `undeclared` (`classifyStoredType`) is re-serialized as `type: note` with the model's type kept in `frontmatter.legacy_type` (the F5 oneshot pin extended to the tool-calling lanes; base-v2 D12 shape). Declared types, aliases, inferred types, the legacy `wiki/agents/<id>/` namespace and CLI/MCP `put_page` are untouched; no resolvable pack → no-op; never rejects (patterns children run `require_writes`). Runs before import so `content_hash` is computed once over the final type.
- `src/mcp/tool-defs.ts` — `buildToolDefs(ops, opts?)` helper; the stdio MCP server, the OAuth HTTP `tools/list`, and the subagent tool registry all consume it, byte-for-byte equivalence pinned by `test/mcp-tool-defs.test.ts`. `opts.strictParams: true` (when `mcp.strict_params` resolves `'reject'`) additionally declares the `_meta`/`dry_run` passthrough keys in `properties` and closes each schema with `additionalProperties: false` (schema-validating clients must not strip `_meta.session_id`); both emission states pinned. Exports the recursive `paramDefToSchema(p: ParamDef)` — single source of truth for ParamDef→JSON Schema mapping shared by `buildToolDefs` and `src/core/minions/tools/brain-allowlist.ts` (subagent registry). Recursive on `items` so nested array-of-arrays preserves inner shape on the wire. Key ordering (type, description, enum, default, items) is intentional so `JSON.stringify` output stays byte-stable. `test/mcp-tool-defs.test.ts` has a `findArrayWithoutItems` walker that fails on any `type: 'array'` lacking `items.type`.
- `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 fifth verb is the extended `recall` op in operations.ts. 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/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote})`: the zero-LLM sub-100ms card behind the `entity` verb. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, canonical entity types (`person`, `company`, `organization`, `entity`) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only-when-remote); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints.
@@ -362,12 +366,12 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.
- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + forgetFactInFence(old) + superseded_by link; DB path: engine insertFact supersedeId). Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug.
- `src/core/facts/forget.ts` — `forgetFactInFence(engine, id, {reason?, sourceId?, worldOnly?})` checks source and visibility before inspecting state, then commits a durable withdrawal through `facts/withdrawal.ts`. A writable source fence is atomically struck with a date and reason; otherwise the DB-body mirror is best-effort. Both paths remain withdrawn on stale reimport while the withdrawal database is preserved. The file resolver and per-page lock match fence writes. The body-only mirror deliberately leaves a hash mismatch so the next import re-chunks. Forget is retraction, not deletion of original prose, files or backups. Pinned by `test/forget-reconcile-durability.test.ts`, `test/privacy-strip-and-forget.test.ts`, and `test/e2e/delegated-grants-withdrawal.test.ts`.
+- `src/core/facts/extract.ts` — the LLM facts extractor (`extractFactsFromTurnWithOutcome` and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). Deterministic junk gate: `isJunkFact(text, kind?)` tests `JUNK_FACT_PATTERNS` — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified `commitment` is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is the surface shape of a genuine commitment, the one kind the loop engine exists to capture); meta-narration and provider-error strings are junk for every kind. `isJunkFilterEnabled(engine)` is the config kill switch (fail-open on a config read error); `getFactsExtractionPromptAppendix` supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become `entity_slug`): `isUnknownSpeakerLabel` (anonymous diarizer labels — `Speaker A`, `SPEAKER_00`, `spk_0`, `other|unknown|guest`) and `isNullLikeEntity` (placeholder STRINGS `"null"`/`"None"`/`"n/a"` where the prompt asked for JSON null; shared with `write-single.ts`) both null the attribution and KEEP the fact, so no consumer (`runFactsPipeline`, `extract-conversation-facts`) can mint `entity_slug='null'` through the resolver's fallback-slugify floor. The provider-error arm is start-anchored (`^\W*`, optional error/status token or a `<step> stopped|failed because …` prefix, then `(spend|rate) (limit|cap) … (hit|exceeded|reached)`), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: `facts.extraction_prompt_appendix` (non-empty text is appended to the extraction prompt, so an operator can steer what counts as a fact without a release) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on). Every extractor `chat()` call (first attempt, the #2113 truncation retry, the malformed-output retry) carries `responseSchema: FACTS_EXTRACTION_SCHEMA` (mirrors `RawExtracted`: `facts[]` of `{fact, kind ∈ ALL_EXTRACT_KINDS}` plus `entity/confidence/notability/metric/value/unit/period` — EVERY property in `required`, the optional ones nullable via type unions, `additionalProperties: false` at both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's default `strict: true`); the gateway honors it only on openai-compatible recipes that declare structured outputs (Ollama's server-side grammar), so small local models cannot emit malformed JSON, while `parseExtractorJsonDetailed` still validates the reply text on every lane. Pinned by `test/facts-extract-structured-output.test.ts`.
- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` — durable withdrawal key is `(source_id, visibility, SHA256(normalized claim))`; entity/page names are excluded so rename and index recreation do not restore it. Normalization folds case and whitespace, not meaning. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import overlays valid matching fence rows as struck before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim before embedding, using the protocol error envelope. Ordinary TTL/supersession expiry creates no withdrawal. Migration backfill only trusts explicit `forgotten:` markers; old unmarked DB-only intent cannot be inferred. Markdown-only copies do not preserve DB-only withdrawals.
- `src/core/minions/delegated-policy.ts` — immutable submitted grant ceiling intersected with the current OAuth grant. Tools, explicit operation authority, source-only reads, write prefixes, concurrency and finite budget may narrow but never widen during execution; changed source/brain, revoked clients, archived sources or unusable intersections fail closed. Explicit job namespaces resolve to `wiki/agents/<job-id>/*`. Removing `submit_agent` stops the next execution boundary; explicit operation allowlists also constrain delegated tools, while legacy null operation lists preserve separately bound agent-only tools. Surface controls transport discovery. Empty tools never mean all tools. Legacy running jobs adopt the ceiling frozen in their persisted payload by grant rescope; host/current brain aliases mean the serving brain.
- `src/core/minions/delegated-admission.ts` + `delegated-tools.ts` — queue admission locks the client row through validation, idempotency/coalescing, counting all nonterminal owned jobs across queues, and insertion. Returning an identical existing job adds no slot. Every delegated tool execution, including replay and one-shot writes, rechecks the current intersection and rebuilds the operation context with its current source/path bounds and authenticated read-source ceiling, including explicit per-call source overrides. Remote-owned writes cannot overwrite private existing pages (including dedup redirects), append their timeline, or run trusted-workspace auto-link/timeline hooks. One-shot remote-owned writes keep links as literal text without probing hidden target existence or counts; trusted local behavior is preserved. Trusted owner fields are separate from user parameters. Replay cannot replace identity or original bounds; valid owned replays and terminal-job retries consume a slot under the same client lock. Legacy terminal jobs missing a stored ceiling require fresh authenticated submission.
- `src/core/minions/delegated-spend.ts` + `src/core/ai/invocation-guard.ts` + `guarded-generation.ts` — async-local admission around each owned provider attempt, including nested paid tool work; unrelated local calls retain their transport behavior. Finite caps require canonical pricing and a declared input ceiling plus enforced output maximum before IO; unknown pricing/bounds refuse. Hidden SDK retries are disabled for owned attempts. Actual reported usage is settled with cache categories normalized across SDK/raw responses; absent usage remains explicit unresolved liability. The current grant is checked again under the reservation's client lock.
- `src/core/minions/budget-meter.ts` — atomic reserve/settle accounting. Per-client advisory lock plus client row lock protects current cap and outstanding holds. NULL cap means unlimited; a caller's existing finite ceiling still applies. Pending and expired unresolved holds count across UTC dates; TTL marks overdue rather than releasing liability. Unknown-bound holds prevent subsequent finite admission until reconciled. Settlement is idempotent and writes reservation state plus spend log in one transaction. Tests cover races, changed caps, unknown usage, late settlement and both engines.
-- `src/core/facts/extract.ts` — the LLM facts extractor (`extractFactsFromTurnWithOutcome` and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). Deterministic junk gate: `isJunkFact(text, kind?)` tests `JUNK_FACT_PATTERNS` — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified `commitment` is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is the surface shape of a genuine commitment, the one kind the loop engine exists to capture); meta-narration and provider-error strings are junk for every kind. `isJunkFilterEnabled(engine)` is the config kill switch (fail-open on a config read error); `getFactsExtractionPromptAppendix` supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become `entity_slug`): `isUnknownSpeakerLabel` (anonymous diarizer labels — `Speaker A`, `SPEAKER_00`, `spk_0`, `other|unknown|guest`) and `isNullLikeEntity` (placeholder STRINGS `"null"`/`"None"`/`"n/a"` where the prompt asked for JSON null; shared with `write-single.ts`) both null the attribution and KEEP the fact, so no consumer (`runFactsPipeline`, `extract-conversation-facts`) can mint `entity_slug='null'` through the resolver's fallback-slugify floor. The provider-error arm is start-anchored (`^\W*`, optional error/status token or a `<step> stopped|failed because …` prefix, then `(spend|rate) (limit|cap) … (hit|exceeded|reached)`), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: `facts.extraction_prompt_appendix` (non-empty text is appended to the extraction prompt, so an operator can steer what counts as a fact without a release) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on).
- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'starter'` (the ~27-op daily-driver set) | `'full'` (default — identity; existing installs unchanged). `STARTER_OPS` is composed PROGRAMMATICALLY: a spread of `VERB_NAMES` (never a hand-count) + the fallback daily slice (`BRAIN_TOOL_ALLOWLIST` + the agent lane `submit_agent`/`get_agent_job`) + `whoami` + `request_tools` + `capture` (a DIRECT literal, deliberately NOT via the allowlist); re-derived from production usage via `scripts/derive-starter-ops.ts` (paste-in proposal, never an auto-edit). `ALWAYS_INCLUDED_STARTER_OPS` (verbs + `whoami` + `request_tools` + the agent lane + `capture`) is the exported always-set consumed by BOTH `derive-starter-ops.ts` and the advisor starter-fit collector, so neither re-types the composition. `parseSurfaceFlag` (strict, loud reject), `resolveSurface` (flag > config `mcp_surface` > full), `filterOpsForSurface`, `allowedOpNames`. Enforcement is TWO-layer and fail-closed: the advertised list AND `dispatchToolCall`'s `allowedOps` set (a hidden op returns `unknown_tool` even when called by name) — applied on stdio (server.ts) and BOTH HTTP paths (serve-http.ts after `!localOnly`, and the second transport http-transport.ts). Per-client ceiling machinery (OAuth transport only): `effectiveSurfaceForClient` is the pure composition `clamp(min(server ceiling, client row surface ?? mcp.default_surface_dcr ?? ceiling))`; the per-REQUEST application lives in serve-http.ts's `resolveEffectiveSurface`, which short-circuits a `verbs` ceiling (min() cannot go lower, so the config read is skipped) and, on a default-surface read failure, applies the LAST successfully read default (held per process, fail-closed) so a transient config outage cannot silently widen a NULL-surface client to the ceiling; `resolveClientRowSurface` ignores unknown row values with a bounded warn-once (the column's value space is documented OPEN for future tier names); `resolveDefaultClientSurface` reads the DCR default dual-plane (DB > file > null) and never throws; `clampSurface`/`readForceSurfaceEnv` fold in the `GBRAIN_MCP_FORCE_SURFACE` kill switch — NARROW-ONLY by construction (min(); can never widen past the ceiling). `minSurface`/`surfaceWiderThan` own the verbs < starter < full rank math. Pinned by test/mcp-surface.test.ts (membership, monotonicity verbs ⊆ starter ⊆ full, ceiling + force-narrow cases).
- `src/commands/protocol.ts` — `gbrain protocol [--json] | conformance [--target <http-url|stdio-cmd>] [--token] [--synthesize] | stats [--days N]`. `--json` emits input schemas from the LIVE Operation defs + RESPONSE_SCHEMAS (doc/code can't drift). Conformance default target self-spawns gbrain's own stdio server (dev `.ts` entry vs compiled binary both handled); CI certifies stdio with --synthesize (no key ⇒ asserts the clean `unavailable` error). Stats aggregates the usage sidecar + the measured TTHW; output states "local JSONL only — never uploaded". CLI_ONLY + SELF_HELP wired in cli.ts; no pre-bound engine.
- `src/core/minions/attachments.ts` — Attachment validation (path traversal, null byte, oversize, base64, duplicate detection).
@@ -389,12 +393,12 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/mcp-usage.ts` — `readClientOpUsage(engine, {days})`: the ONE shared reader over `mcp_request_log`, consumed by `gbrain auth clients --usage`, the advisor `mcp-client-fit` collector, and `scripts/derive-starter-ops.ts`. Encodes the row-hygiene rules once (`normalizeLoggedOperation`): JSON-RPC method rows (`tools/list`, `initialize`, …) and `surface_change` audit rows drop; the legacy `tools/call:<name>` prefix strips to the op name, and the hygiene check re-runs on the stripped name (`tools/call:tools/list` is still not an op call). Only `status IN ('success','success_with_warnings')` rows count as usage — denied or erroring traffic cannot "use" its way into starter derivation or advisor fit findings. Windows on `created_at` (rides `idx_mcp_log_time_agent`); plain SQL through `engine.executeRaw`, both engines. Behavioral automation classification: `likely_automation` = >90% of calls are `context_pack`/`delta` boundary verbs (the hook lane is stdio and never logs, so there is no name convention to key on). Sees HTTP clients ONLY — stdio never writes the log. Pinned by test/mcp-usage.test.ts.
- `docs/protocol/MCP_META_CHANNELS.md` — normative `_meta` conventions for MCP tool responses: one producer per top-level key, additive-forever within a key, producer isolation, and the registered-keys table (`brain_hot_memory`, `retrieval`, `warnings`). Anything the model must SEE rides a content block (mainstream harnesses don't feed `_meta` to the model); `_meta` serves structured consumers. Add a key by registering it in the table — one producer, additive-forever.
- `src/mcp/rate-limit.ts` — Bounded-LRU token-bucket limiter. `buildDefaultLimiters()` returns the two-bucket pipeline: pre-auth IP (30/60s, fires BEFORE the DB lookup so brute-force load against `access_tokens` is capped) + post-auth token-id (60/60s). Tracks `lastTouchedMs` separately from `lastRefillMs` so an exhausted key can't be reset by hammering past the TTL. LRU cap bounds memory under attacker-controlled key growth. `refund(key)` returns one consumed token (capped at the limit) — the `request_tools` persist path refunds when a race-lost 0-row UPDATE (concurrent operator pin) means no write actually happened; dry-run previews never draw a token at all (the limiter meters actual writes only).
-- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. The legacy `POST /ingest` queue refuses operation-snapshot clients; they use approved MCP writes so execution stays inside the shared grant contract. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and `express-rate-limit` at 50 req / 15 min on `/token`. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard would see a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(engine, engineName, version, timeoutMs)` racing `engine.executeRaw('SELECT 1', undefined, { signal })` against the exported `HEALTH_TIMEOUT_MS = 3000`; when the timeout wins, an `AbortController` cancels the Postgres query (PGLite can only discard its eventual result) before the same tagged `ProbeHealthResult` 503 envelope is returned (single timer-cleanup site); body shape `{status, version, engine}` only. Full stats live at admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. OAuth/admin/audit SQL outside the abortable liveness probe routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page inside its granted source). The write source is resolved server-side as `authInfo.sourceId ?? 'default'` and travels on the job as `job.data.sourceId`; the caller-supplied `X-Gbrain-Source-Id` header routes nothing and only names the emitter (`webhook-<clientId>`), which is what the event's `source_id` and the 202's back-compat `source_id` field carry. The 202 additionally reports the routed destination as `write_source_id`, and the resolved write source joins the queue idempotency key so a rescoped client lands a new capture instead of deduping against its old job. confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the honest catalog: per-request filters (token scope incl. the `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count`. Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client). OAuth protected-resource metadata (RFC 9728) names `/mcp` as the resource (`resourceServerUrl`), so the SDK mounts the PRM at `/.well-known/oauth-protected-resource/mcp` and the 401 `resource_metadata` URL is derived from the same value; the bare root path is kept as an alias by rewriting `req.url` onto the SDK's handler (same document, same CORS).
-- `src/core/sql-query.ts` — engine-aware tagged-template SQL adapter for OAuth/admin/auth infrastructure. `sqlQueryForEngine(engine)` returns a `SqlQuery` (`(strings, ...values) => Promise<rows[]>`) that walks the template, builds `$N` positional SQL, asserts every value is a `SqlValue` (string | number | bigint | boolean | Date | null), and routes through `engine.executeRaw(sql, params)` (Postgres via postgres.js `unsafe(sql, params)`, PGLite via `db.query(sql, params)`). Deliberately narrower than postgres.js's `sql` tag: no nested fragments, `sql.json()`, `sql.unsafe()`, `sql.begin()`, or array binding — the narrow scalar-only surface is the feature (keeps it from drifting into a partial postgres.js clone). JSONB writes go through `executeRawJsonb(engine, sql, scalarParams, jsonbParams)` which composes positional `$N::jsonb` casts and passes JS **objects** through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified by `test/sql-query.test.ts` on PGLite, `test/e2e/auth-permissions.test.ts:67` on Postgres). Positional binding is NOT universally immune, though: binding a `JSON.stringify(x)` **string** to a bare `$N::jsonb` via `unsafe()` double-encodes it into a jsonb string scalar on real Postgres (PGLite hides it). Fixes: pass a raw object (executeRawJsonb / `sql.json`), or cast through `$N::text::jsonb`. `scripts/check-jsonb-pattern.sh` (template grep) doesn't fire on `executeRawJsonb(...)` because it passes objects; the positional `$N::jsonb` + `JSON.stringify` form is caught by `scripts/check-jsonb-params.mjs`. Consumed by `src/commands/auth.ts`, `src/commands/serve-http.ts`, `src/core/oauth-provider.ts`, `src/commands/files.ts`, `src/mcp/http-transport.ts` so all five work uniformly against PGLite and Postgres.
-- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`). Both stdin activity listeners (the default-on idle sweep and the opt-in `--stdio-idle-timeout`) attach only AFTER the MCP SDK transport's own stdin listener — the sweep on its first interval tick, the idle timeout through the activator `installStdioLifecycle` returns, which `runServe` invokes once `startMcpServer` resolves (and which re-arms the countdown so boot time does not eat into the idle window) — so neither can flip stdin into flowing mode and consume a fast client's initialize frame before the SDK sees it. Pinned by `test/serve-stdio-lifecycle.test.ts` (22 cases).
+- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. The legacy `POST /ingest` queue refuses operation-snapshot clients; they use approved MCP writes so execution stays inside the shared grant contract. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and `express-rate-limit` at 50 req / 15 min on `/token`. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard would see a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(engine, engineName, version, timeoutMs)` racing `engine.executeRaw('SELECT 1', undefined, { signal })` against the exported `HEALTH_TIMEOUT_MS = 3000`; when the timeout wins, an `AbortController` cancels the Postgres query (PGLite can only discard its eventual result) before the same tagged `ProbeHealthResult` 503 envelope is returned (single timer-cleanup site); body shape `{status, version, engine}` only. Full stats live at admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. OAuth/admin/audit SQL outside the abortable liveness probe routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page inside its granted source). The write source is resolved server-side as `authInfo.sourceId ?? 'default'` and travels on the job as `job.data.sourceId`; the caller-supplied `X-Gbrain-Source-Id` header routes nothing and only names the emitter (`webhook-<clientId>`), which is what the event's `source_id` and the 202's back-compat `source_id` field carry. The 202 additionally reports the routed destination as `write_source_id`, and the resolved write source joins the queue idempotency key so a rescoped client lands a new capture instead of deduping against its old job. confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the honest catalog: per-request filters (token scope incl. the `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count`. Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client). OAuth protected-resource metadata (RFC 9728) names `/mcp` as the resource (`resourceServerUrl`), so the SDK mounts the PRM at `/.well-known/oauth-protected-resource/mcp` and the 401 `resource_metadata` URL is derived from the same value; the bare root path is kept as an alias by rewriting `req.url` onto the SDK's handler (same document, same CORS). Shutdown: `waitForHttpServerLifecycle` tracks accepted sockets weakly (`trackServerSockets`; Bun never emits socket `close`, so a strong set leaked one per request), severs the still-reachable ones right after `server.close()`, and bounds the close wait at `CLOSE_TIMEOUT_MS` (5s) — a collected keep-alive wrapper whose native handle keeps `close()` from returning gets one stderr line and shutdown proceeds instead of hanging.
+- `src/core/sql-query.ts` — engine-aware tagged-template SQL adapter for OAuth/admin/auth infrastructure. `sqlQueryForEngine(engine)` returns a `SqlQuery` (`(strings, ...values) => Promise<rows[]>`) that walks the template, builds `$N` positional SQL, asserts every value is a `SqlValue` (string | number | bigint | boolean | Date | null), and routes through `engine.executeRaw(sql, params)` (Postgres via postgres.js `unsafe(sql, params)`, PGLite via `db.query(sql, params)`). Deliberately narrower than postgres.js's `sql` tag: no nested fragments, `sql.json()`, `sql.unsafe()`, `sql.begin()`, or array binding — the narrow scalar-only surface is the feature (keeps it from drifting into a partial postgres.js clone). JSONB writes go through `executeRawJsonb(engine, sql, scalarParams, jsonbParams)` which composes positional `$N::jsonb` casts and passes JS **objects** through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified by `test/sql-query.test.ts` on PGLite, `test/e2e/auth-permissions.test.ts:67` on Postgres). Positional binding is NOT universally immune, though: binding a `JSON.stringify(x)` **string** to a bare `$N::jsonb` via `unsafe()` double-encodes it into a jsonb string scalar on real Postgres (PGLite hides it). Fixes: pass a raw object (executeRawJsonb / `sql.json`), or cast through `$N::text::jsonb`. `scripts/check-jsonb-pattern.sh` (template grep) doesn't fire on `executeRawJsonb(...)` because it passes objects; the positional `$N::jsonb` + `JSON.stringify` form is caught by `scripts/check-jsonb-params.mjs`. Also exports `FILES_METADATA_MERGE_SQL`, the one `ON CONFLICT (storage_path)` merge fragment every files upsert (`src/commands/files.ts` x4, `src/core/ops/files.ts` `file_upload`) interpolates: it resets a non-object `files.metadata` to `{}` before the jsonb `||` merge, because `||` array-wraps a non-object left operand and would turn a legacy string-scalar row into `["{}", {...}]` that `gbrain repair-jsonb` can no longer see (pinned by `test/file-upload-fail-closed.test.ts`). Consumed by `src/commands/auth.ts`, `src/commands/serve-http.ts`, `src/core/oauth-provider.ts`, `src/commands/files.ts`, `src/mcp/http-transport.ts` so all five work uniformly against PGLite and Postgres.
+- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`); it targets the source `resolveMcpStdioSourceScope` resolves (GBRAIN_SOURCE > `.gbrain-source` dotfile > local_path > `sources.default` > …) — the SAME ladder as stdio dispatch and the startup sweep, so dotfile/local_path-scoped serves reconcile their in-session MCP writes (pinned by `test/serve-idle-sweep-source.serial.test.ts`). Both stdin activity listeners (the default-on idle sweep and the opt-in `--stdio-idle-timeout`) attach only AFTER the MCP SDK transport's own stdin listener — the sweep on its first interval tick, the idle timeout through the activator `installStdioLifecycle` returns, which `runServe` invokes once `startMcpServer` resolves (and which re-arms the countdown so boot time does not eat into the idle window) — so neither can flip stdin into flowing mode and consume a fast client's initialize frame before the SDK sees it. Pinned by `test/serve-stdio-lifecycle.test.ts` (22 cases).
+- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Owner-approved authorization codes have a 10-minute TTL. Grant transactions lock the active client row before consuming codes or refresh tokens and creating replacements; revocation uses the same lock. Provider-side S256 PKCE validation is mandatory (`skipLocalPkceValidation=true` prevents the SDK from discarding the verifier first). Existing active-client grants remain usable. `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and threads BOTH stored grants off the token's `permissions` JSONB: `source_id` via `parseLegacyTokenScope` and `takes_holders` via `parseTakesHoldersAllowList` (both in `src/core/legacy-token-scope.ts`, shared with the legacy HTTP transport so the two transports cannot drift; `[]` takes-holders preserved as explicit deny-all, missing/non-array → undefined → the `/mcp` dispatch site's fail-closed `['world']`; OAuth-client tokens carry no takes-holders grant pending per-client storage — TODOS.md). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`).
- `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, and unlimited delegated spend. `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit).
- `src/commands/serve-http-grants.ts` + `admin/src/components/ClientGrant.tsx` — typed admin grant request validation and shared profile/advanced permission editor. Register/rescope/TTL routes in `serve-http.ts` use canonical grant validation and audit; legacy response shapes remain available. New UI creation defaults to memory-writer and requires a preview, while edits carry the displayed revision and require a fresh preview after any field change or conflict. Detail/catalog endpoints expose non-secret grants and the shared harness registry. Operation authority snapshots, source sets, delegated tools/namespaces, spend, concurrency, and future TTL are independently reviewable; profile regrant is explicit. `admin/src/pages/Agents.tsx` downloads the private `HarnessCredentials` handoff and links current harness guides instead of maintaining native config snippets. Rebuild committed `admin/dist` and `src/admin-embedded.ts` after SPA edits.
-- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Owner-approved authorization codes have a 10-minute TTL. Grant transactions lock the active client row before consuming codes or refresh tokens and creating replacements; revocation uses the same lock. Provider-side S256 PKCE validation is mandatory (`skipLocalPkceValidation=true` prevents the SDK from discarding the verifier first). Existing active-client grants remain usable. `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and threads BOTH stored grants off the token's `permissions` JSONB: `source_id` via `parseLegacyTokenScope` and `takes_holders` via `parseTakesHoldersAllowList` (both in `src/core/legacy-token-scope.ts`, shared with the legacy HTTP transport so the two transports cannot drift; `[]` takes-holders preserved as explicit deny-all, missing/non-array → undefined → the `/mcp` dispatch site's fail-closed `['world']`; OAuth-client tokens carry no takes-holders grant pending per-client storage — TODOS.md). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`).
- `admin/` — React 19 + Vite + TypeScript admin SPA embedded in the binary via `admin/dist/` served by `serve-http.ts`. 7 screens: Login (bootstrap token → session cookie), Dashboard (metrics + SSE feed + token health), Agents (sortable table + sparklines + Register), Register (modal with scope checkboxes + grant type selector), Credentials reveal (Copy + Download JSON + one-time-only warning), Request Log (filterable paginated), Agent Detail drawer (Details / Activity / Config Export tabs + Revoke). Design tokens: `#0a0a0f` bg, Inter for UI, JetBrains Mono for data, 4-32px spacing scale, rounded pill badges. HTTP-only SameSite=Strict cookie auth. 65KB gzip. Build: `cd admin && bun install && bun run build`; output at `admin/dist/` is committed for self-contained binaries.
- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), and federated reads (`federated_read`) — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`.
- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.
@@ -409,20 +413,21 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/whoknows.ts` — `gbrain whoknows <topic>` and MCP `find_experts`: expertise and relationship routing. `findExperts()` threads source, page-privacy and holder policy through hybrid retrieval and enrichment, then requires an authorized effective-date read after optional salience work for every caller, including trusted local callers. Candidates absent from that exact `(source_id, slug)` map are omitted; required admission failures propagate. Optional salience failures retain the existing neutral factor. `rankCandidates()` uses `score = log(1 + raw_match) × max(0.1, exp(-days/180)) × (0.5 + 0.5 × salience)`, with salience normalized before ranking and alphabetical slug tie-breaking. Hybrid salience/recency boosts are disabled here to avoid applying them twice. Expert types are filtered in SQL and resolved from the pack by `ops/insights.ts`; a failed pack load supplies an empty type list. CLI supports `--explain`, `--limit`, `--json` and thin-client routing. Math is pinned by `test/whoknows.test.ts`; exact final admission, mutation races and SQL-failure behavior run on both engines in `test/e2e/read-enrichment-privacy.test.ts`.
- `src/commands/eval-whoknows.ts` — `gbrain eval whoknows <fixture.jsonl> [--json] [--skip-replay]`: two-layer eval gate. Layer 1 quality (hand-labeled fixture, top-3 hit rate ≥ 0.8). Layer 2 regression (`eval_candidates` replay set-Jaccard@3 ≥ 0.4). Sparseness fallback: < 20 replay-eligible rows → Layer 2 auto-skips with stderr warning. Stable JSON envelope with `schema_version: 1`; exit 0/1/2 for pass/fail/usage. `WhoknowsFn` callable abstraction makes the gates impl-agnostic; `runEvalWhoknows(engine: BrainEngine | null, args)` picks the impl at entry — thin-client mode (`isThinClient(cfg)`) routes per-query through `callRemoteTool(cfg, 'find_experts', {topic, limit})`, local mode calls `findExperts(engine, ...)` directly. cli.ts adds a thin-client bypass before `connectEngine` (dispatch shape under `src/commands/eval.ts`); the regression gate auto-skips in thin-client mode (no DB access to `eval_candidates`). Public exports `jaccardAtK`, `topKHit`, `readFixture`, `WhoknowsFn`, threshold constants pinned by `test/eval-whoknows.test.ts` (25 cases incl. null-engine signature contract).
- `test/fixtures/whoknows-eval.jsonl` — 10-row synthetic placeholder demonstrating the eval-fixture schema (`{query, expected_top_3_slugs, notes?}` JSONL). End users replace with their own real queries; placeholder uses obviously-example slugs (`wiki/people/example-alice`). Drives `test/e2e/whoknows.test.ts` (seeds a matching synthetic brain, asserts the >=80% gate) and the `whoknows_health` doctor check.
-- `src/core/skillopt/` + `src/commands/skillopt.ts` + `skills/skill-optimizer/` — self-evolving skill optimization grounded in the SkillOpt paper (arXiv 2605.23904). `gbrain skillopt <skill>` treats `SKILL.md` as trainable parameters of a frozen agent: validation-gated (median-of-3 + epsilon=0.05), budget-capped (preflight estimator), per-skill DB-locked (`tryAcquireDbLock('skillopt:<name>', 60min)`), atomic-versioned (history-intent-first 5-step commit), body-only mutations (frontmatter forbidden). Rollouts use `gateway.toolLoop` directly with no-op persistence callbacks (zero `subagent_messages` pollution) + a read-only tool allowlist derived from `BRAIN_TOOL_ALLOWLIST` minus `put_page`/`submit_job`/`file_upload`. Two reflect calls per step; rejected-edit buffer LRU-bounded to 100; bundled-skill gate; bootstrap workflow (sentinel + `--bootstrap-reviewed`); D_sel floor (>=5 with `--split` override); audit JSONL via `audit-writer.ts`. Added to `ALL_PHASES` after `patterns` (default OFF; opt-in via `gbrain config set cycle.skillopt.enabled true`); cycle phase wrapper at `src/core/skillopt/cycle-phase.ts` walks stale skills with per-skill ($0.50) + brain-wide ($2.00) caps. Added to `PROTECTED_JOB_NAMES`. Surface: dream-cycle phase wrapper; `--all` batch mode (`src/core/skillopt/batch.ts:runBatchAll`); `--target-models` fleet (`runFleet` parallel per-model receipts under `skillopt/fleet/<slug>/`); MCP op `run_skillopt` (admin scope + per-skill `skillopt.allowed_skills` allowlist, NOT localOnly, validates `skill_name` kebab-only + confines caller-supplied benchmark/held-out paths to skillsDir for remote callers); Minion `skillopt` handler + `--background` with `allowProtectedSubmit: true`; write-flavored optimization via `src/core/skillopt/write-capture.ts:buildWriteCaptureRegistry` (virtual `put_page`/`submit_job`/`file_upload` captured in-memory; `--write-capture` flag); held-out real-user test set via `src/core/skillopt/held-out.ts` (capture infra at `~/.gbrain/skillopt-captures/<skill>/<run>.jsonl`, `--held-out <path>` flag, `runHeldOutGate` candidate >= baseline). Hermetic via DI seams (`opts.chatFn` for optimizer + judge; `opts.toolLoopFn` for rollouts; no `mock.module`). `--bootstrap-from-skill` → `runBootstrapFromSkill` in `src/core/skillopt/bootstrap-benchmark.ts`: reads `SKILL.md` directly (no `routing-eval.jsonl`), makes ONE LLM call emitting a full starter benchmark (tasks + rule judges) as JSONL, parsed line-by-line with skip-bad-line salvage and a min-2-valid-checks-per-task drop; provider/transport errors PROPAGATE (not collapsed to `bootstrap_empty`). `--bootstrap-tasks N` (default 15, capped 50); `maxTokens` scales `min(8000, max(4000, N*220))`. The stderr REVIEW line prints the literal `gbrain skillopt <name> --bootstrap-reviewed --split 1:1:1` — load-bearing because the default `4:1:5` split makes a 15-task starter's `D_sel = floor(15/10) = 1`, below the `>=5` floor, so a 15-task benchmark needs `--split 1:1:1`. Both bootstrap generators share `assertBenchmarkAbsent` + `readSkillBodyOrThrow`; `--bootstrap-from-skill` is mutually exclusive with `--bootstrap-from-routing`/`--benchmark`/`--all`/`--target-models`/`--resume`. Generated rule judges are explicitly WEAK DRAFTS to be strengthened during the review gate. The held-out gate is wired: `--held-out <path>` is parsed and threaded through every caller (CLI main + `--background` `held_out_path` + batch/fleet `heldOutPath` + the `run_skillopt` `held_out_path` param), running at CHECKPOINT ACCEPTANCE so no-mutate/fleet paths can't promote a held-out-failing candidate. `assertBundledMutationHeldOut` in bundled-skill-gate.ts: bundled + `--allow-mutate-bundled` requires a NON-EMPTY held-out (`MIN_HELD_OUT_SIZE = D_SEL_MIN_SIZE` = 5, derived so they can't desync) or hard-refuses (exit 2), for ALL callers (they funnel through `runSkillOpt`); held-out must be task_id-DISJOINT from the benchmark (overlap rejected — can't catch overfitting). `receipt.baseline_sel_score` populated + a real final-test eval (`test_score` + `baseline_test_score`) scoring best + baseline on `split.test`; shared `scoreSkillOnTasks` primitive (validate-gate.ts) backs baseline/final-test/held-out scoring. `--no-mutate` writes proposed.md via `writeProposed` in version-store.ts. `maxRuntimeMin` ENFORCED (wall-clock deadline between steps → `skillopt_runtime_exceeded` → outcome aborted). Three eval-internal ablation opts on `SkillOptOpts` (NOT on CLI): `reflectMode` (`'both'`/`'failure-only'`), `disableValidationGate` (greedy-accept), `optimizerMode` (`'reflect'`/`'one-shot-rewrite'`), recorded in `RunReceipt` + audit `run_start` for replayability; `ROLLOUT_SUCCESS_THRESHOLD = 0.5` named constant for the partition; one-shot fence-strip is anchored (`^```...```$`) so an embedded code sample isn't truncated. Claude Haiku 4.5's dateless canonical id `claude-haiku-4-5` is in `src/core/anthropic-pricing.ts` (a `BudgetTracker`-capped run on Haiku would otherwise throw `no_pricing` on the FIRST `chat()` of every rollout); `runValidationGate` (validate-gate.ts) scans settled results for `isMustAbortError(error)` (from `worker-pool.ts`; `BUDGET_EXHAUSTED` is in `MUST_ABORT_ERROR_TAGS`) and re-throws so the caller aborts loudly instead of recording a hollow `selScore:0` — ordinary non-abort rollout errors still fail-open to `score:0` (judge-hiccup posture preserved). Pinned by 152 tests across 18 files (foundation + adversarial + v2 surface + E2E PGLite serial), `test/skillopt/bootstrap-from-skill.test.ts` (20 cases), `test/skillopt/rollout.test.ts`, `test/skillopt/validate-gate-abort.test.ts` (3 cases), held-out ENFORCE + one-shot-rewrite unit cases, and e2e (held-out block/allow, bundled no-mutate, runtime deadline, receipt honesty, held-out disjointness, no-DB-pollution). Drives the Track B SkillOpt benchmark suite in the sibling `gbrain-evals` repo.
+- `src/core/skillopt/` + `src/commands/skillopt.ts` + `skills/skill-optimizer/` — self-evolving skill optimization grounded in the SkillOpt paper (arXiv 2605.23904). `gbrain skillopt <skill>` treats `SKILL.md` as trainable parameters of a frozen agent: validation-gated (median-of-3 + epsilon=0.05), budget-capped (preflight estimator), per-skill DB-locked (`tryAcquireDbLock('skillopt:<name>', 60min)`), atomic-versioned (history-intent-first 5-step commit), body-only mutations (frontmatter forbidden). Rollouts use `gateway.toolLoop` directly with no-op persistence callbacks (zero `subagent_messages` pollution) + a read-only tool allowlist derived from `BRAIN_TOOL_ALLOWLIST` minus `put_page`/`submit_job`/`file_upload`. Two reflect calls per step; rejected-edit buffer LRU-bounded to 100; bundled-skill gate; bootstrap workflow (sentinel + `--bootstrap-reviewed`); D_sel floor (>=5 with `--split` override); audit JSONL via `audit-writer.ts`. Added to `ALL_PHASES` after `patterns` (default OFF; opt-in via `gbrain config set cycle.skillopt.enabled true`); cycle phase wrapper at `src/core/skillopt/cycle-phase.ts` walks stale skills with per-skill ($0.50) + brain-wide ($2.00) caps. Added to `PROTECTED_JOB_NAMES`. Surface: dream-cycle phase wrapper; `--all` batch mode (`src/core/skillopt/batch.ts:runBatchAll`); `--target-models` fleet (`runFleet` parallel per-model receipts under `skillopt/fleet/<slug>/`); MCP op `run_skillopt` (admin scope + per-skill `skillopt.allowed_skills` allowlist, NOT localOnly, validates `skill_name` kebab-only + confines caller-supplied benchmark/held-out paths to skillsDir for remote callers); Minion `skillopt` handler + `--background` with `allowProtectedSubmit: true`; write-flavored optimization via `src/core/skillopt/write-capture.ts:buildWriteCaptureRegistry` (virtual `put_page`/`submit_job`/`file_upload` captured in-memory; `--write-capture` flag); held-out real-user test set via `src/core/skillopt/held-out.ts` (capture infra at `~/.gbrain/skillopt-captures/<skill>/<run>.jsonl`, `--held-out <path>` flag, `runHeldOutGate` candidate >= baseline). Hermetic via DI seams (`opts.chatFn` for optimizer + judge; `opts.toolLoopFn` for rollouts; no `mock.module`). `--bootstrap-from-skill` → `runBootstrapFromSkill` in `src/core/skillopt/bootstrap-benchmark.ts`: reads `SKILL.md` directly (no `routing-eval.jsonl`), makes ONE LLM call emitting a full starter benchmark (tasks + rule judges) as JSONL, parsed line-by-line with skip-bad-line salvage and a min-2-valid-checks-per-task drop; provider/transport errors PROPAGATE (not collapsed to `bootstrap_empty`). `--bootstrap-tasks N` (default 15, capped 50); `maxTokens` scales `min(8000, max(4000, N*220))`. The stderr REVIEW line prints the literal `gbrain skillopt <name> --bootstrap-reviewed --split 1:1:1` — load-bearing because the default `4:1:5` split makes a 15-task starter's `D_sel = floor(15/10) = 1`, below the `>=5` floor, so a 15-task benchmark needs `--split 1:1:1`. Both bootstrap generators share `assertBenchmarkAbsent` + `readSkillBodyOrThrow`; `--bootstrap-from-skill` is mutually exclusive with `--bootstrap-from-routing`/`--benchmark`/`--all`/`--target-models`/`--resume`. Generated rule judges are explicitly WEAK DRAFTS to be strengthened during the review gate. The held-out gate is wired: `--held-out <path>` is parsed and threaded through every caller (CLI main + `--background` `held_out_path` + batch/fleet `heldOutPath` + the `run_skillopt` `held_out_path` param), running at CHECKPOINT ACCEPTANCE so no-mutate/fleet paths can't promote a held-out-failing candidate. `assertBundledMutationHeldOut` in bundled-skill-gate.ts: bundled + `--allow-mutate-bundled` requires a NON-EMPTY held-out (`MIN_HELD_OUT_SIZE = D_SEL_MIN_SIZE` = 5, derived so they can't desync) or hard-refuses (exit 2), for ALL callers (they funnel through `runSkillOpt`); held-out must be task_id-DISJOINT from the benchmark (overlap rejected — can't catch overfitting). `receipt.baseline_sel_score` populated + a real final-test eval (`test_score` + `baseline_test_score`) scoring best + baseline on `split.test`; shared `scoreSkillOnTasks` primitive (validate-gate.ts) backs baseline/final-test/held-out scoring. `--no-mutate` writes proposed.md via `writeProposed` in version-store.ts. `maxRuntimeMin` ENFORCED (wall-clock deadline between steps → `skillopt_runtime_exceeded` → outcome aborted). Three eval-internal ablation opts on `SkillOptOpts` (NOT on CLI): `reflectMode` (`'both'`/`'failure-only'`), `disableValidationGate` (greedy-accept), `optimizerMode` (`'reflect'`/`'one-shot-rewrite'`), recorded in `RunReceipt` + audit `run_start` for replayability; `ROLLOUT_SUCCESS_THRESHOLD = 0.5` named constant for the partition; one-shot fence-strip is anchored (`^```...```$`) so an embedded code sample isn't truncated. Claude Haiku 4.5's dateless canonical id `claude-haiku-4-5` is in `src/core/anthropic-pricing.ts` (a `BudgetTracker`-capped run on Haiku would otherwise throw `no_pricing` on the FIRST `chat()` of every rollout); `runValidationGate` (validate-gate.ts) scans settled results for `isMustAbortError(error)` (from `worker-pool.ts`; `BUDGET_EXHAUSTED` is in `MUST_ABORT_ERROR_TAGS`) and re-throws so the caller aborts loudly instead of recording a hollow `selScore:0` — ordinary non-abort rollout errors still fail-open to `score:0` (judge-hiccup posture preserved), but a 100%-failed gate (every task errored — e.g. a logged-out `claude-cli` child — or every rollout carrying a `judge_error`) throws `skillopt_all_rollouts_failed` / `skillopt_all_judge_errors` (constants exported from validate-gate.ts) so a dead provider ends the run `errored` with the first provider message as `abort_detail` instead of a plausible `no_improvement` at 0.000; the orchestrator's zero-candidate step (reflect produced/parsed no edits) logs audit reason `no_edits_proposed[: <first reflect error>]` + one stderr line, distinct from the apply-rejected `no_edits_applied`, and does not touch the rejected buffer. `GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG=1` (empty config dir) logs the child out on every platform, macOS included — docs/comment make no keychain-survives claim (pinned by `test/skillopt/deadline-and-hermetic.test.ts`). Pinned by 152 tests across 18 files (foundation + adversarial + v2 surface + E2E PGLite serial), `test/skillopt/bootstrap-from-skill.test.ts` (20 cases), `test/skillopt/rollout.test.ts`, `test/skillopt/validate-gate-abort.test.ts` (7 cases), held-out ENFORCE + one-shot-rewrite unit cases, and e2e (held-out block/allow, bundled no-mutate, runtime deadline, receipt honesty, held-out disjointness, no-DB-pollution). Drives the Track B SkillOpt benchmark suite in the sibling `gbrain-evals` repo.
- `src/core/brainstorm/{domain-bank,orchestrator,judges}.ts` + `src/commands/{brainstorm,lsd,eval-brainstorm}.ts` + `src/core/last-retrieved.ts` — bisociation-grounded idea generation pair: `gbrain brainstorm <question>` (defensible, cite-heavy, 4 close × 6 far, judge threshold 4.0/5, save by default) and `gbrain lsd <question>` (Lateral Synaptic Drift — inverted judge rejecting ideas with resistance >4.5 "too obvious", stale-page bias via `pages.last_retrieved_at`, 2 close × 12 far, axiomatic inversions required, ephemeral by default). The "domain bank" is prefix-stratified sampling from the user's own brain (`SELECT DISTINCT substring(slug from '^[^/]+/[^/]+')` cached 1h-TTL in `config` per source) tiebroken by `JOIN page_links` connection_count, with corpus-sampling fallback when fewer prefixes than M exist. Distance normalized to [0,1] via `1 - clamp(cosine_distance, 0, 2) / 2`. `judges.ts` exports `runJudge(config, ideas)` + two configs (`BRAINSTORM_JUDGE_CONFIG` weighted originality/resistance/thesis_density/concrete_grounding/cognitive_load 0.25/0.20/0.20/0.20/0.15 vs `LSD_JUDGE_CONFIG` cognitive_load 0.50 + inversion rule). Calibration cold-start fallback: when `calibration_profiles.active_bias_tags` is empty, judge runs without anti-bias context AND stderr-warns. Op-layer write-back in `src/core/operations.ts` `search`/`query`/`get_page` handlers fires `bumpLastRetrievedAt(engine, pageIds)` (fire-and-forget, 5-min throttled via SQL clause, default-on with `search.track_retrieval` config escape hatch); internal callers (sync, migrations, dream cycle) bypass the op layer so the LSD stale signal stays clean. The fire-and-forget IIFE is tracked in a module-scoped `Set<Promise<unknown>>`; `awaitPendingLastRetrievedWrites(timeoutMs?: number): Promise<{outcome, pending}>` resolves once all tracked promises settle, bounded by a 5s `Promise.race` timeout that stderr-warns the pending count. `src/cli.ts` awaits the drain unconditionally for every op in the op-dispatch finally block BEFORE `engine.disconnect()`, then a fallback `process.exit(0)` fires ONLY when `outcome === 'timeout'` AND `shouldForceExitAfterMain(argv)` (excludes `serve` so daemons stay alive) — so the IIFE cannot race disconnect and leave PGLite's WASM keeping Bun's event loop alive. `pages.last_retrieved_at TIMESTAMPTZ NULL` has a full (NOT partial) B-tree index covering both NULL and range branches; full forward-reference bootstrap probe on both engines. Frontmatter `mode: lsd` makes the dream-cycle synthesize phase skip LSD output via `isLsdOutput()` in `src/core/cycle/transcript-discovery.ts` short-circuiting `isDreamOutput()`. `gbrain eval brainstorm <fixture.jsonl>` is a three-axis conjunctive gate (distance + usefulness + grounding — distance alone is gameable). `gbrain doctor` has a `brainstorm_health` check (migration applied, `search.track_retrieval` setting, calibration cold-start status). `judges.ts` computes the judge token budget via `computeJudgeMaxTokens(ideaCount, modelId)` (named constants `TOKEN_BUDGET_PER_IDEA`, `TOKEN_BUDGET_ENVELOPE`, `LEGACY_MIN_MAX_TOKENS`, `MAX_OUTPUT_TOKENS_CEIL`; `ANTHROPIC_OUTPUT_CAPS` map: Opus 4.7 32K, Sonnet 4.6 / Haiku 4.5 64K, legacy Claude 3.5 8K) so a large multi-call judge doesn't truncate mid-JSON; with no `modelOverride` the cap routes through the gateway's actual configured chat model via `getChatModel()`. `--save` for both commands persists through the canonical ingestion path: `persistSavedIdea(engine, {slug, content, provenanceVia})` calls `importFromContent({noEmbed:true, sourcePath})` (chunked + tagged + content_hash so search finds it, no embedding cost at save) THEN renders the saved row to disk via the shared `writePageThrough` helper (file rendered FROM the row so the two sinks can't diverge and `gbrain sync` doesn't churn it). `formatSaveOutcome(outcome, ctx)` returns an honest per-branch message (both-sinks, DB-only when no `sync.repo_path`/repo-not-a-dir, DB-saved-but-file-errored, total-failure → loud `save FAILED … NOT persisted` on stderr + nonzero exit) — `--save` never prints "Saved" when the DB write failed. `buildIdeaSlug(question, label, nonce?)` adds a random nonce suffix (injectable for tests) so two same-day runs sharing the first 60 slug chars don't clobber. `--json` callers stay DB-only. `buildBrainstormFrontmatterObject(result)` in orchestrator.ts returns the object form for `serializeMarkdown`. Pinned by `test/last-retrieved.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts` (IRON-RULE: real `bun src/cli.ts` subprocess against a hermetic PGLite tempdir asserts search/get/query exit 0 in <15s + daemon-survival), `test/fix-wave-structural.test.ts` (asserts the drain `await` is textually BEFORE `engine.disconnect`), `test/brainstorm/{distance,lsd-mode-skip,eval-brainstorm,judges-maxtokens,save}.test.ts`. Open Collider source: `github.com/CL-ML/open-collider`.
-- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId)` is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained `file://` `source_uri`) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention (GIT-ROOT-relative when the scan root sits inside a git repo, so a subdirectory-scoped `local_path` binds the same form delete-reconcile keys on; scan-root-relative otherwise). The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering FROM the row means file and row cannot diverge. ATOMIC: writes to a unique temp sibling (`<file>.tmp.<pid>.<rand>`) + `renameSync`, cleaning up temp on any failure, so a crash or concurrent `gbrain sync`/autopilot walking the live git tree never reads a half-written `.md` (matches the `.tmp + rename` convention in import-checkpoint.ts / op-checkpoint.ts). After a successful rename, a row whose `source_path` is still NULL is immediately bound to `sourcePathToBind` (pages born via put/capture/reverse-write otherwise stay `source_path=NULL` forever because mtime-watermark incremental sync never rescans an untouched file); NULL-guarded so a scanner-recorded path is never rewritten, best-effort so a failed bind never fails the write. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision', error? }` so the caller decides messaging + exit codes. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.serial.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error`, deleting a just-created row first so "created" is never answered for a page with no file backing.
+- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId)` is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained `file://` `source_uri`) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention (GIT-ROOT-relative when the scan root sits inside a git repo, so a subdirectory-scoped `local_path` binds the same form delete-reconcile keys on; scan-root-relative otherwise). The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering FROM the row means file and row cannot diverge. ATOMIC: writes to a unique temp sibling (`<file>.tmp.<pid>.<rand>`) + `renameSync`, cleaning up temp on any failure, so a crash or concurrent `gbrain sync`/autopilot walking the live git tree never reads a half-written `.md` (matches the `.tmp + rename` convention in import-checkpoint.ts / op-checkpoint.ts). After a successful rename, a row whose `source_path` is still NULL is immediately bound to `sourcePathToBind` (pages born via put/capture/reverse-write otherwise stay `source_path=NULL` forever because mtime-watermark incremental sync never rescans an untouched file); NULL-guarded so a scanner-recorded path is never rewritten, best-effort so a failed bind never fails the write. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision', warning?, error? }` so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.serial.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.serial.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error`, deleting a just-created row first so "created" is never answered for a page with no file backing.
- `src/core/model-id.ts` — `splitProviderModelId(input: string | null | undefined): {provider: string | null, model: string}` shared parser for the pricing side. Splits on `:` first, then `/`. Defensive contract: null/undefined/empty/whitespace returns `{provider: null, model: ''}`. Five sites consume it (`src/core/anthropic-pricing.ts:estimateMaxCostUsd`, `src/core/budget/budget-tracker.ts:lookupPricing`, `src/core/eval-contradictions/cost-tracker.ts:pricingFor`, `src/core/minions/batch-projection.ts` at two call sites, `src/core/model-config.ts:isAnthropicProvider`) so the pricing + classification surface has no parallel re-implementations of `provider:model` splitting — slash-form ids (`anthropic/claude-sonnet-4-6`) classify correctly instead of falling through to "unknown model". Distinct from the gateway-side `parseModelId` in `src/core/ai/model-resolver.ts`, which throws on bare names because routing needs an explicit provider; this one returns `{provider: null, model: 'bare'}` because pricing lookups happen against bare model ids. Pinned by `test/model-id.test.ts`.
- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first read; local engine or thin-client). Entity→text fallback: a bare positional is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read) the query retries as the SQL-level fact-text grep with a one-line stderr note — so keyless/casual usage (`gbrain recall coffee`) finds the fact either way. One gating predicate + one note formatter (`entityTextFallbackApplies`/`noteEntityTextFallback`) shared by the local path and the thin-client mirror so the two can't drift; explicit `--grep` callers keep exact semantics (their filter already ran, no fallback surprise). `--since` composes with the positional entity and with `--session-id` through `engine.listFactsSince({entitySlug, sessionId})` (one query, cutoff before LIMIT, event time unless `--since-last-run`), mirroring the `recall` op's composition in `src/core/ops/facts.ts`; pinned by `test/facts-recall-since-composition.test.ts`.
- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest`; embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan; no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec.
-- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` — `<session>/subagents/agent-*.jsonl` logs are all-sidechain, zero-turn files carrying the PARENT session id, so `discover.ts` and the CLI's `expandPaths` both skip them and they never read as gap-table backlog or drift; strict parent-dir + basename shape so a project slug containing "subagents" is never hidden), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message, assistant from `response_item` output_text; role user/developer response_items are injected preambles and never leak), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), ~300KB message-boundary splitting with 2-message overlap (under the embed-skip threshold), part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/e2e/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).
+- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when a file has zero turn-shaped records (`type` user/assistant, not sidechain) and zero skipped lines — a title/metadata-only stub is understood, not drift, while turn records that yield no text and unparseable lines still drift), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message, assistant from `response_item` output_text; role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), ~300KB message-boundary splitting with 2-message overlap (under the embed-skip threshold), part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/e2e/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).
- `src/core/connectors/` (directory) — the LIVE chat-history connector layer (front-end to the transcripts pipeline). `types.ts`: the `ChatHistoryProvider` contract (mirror of `TranscriptAdapter` — leaf module per provider; `spoolFormat` names the adapter that parses its output; dated `HostSpecTarget`). `credentials.ts`: file-plane store at `~/.gbrain/connectors/<provider>.json` (0600, dir 0700, atomic tmp+rename), env-above-file `resolveCredential` returning `{cred, source}`; credentials NEVER touch the DB / `sources.config` / config planes / op payloads. `classify.ts`: the pure §2A/§2B response classifier — distinguishes a Cloudflare-fingerprint 403 (`forbidden_fingerprint`, dead-end) from an auth-expired 403 (`auth_required`, re-auth) and flags a parses-but-no-`items` body as `drift`. `client.ts`: `ConnectorClient` modeled on `GitHubClient` (plain fetch against a hardcoded ORIGIN + off-origin guard so the cookie/bearer never leaks, browser UA, refresh-once-on-401, Retry-After backoff; `fetchImpl`/`sleep`/`now` injectable — NOT `fetchWithSSRFGuard`, which breaks SNI on Cloudflare hosts). `providers/chatgpt.ts` + `providers/claude.ts` (registry in `registry.ts`; Perplexity deliberately absent — no adapter): offset/updated pagination with a per-pass 500-page cap and a `stopBefore` watermark break, epoch/ISO normalization, ChatGPT's `is_archived` second pass, org discovery + content-block text assembly for Claude, and a `refreshAccessToken` (ChatGPT re-mints from the cookie via `/api/auth/session`; Claude's cookie is terminal). `spool.ts`: writes fetched conversations in native-export shape (0600, batched, pruned in the orchestrator `finally`). `sync.ts`: `runConnectorSync` — resolve credential → probe → read the **config-scalar watermark** `connectors.<p>.watermark_iso` (NOT op_checkpoint, whose 7-day GC would wipe it → full re-fetch) → list to `watermark − windowDays` → fetch → spool → `runTranscriptsIngest` → advance the watermark ONLY on a fully clean run → `logIngest` receipt → stamp `last_sync_at` → engine-branched embed kickoff (`maybeKickoffEmbed`: Postgres `submitEmbedBackfill`, PGLite `runEmbedCore` inline — NEVER `submitEmbedBackfill`, which refuses `no_worker_surface`). `config-keys.ts`: the `connectors.` key builders + the pure `isConnectorSyncStale(last, now, floor)` dispatch gate. `oauth-pkce.ts`: dependency-free S256 PKCE loopback (`Bun.serve`, timing-safe state) — best-effort `--try-oauth` only. Surfaces: the `connectors_status`/`connector_sync` ops (`src/core/ops/connectors.ts`, both `localOnly`), the `gbrain connectors` command family (`src/commands/connectors/` peeled dir), the `connector-sync` minion handler (`src/core/minions/handlers/connector-sync.ts`, single-flight lock), the autopilot `maybeDispatchConnectorSyncs` gate, and the `connectors` doctor check. Pinned by `test/connectors-*.test.ts` + `test/e2e/connectors-sync-pglite.test.ts` (full pipeline against a `Bun.serve` fixture backend, keyless) + `test/e2e/connector-sync-handler-pglite.test.ts` + `test/e2e/doctor-connectors-pglite.test.ts`.
- `src/commands/integrity.ts` — `gbrain integrity check|auto|review|extract`: bare-tweet detection, dead-link detection, three-bucket repair (auto-repair / review-queue / skip). `scanIntegrity()` is the shared library function called from `gbrain doctor` (sampled at limit=500) and `cmdCheck` (full scan). Batch-load fast path on Postgres uses a single SQL query (avoids the PgBouncer per-row round-trip timeout), gated by `engine.kind === 'postgres'` at the call site so PGLite never enters batch; fallback `catch` logs at `GBRAIN_DEBUG=1`. Batch projection is `SELECT ... ORDER BY source_id, slug` (NOT `SELECT DISTINCT ON (slug)`, which would collapse same-slug-different-source pages into one scan) so multi-source brains scan each `(source, slug)` row independently. Sequential and auto-repair loops use `listAllPageRefs()` to enumerate `(slug, source_id)` pairs and thread `sourceId` to `getPage`; batch + sequential paths report the same page count on multi-source brains.
- `src/core/timeline-dedup-repair.ts` — schema-drift self-heal for `idx_timeline_dedup`. A master-merge migration renumbering can leave a brain's version counter stamped past the index change while the index keeps an old shape — and every `addTimelineEntry` batch then fails its `ON CONFLICT` inference, silently breaking timeline writes brain-wide. The version counter can't detect this, so the repair is keyed off the actual index SHAPE. Canonical shape is `(page_id, date, md5(summary), source)` — md5-keyed (migration v138) because a raw long/incompressible summary would overflow the btree v4 row cap (~2704 bytes) and abort every timeline insert for that page; both engines' insert sites infer `ON CONFLICT` on the md5 tuple, so `EXPECTED_COLUMNS` MUST carry the md5 form (a raw-shape expectation would make the repair revert v138 on every migrate pass). `checkTimelineDedupIndex(engine)` returns `{tablePresent, indexPresent, columns, needsRepair}` (read-only; powers the `timeline_dedup_index` doctor check; the indexdef column parser is paren-depth-aware so `md5(summary)` — or any future expression column — parses as ONE column instead of flagging a correct index as drifted forever) and `repairTimelineDedupIndex(engine)` dedupes-then-rebuilds to the canonical shape (raw-summary grouping ⟺ md5 grouping modulo negligible collisions). `runMigrations` invokes the repair on every pass (including the no-pending early-return path); idempotent no-op when the index already matches. `gbrain apply-migrations --force-schema` triggers it on demand. Pinned by `test/timeline-dedup-repair.test.ts`.
+- `src/core/link-source-check-repair.ts` — schema-drift self-heal for the `links_link_source_check` CHECK constraint (third instance of the `timeline-dedup-repair.ts` / `pages-upsert-arbiter.ts` class). Migration v114 opened `link_source` from a closed allowlist to the kebab-case gate; the migrator trusts the version ledger, so a brain stamped >= 114 whose live constraint reverted to the pre-v114 allowlist (drifted restore, manual DDL) rejects every kebab provenance write (`atom-provenance`, `concept-provenance`) while the ledger reads current. `LINK_SOURCE_KEBAB_RE` is the ONE exported copy of the regex (a drift-guard test pins it to the literal in migrate.ts v114, `schema.sql`, `pglite-schema.ts`). `checkLinkSourceCheck(engine)` probes `pg_constraint` (`pg_get_constraintdef` + `convalidated`) and classifies the drift as `absent` / `wrong_def` / `not_validated` (read-only; powers the `links_link_source_check` doctor check in `doctor/checks/core-health.ts`, whose severity follows what writes do: only `wrong_def` rejects kebab writes → fail; `absent` / `not_validated` still accept them → warn). `repairLinkSourceCheck(engine)` first COUNTs rows that fail the gate and returns `reason: 'violations'` WITHOUT any DDL when there are any (the prior constraint survives; rows are never touched; a brain with a bad row never pays for a failing ALTER at every engine open), then restores v114's definition mirroring the migration's engine split: Postgres runs DROP + `ADD ... NOT VALID` in one `engine.transaction` (atomic, no scan) and `VALIDATE CONSTRAINT` as a separate `engine.runMigration` outside it (SHARE UPDATE EXCLUSIVE, never a plain ADD's ACCESS EXCLUSIVE + full-table scan), with a `not_validated` drift getting the VALIDATE only; PGLite keeps the one-shot DROP+ADD transaction. A DDL failure re-counts violators (a row written between probe and ALTER) and rethrows when there are none. `LINK_SOURCE_GATE_MIGRATION_VERSION` (114) is the ledger gate `runMigrations` applies before calling it. Pinned by `test/link-source-check-repair.test.ts` (PGLite, incl. a recording-engine assertion that violators trigger no DDL and that a sub-114 ledger never probes) and the DATABASE_URL-gated `test/e2e/link-source-check-repair-postgres.test.ts` (two-phase DDL sequence on real Postgres).
- `src/core/progress.ts` — Shared bulk-action progress reporter. Writes to stderr. Modes: `auto` (TTY `\r`-rewriting; non-TTY plain lines), `human`, `json` (JSONL), `quiet`. Rate-gated by `minIntervalMs` and `minItems`. `startHeartbeat(reporter, note)` for single long queries. `child()` composes phase paths. Singleton SIGINT/SIGTERM coordinator emits `abort` events for every live phase. EPIPE defense on both sync throws and stream `'error'` events. Zero dependencies. `emitHumanLine` is prefix-aware — inside a `withSourcePrefix(id, ...)` scope from `src/core/console-prefix.ts` it prepends `[id] ` (and TTY-rewrite mode `\r\x1b[2K` carries the prefix inside the clear-to-EOL escape); `emitJson` is intentionally NOT prefixed so NDJSON consumers don't choke on a `[id] {...}` shape.
-- `src/core/console-prefix.ts` — `AsyncLocalStorage<string>`-backed per-source line-prefix helper. Exports `withSourcePrefix(id, fn)` (runs `fn` with `id` as active prefix; nested wraps replace then restore), `getSourcePrefix()` (read-only accessor; test seam), `slog(...)` / `serr(...)` (prefix-aware `console.log`/`console.error`), and `withHumanLogsToStderr(fn)` (runs `fn` with every `slog` line, prefixed or not, routed to stderr; `runSync` wraps its body in it under `--json` so stdout carries only JSON lines — the envelope plus any JSON status lines — while `serr` and direct `console.log(JSON.stringify(..))` sites are unaffected; scoped via its own `AsyncLocalStorage`, never a process-wide console rebind). Embedded-newline-safe: a multi-line string under prefix `[foo]` emits `[foo] line1\n[foo] line2`. Outside a wrap, `slog`/`serr` fall through to bare `console.log`/`console.error` so single-source callers see identical output (back-compat invariant). Use `src.id` (slug-validated by `sources add`) NOT `src.name` (free-form) to defeat log-injection through newline/control-character names. Coverage: `src/commands/sync.ts` performSync + callees, `src/commands/embed.ts` runEmbedCore + helpers, `src/core/progress.ts` emitHumanLine, `src/commands/import.ts` runImport's human-only lines (`info()` + the end-of-run `Import complete` summary — so the first-sync full import under `sync --json` lands on stderr too).
+- `src/core/console-prefix.ts` — `AsyncLocalStorage<string>`-backed per-source line-prefix helper. Exports `withSourcePrefix(id, fn)` (runs `fn` with `id` as active prefix; nested wraps replace then restore), `getSourcePrefix()` (read-only accessor; test seam), `slog(...)` / `serr(...)` (prefix-aware `console.log`/`console.error`), and `withHumanLogsToStderr(fn)` (runs `fn` with every `slog` line, prefixed or not, routed to stderr; `runSync` wraps its body in it under `--json` so stdout carries only the ONE JSON envelope (the cost-gate status object rides inside it as `cost_gate`, #4684) while `serr` and direct `console.log(JSON.stringify(..))` sites are unaffected; scoped via its own `AsyncLocalStorage`, never a process-wide console rebind). Embedded-newline-safe: a multi-line string under prefix `[foo]` emits `[foo] line1\n[foo] line2`. Outside a wrap, `slog`/`serr` fall through to bare `console.log`/`console.error` so single-source callers see identical output (back-compat invariant). Use `src.id` (slug-validated by `sources add`) NOT `src.name` (free-form) to defeat log-injection through newline/control-character names. Coverage: `src/commands/sync.ts` performSync + callees, `src/commands/embed.ts` runEmbedCore + helpers, `src/core/progress.ts` emitHumanLine, `src/commands/import.ts` runImport's human-only lines (`info()` + the end-of-run `Import complete` summary — so the first-sync full import under `sync --json` lands on stderr too).
- `src/core/cli-options.ts` — Global CLI flag parser. `parseGlobalFlags(argv)` returns `{cliOpts, rest}` with `--quiet` / `--progress-json` / `--progress-interval=<ms>` / `--brain <id>` stripped. `--brain` is the brain-axis (which database) selector: exact-match only (`--brain-*` per-command flags pass through), value validated against the mount-id regex at parse time, missing/malformed value THROWS — never a silent host fallback. `connectEngine` in `src/cli.ts` feeds it (plus the ambient `GBRAIN_BRAIN_ID` / `.gbrain-mount` / mount-path tiers) through `resolveBrainId` → `BrainRegistry.getBrain`, which throws `UnknownBrainError` for an unregistered id; mounts get no auto-migrations and keep the host-config AI gateway. `getCliOptions()` / `setCliOptions()` expose a module-level singleton so commands reach resolved flags without parameter threading. `cliOptsToProgressOptions()` maps to reporter options. `childGlobalFlags()` returns the flag suffix to append to `execSync('gbrain ...')` calls in migration orchestrators (propagates `--brain=<id>` so children stay on the parent's brain). `OperationContext.cliOpts` extends shared-op dispatch for MCP callers. `CliOptions` carries `explain: boolean`. `parseGlobalFlags` recognizes `--explain` anywhere in argv (stripped before command dispatch). `src/cli.ts` `formatResult` for `search` + `query` cases routes to `formatResultsExplain` from `src/core/search/explain-formatter.ts` when `CliOptions.explain` is set; falls through to the existing JSON / human formatters otherwise. `maybeBackground(opName, fingerprintArgs, runDirect)` helper. Same semantics in TTY and cron (no `--no-tty-detect` flag, no surprise behavior change between contexts): when `--background` is passed, submits the op as a Minion job via `op_checkpoints` for resumability and returns the `job_id`. `--background --follow` execs `gbrain jobs follow <id>` so the user sees the same stderr stream they'd get from a direct call. PGLite degrades to inline execution with a clear stderr note ("PGLite worker pool not yet supported; running inline"). Returns a tagged union the caller dispatches on.
-- `src/cli.ts` strict flag validation + `src/core/cli-flag-registry.generated.ts` + `scripts/generate-flag-registry.ts` — pre-dispatch, pre-engine unknown-flag rejection for every command: a flag no handler consults fails loud (`unknown flag --x for 'gbrain <cmd>'`, exit 1; `--json` invocations also get a structured `{status:'error', reason:'invalid_flag'}` on stdout) instead of being silently ignored while the un-asked-for real operation runs. `validateCommandFlags(command, subArgs)` runs after the `--help` short-circuit and before any dispatch or engine connect, in two lanes mirroring dispatch order (CLI_ONLY first — `think`/`salience`/`anomalies` are both ops AND CLI_ONLY members whose handlers parse flags the op contract doesn't declare): CLI_ONLY commands validate against the generated `CLI_FLAG_REGISTRY` (per-command legal sets derived from each command's source — case block + imported modules + one level of relative imports + `EXTRA_FLAGS`; deliberately over-inclusive, help-text mentions count; regenerate via `bun run build:flag-registry`); op commands validate via `findUnknownOpFlag`, which mirrors `parseOpArgs`'s traversal (non-boolean flags consume their value token; `--key=value` inline form recognized) plus the CLI-local flags consumed outside the op contract (`json`, `explain`, `help`, `source`, `dry-run`); the CLI_ONLY token scan is the exported `findUnknownFlag(args, legal)`. In `parseOpArgs`, `json`/`dry_run` are CLI-local booleans that never consume a value token, so a trailing `--dry-run` is a real rehearsal switch feeding `makeContext`'s `ctx.dryRun`. Uppercase flag spellings are treated as unknown (every handler is case-sensitive-lowercase, so they'd be silently ignored downstream — the exact class the validator kills). Exempt by contract: `call` (arbitrary `--param` interface), `config` (arbitrary set values), `jobs submit` (handler-defined payload params); everything after a literal `--` is passthrough and never validated. A command missing from the registry fails OPEN at runtime (never bricks a command); `test/cli-flag-validation.test.ts` pins registry freshness, per-command drift, and consumption evidence — a safety flag (`--dry-run`, `--yes`, `--force`) may only be advertised if the command's source actually reads it. The generator segments `handleCliOnly` into per-command text blocks with `segmentDispatchBlocks`: both `case 'X':` labels and every `if (command === 'X' …)` head — plain, compound (`&& args[0] === 'sub'`: the no-DB `eval <sub>` bypasses such as `eval longmemeval`, the `<cmd> --help` pre-engine branches, `agent register`) and multi-line — are markers, and ownership follows the `command === 'X'` head, never the condition's tail, so a compound block's flags land on its own command's row (the `eval` row is a union across eval subcommands, the registry's shape for every multi-subcommand command); a bare `command === 'X'` inside a non-`if` expression is deliberately not a marker. Only `import('./commands/*.ts')` inside a block counts as a command module (core helpers a block reaches for directly are not scanned — a flag the block consumes through one is already a literal in the block's own text), and `isValueOnlyImport` skips a destructured import whose bindings are all SCREAMING_CASE constants (a borrowed message string, not a handler). Pinned by `test/generate-flag-registry.test.ts` (acceptance AND rejection: `--frobnicate` is still refused) and `test/eval-longmemeval-cli-smoke.test.ts` (the documented `gbrain eval longmemeval … --retrieval-only --by-type --no-trajectory --keyword-only` invocation exits 0 as a subprocess).
+- `src/cli.ts` strict flag validation + `src/core/cli-flag-registry.generated.ts` + `scripts/generate-flag-registry.ts` — pre-dispatch, pre-engine unknown-flag rejection for every command: a flag no handler consults fails loud (`unknown flag --x for 'gbrain <cmd>'`, exit 1; `--json` invocations also get a structured `{status:'error', reason:'invalid_flag'}` on stdout) instead of being silently ignored while the un-asked-for real operation runs. `validateCommandFlags(command, subArgs)` runs after the `--help` short-circuit and before any dispatch or engine connect, in two lanes mirroring dispatch order (CLI_ONLY first — `think`/`salience`/`anomalies` are both ops AND CLI_ONLY members whose handlers parse flags the op contract doesn't declare): CLI_ONLY commands validate against the generated `CLI_FLAG_REGISTRY` (per-command legal sets derived from each command's source — case block + imported modules + one level of relative imports + `EXTRA_FLAGS`; deliberately over-inclusive, help-text mentions count, but `//` and `/* */` comments are stripped at every depth before the scan — a helper's doc comment naming `--fresh` must not legalise it for a command that only imports one function from that helper; regenerate via `bun run build:flag-registry`); op commands validate via `findUnknownOpFlag`, which mirrors `parseOpArgs`'s traversal (non-boolean flags consume their value token; `--key=value` inline form recognized) plus the CLI-local flags consumed outside the op contract (`json`, `explain`, `help`, `source`, `dry-run`); the CLI_ONLY token scan is the exported `findUnknownFlag(args, legal)`. In `parseOpArgs`, `json`/`dry_run` are CLI-local booleans that never consume a value token, so a trailing `--dry-run` is a real rehearsal switch feeding `makeContext`'s `ctx.dryRun`. Uppercase flag spellings are treated as unknown (every handler is case-sensitive-lowercase, so they'd be silently ignored downstream — the exact class the validator kills). Exempt by contract: `call` (arbitrary `--param` interface), `config` (arbitrary set values), `jobs submit` (handler-defined payload params); everything after a literal `--` is passthrough and never validated. A command missing from the registry fails OPEN at runtime (never bricks a command); `test/cli-flag-validation.test.ts` pins registry freshness, per-command drift, and consumption evidence — a safety flag (`--dry-run`, `--yes`, `--force`) may only be advertised if the command's source actually reads it. The generator segments `handleCliOnly` into per-command text blocks with `segmentDispatchBlocks`: both `case 'X':` labels and every `if (command === 'X' …)` head — plain, compound (`&& args[0] === 'sub'`: the no-DB `eval <sub>` bypasses such as `eval longmemeval`, the `<cmd> --help` pre-engine branches, `agent register`) and multi-line — are markers, and ownership follows the `command === 'X'` head, never the condition's tail, so a compound block's flags land on its own command's row (the `eval` row is a union across eval subcommands, the registry's shape for every multi-subcommand command); a bare `command === 'X'` inside a non-`if` expression is deliberately not a marker. Only `import('./commands/*.ts')` inside a block counts as a command module (core helpers a block reaches for directly are not scanned — a flag the block consumes through one is already a literal in the block's own text), and `isValueOnlyImport` skips a destructured import whose bindings are all SCREAMING_CASE constants (a borrowed message string, not a handler). Pinned by `test/generate-flag-registry.test.ts` (acceptance AND rejection: `--frobnicate` is still refused) and `test/eval-longmemeval-cli-smoke.test.ts` (the documented `gbrain eval longmemeval … --retrieval-only --by-type --no-trajectory --keyword-only` invocation exits 0 as a subprocess).
- `src/core/source-id.ts` — single canonical source_id validation, dependency-free by design (imported by both engines, cycle, source-resolver, sources-ops). `SOURCE_ID_RE` (strict: 1-32 lowercase alnum, interior hyphens only, no edge hyphens); `isValidSourceId` (boolean — for tiers that silently fall back: dotfile, brain_default) vs `assertValidSourceId` (throws — for tiers that must reject loudly: explicit `--source`, `GBRAIN_SOURCE`, `cycleLockIdFor`); `ALL_SOURCES = '__all__'` sentinel (deliberately NOT a valid id so it can never collide with a real source or leak into lock ids/path joins; `sourceScopeOpts` translates it to an unscoped read for trusted local callers and keeps it unsatisfiable for remote callers, fail-closed). `normalizeSourceInput`/`normalizeFederatedReadInput` normalize the `/admin/api/register-client` HTTP body, mirroring the CLI's `--source`/`--federated-read` flags: omitted `source` → `'default'`; omitted `federatedRead` → `undefined` so `registerClientManual` applies its own `[sourceId]` default; present-but-invalid values throw so the route returns a structured 400 (`invalid_source`) instead of failing at INSERT time. Pinned by `test/register-client-source-normalize.test.ts`.
- `src/core/entity-identity.ts` + `src/core/ops/entity-identity.ts` — cross-source entity identity (cross-source federation). THE IDENTITY KEY IS `(source_id, slug)`: the same real-world entity routinely exists as a different page per mounted source, and nothing else in gbrain asserts "these pages are the same entity". The `entity_identities` table (migration v137) records that assertion explicitly — member pages grouped under an opaque `entity_id` handle (`validateEntityId`: slug-flavored, lowercase, max 128 chars), one optional canonical member per group, a page belongs to at most one identity (`UNIQUE (source_id, page_id)`; re-linking MOVES it). Posture is MANUAL-ONLY by design: rows come exclusively from the `entity_identity_link` op — no auto-matching or name-similarity heuristics, because a wrong identity merge silently corrupts retrieval. Three ops: `entity_identity_link` / `entity_identity_unlink` (write, localOnly — merges change what retrieval unions across sources, too sharp for a remote surface) + `entity_identity_list` (read; restricts MEMBER visibility to a federated grant or remote scalar scope, while a trusted local caller sees the full cross-source group — cross-source IS the feature). Retrieval union is OFF by default behind the `entity_identity.union` config key; when on, get_links/get_backlinks merge edges from identity co-members (dedup'd), never widening past the caller's source grant. Same SQL text on both engines (parity by construction); pinned by the entity-identity test + the DATABASE_URL-gated engine-parity suite. Topology context: `docs/architecture/brains-and-sources.md`.
- `src/core/db-lock.ts` — generic `tryAcquireDbLock(engine, lockId, ttlMinutes)` over the `gbrain_cycle_locks` table. Parameterized lock id so scopes nest cleanly: `gbrain-cycle` for the broad cycle (held by `cycle.ts`) and `gbrain-sync` (`SYNC_LOCK_ID`) for `performSync`'s narrower writer window. UPSERT-with-TTL semantics survive PgBouncer transaction pooling (unlike session-scoped `pg_try_advisory_lock`); crashed holders auto-release once their TTL expires. Every handle is FENCED to its exact acquisition: `DbLockHandle.acquiredAt` captures the row's `acquired_at` as epoch-seconds text (`extract(epoch from acquired_at)::text` — GUC-independent, unlike `timestamptz::text` which varies with per-session TimeZone/DateStyle across pools) and `refresh()`/`release()`/the cleanup hook all match `(id, holder_pid, fence)`, so a recycled PID or a superseded holder can never refresh or delete a successor's row. `refresh()` returns a boolean: `true` = still owned; `false` = the fenced UPDATE matched 0 rows (stolen or force-cleared — certain loss, the caller must stop relying on mutual exclusion); transient DB errors still THROW (not evidence of a steal; the TTL is the backstop). Exports `LockStolenError` (thrown/used as an AbortSignal reason by consumers like `cycle.ts`'s refresher and the supervisor). It also does automatic same-host dead-pid takeover: when the upsert finds a held, NOT-TTL-expired lock whose holder is on this host and provably dead, it reclaims via a guarded `DELETE WHERE id=$1 AND holder_pid=$2` + one normal-upsert retry returning the standard handle (refresh/release intact). The liveness check is the exported `classifyHolderLiveness(pid, host, ageMs, opts?)` / `isHolderDeadLocally(...)` (injectable `process.kill` seam; `HOLDER_TAKEOVER_GRACE_MS = 60_000` PID-reuse guard; EPERM classified as `alive` so a live process you don't own is never stolen). TTL-expired locks stay the upsert's job; cross-host stays TTL-only. `runBreakLock` (`src/commands/sync.ts`) consumes the same predicate. Background reaper: `reapDeadHolderLocks(engine)` is the periodic sweep the contention path lacked — it deletes locks whose holder is `isHolderDeadLocally`, scoped to the `gbrain-sync:*` / `gbrain-cycle`/`gbrain-cycle:*` namespaces ONLY (election/supervisor/reindex locks keep TTL-only behavior, untouched), via `deleteLockRowExact(engine, id, pid, acquiredAt)` — a snapshot-matched delete (`date_trunc('milliseconds', acquired_at) = $3`, so the ms a JS Date keeps survives) that's TOCTOU-safe against a reused PID taking the lock between SELECT and DELETE. `cycle.ts` runs it at cycle start (before the sync phase); `gbrain doctor --fix` runs it for no-autopilot brains. `selectLockRows(engine, opts?)` + a shared row→`LockSnapshot` mapper are the single canonical reader backing `inspectLock` + `listStaleLocks` + the reaper. `isLockHolderLive(snap, ttlMinutes)` is the observability liveness predicate — freshness-keyed (`ttl_expired` plus the heartbeat steal-grace), never `process.kill`, so `gbrain jobs supervisor status` / `gbrain doctor` can report a live supervisor via its queue lock without a PID-reuse false-positive. Pinned by `test/db-lock-auto-takeover.test.ts` + `test/db-lock-reap.test.ts` + `test/db-lock-fencing.test.ts`. `DbLockHandle.refresh(opts?)` accepts `{signal}` (Postgres forwards to executeRawDirect; PGLite ignores); `withRefreshingLock`'s heartbeat aborts the per-tick signal on timeout and guards re-entrancy (15s min cadence vs 30s timeout could stack ticks).
@@ -430,7 +435,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/worker-pool.ts` — Canonical sliding-pool + bounded-semaphore primitive (used by the `src/commands/embed.ts` sliding-pool sites and `src/commands/eval-cross-modal.ts`'s `runWithLimit` semaphore). Two exports: `runSlidingPool<T>({items, workers, onItem, signal?, onError?, failureLabel?, onProgress?})` + `runWithLimit<TIn, TOut>({items, limit, fn, signal?})`. Atomicity invariant: `const idx = nextIdx++` is one synchronous JS statement (no `await` between read and write — guaranteed by the single-threaded event loop), documented in the module header AND enforced by `scripts/check-worker-pool-atomicity.sh` (wired into `bun run verify`), which rejects importing `worker_threads` in any consuming file and inserting `await` between the `nextIdx` read and write. `MUST_ABORT_ERROR_TAGS` set is seeded with `BUDGET_EXHAUSTED` from `src/core/budget/budget-tracker.ts`; tagged errors (matched via `err.tag === 'BUDGET_EXHAUSTED'` to avoid cross-module import) bypass `onError` and hard-abort the pool via `AbortController.abort()` to in-flight `onItem`, then the pool JOINS every worker (each finishes its current item) before rethrowing — the budget cap is a structural ceiling under concurrency and no worker is left running detached past the caller's catch. `failures[]` shape is `{idx, label, error}` records (NOT full items; callers supply `failureLabel(item) => string`) for bounded memory under huge brains. Pinned by `test/worker-pool.test.ts` + `test/scripts/check-worker-pool-atomicity.test.ts`. Drives every `--workers N` bulk command.
- `src/core/embedding-dim-check.ts` — facts.embedding dim drift surface. `readFactsEmbeddingDim(engine): Promise<FactsColumnDimResult>` covers both `vector(N)` and `halfvec(N)` shapes (migration v40 falls back to `vector` on pgvector < 0.7); regex ordering is halfvec-before-vector (substring "vec" appears in "halfvec"; naive `/vector/i` would shadow). `buildFactsAlterRecipe(dims, configured, type)` emits the paste-ready `DROP INDEX IF EXISTS idx_facts_embedding_hnsw; ALTER TABLE facts ALTER COLUMN embedding TYPE halfvec(N) USING embedding::halfvec(N); CREATE INDEX idx_facts_embedding_hnsw ON facts USING hnsw (embedding halfvec_cosine_ops) WHERE ...` flow (NOT bare REINDEX, which doesn't rewrite the index after a column-type change). `assertFactsEmbeddingDimMatchesConfig(engine)` is the preflight — throws `FactsEmbeddingDimMismatchError` (tagged `tag: 'FACTS_EMBEDDING_DIM_MISMATCH'` for parity with the worker-pool MUST_ABORT semantics) when configured dim ≠ column width; cached per-engine via `WeakMap`; PGLite engines silently skip. Doctor check `facts_embedding_width_consistency` (registered after `embedding_width_consistency`) reuses the same helpers with an identical ALTER recipe. `decorateEmbeddingDimError(err, slug)`: maps pgvector's bare "expected N dimensions, not M" write rejection to a named `OperationError('embedding_plane_split', …)` carrying the consequence (page NOT written, transaction rolled back) + recovery command; applied at `importFromContent`'s transaction boundary so `gbrain put` fails loudly instead of echoing an unexplained provider string; every other error passes through untouched. Pinned by `test/embedding-dim-check-facts.test.ts` + `test/put-page-embedding-plane-split.test.ts`.
- `src/core/sort-newest-first.ts` — single source of truth for the descending-lex sort that `gbrain import` and `gbrain sync` both apply. Mutates in place (Array.prototype.sort semantics), returns the same array reference for fluent chaining. Empty/single-element inputs short-circuit. Future ordering changes flip one line here instead of touching two CLI commands. Pinned by `test/sort-newest-first.test.ts` (descending order, mixed prefixes, empty, single-element, in-place-mutation contract).
-- `src/core/cycle.ts` — brain maintenance cycle primitive (23 phases; `ALL_PHASES` is the ordered source of truth). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; their in-flight work runs to its own bounded timeout because their opts can't carry a signal yet). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, AND synthesize so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/cycle/cycle-lock-ttl.test.ts` (pins `LOCK_TTL_MINUTES === 5`), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run.
+- `src/core/cycle.ts` — brain maintenance cycle primitive (23 phases; `ALL_PHASES` is the ordered source of truth). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; their in-flight work runs to its own bounded timeout because their opts can't carry a signal yet). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, AND synthesize so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash (`hashGazetteer` in `src/core/by-mention.ts` — every entry's source_id/slug/title/tokens, not just the first-token bucket keys, so a new "Acme Labs" beside an existing "Acme Corp" moves it) is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `findMentionedEntities` keys its self-link guard and first-mention dedup on `(source_id, slug)`, so under `link_resolution.cross_source` a foreign namesake of the scanning page is a real target and same-slug pages in two sources both link; the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/cycle/cycle-lock-ttl.test.ts` (pins `LOCK_TTL_MINUTES === 5`), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run.
- `src/core/cycle/phase-scope.ts` — the phase-scope taxonomy: `PHASE_SCOPE: Record<CyclePhase, 'source'|'mixed'|'global'>` maps each of the 23 phases (source: safe to parallelize per source; global: must serialize across the brain; mixed: brain-wide read + page write, so it stays in the default/global-maintenance lane until decomposed), plus `SOURCE_FRESHNESS_PHASES` — the deterministic, non-LLM subset (lint, backlinks, sync, extract, extract_facts, recompute_emotional_weight) that alone defines source freshness, so LLM-backed enrichment can never hold a freshness stamp hostage. cycle.ts re-exports both and derives the scheduling lists from them (see the cycle.ts entry). Consumed by `runCycle`'s `resolveCyclePhases` boundary, the autopilot fanout's per-source enqueue (`src/commands/autopilot-fanout.ts`), the jobs global-maintenance handler, and doctor's routing-federation phase-scope surface (`src/commands/doctor/checks/routing-federation.ts`). Pinned by `test/autopilot-global-maintenance.test.ts` (SOURCE ∪ MIXED ∪ GLOBAL == ALL_PHASES with no overlap; FRESHNESS ∪ BACKGROUND == SOURCE; resolveCyclePhases boundary semantics).
- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written ONLY on success. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/e2e/dream-synthesize-chunking.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails OPEN with a stderr warn). `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every child-written page BEFORE reverse-rendering, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the quote verify/repair pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on newly-created pages; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`.
- `src/core/cycle/cycle-date.ts` — the dream-cycle calendar-date policy: `resolveCycleDate` resolves explicit `--date` > `cycle.timezone` config > host IANA timezone > UTC, so a run after local midnight buckets into the day the user actually lived instead of rewriting yesterday's UTC-day summary. `isValidTimeZone` gates configured values (config.ts also validates at `gbrain config set` time); an invalid configured timezone falls back loudly instead of killing the cycle. `utcDate` is retained for source-date fallbacks and legacy pages.
@@ -442,8 +447,8 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/cycle/synthesize-verify.ts` — Mechanical quote verify/repair on newly-created dream pages (zero LLM). Exports the shared grounding primitive `normalizeForGrounding` (whitespace/curly-quote/dash/case folding WITH an offset map back to the original string, so every replacement is a verbatim transcript slice) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). `verifyAndRepairDreamPages(engine, writtenRefs, transcriptsByPath)` scopes to pages whose slug carries the transcript's content-hash suffix (page↔transcript binding; modified pre-existing people/pattern pages are skipped + counted `skipped_preexisting` — they may quote other sources), extracts paired-quote spans from the page BODY (code fences/inline code/wikilinks/link targets masked; paragraph-paired; odd-mark paragraphs skipped + counted `unbalanced`; min span 15 chars, ≤200 spans/page), and runs the repair ladder per span: exact substring → keep; normalized match → replace with the verbatim original slice; near match (word-trigram anchors, ≥0.8 token overlap, ambiguity within 0.05 falls through) → replace; else STRIP the quote marks keeping the text — NEVER fabricates, never deletes content. Warn-only counter: numeric/date claims ($amounts, percents, ISO/month dates, 4+ digit numbers, deduped, fences skipped) absent from the normalized transcript → `numeric_claim_warns`. Write-back ONLY when a span changed, through the canonical `importFromContent` pipeline (page+tags+chunks+links in one transaction, content_hash recomputed, `noEmbed` — the phase-end sweep backfills; provenance nulls preserve the first-write record); bare `engine.putPage` is insufficient (pages row only — the embed sweep would embed stale chunk_text). Fail-open per page (read-back miss / write throw → count + continue; abort still unwinds). Kill switch `dream.synthesize.quote_verify` (default on). Telemetry shape = `QuoteVerifyStats` in `details.synthesis.quote_verify`. Pinned by `test/cycle-synthesize-verify.test.ts` + the write-path mini-eval harness `test/cycle-write-path-mini-eval.test.ts`.
- `src/core/cycle/triage-rescue.ts` — THE dream triage gate (`passesTriageGate`) + the verified-segment rescue (`applyTriageRescue`). Rescue fires only for scores in `[floor, threshold)` (floor inclusive; at/above threshold is the plain gate's job) with content_type in the buried-signal allowlist (default mixed/reflection/idea/strategy/people — never routine/technical) and ≥ minSegments of the judge's own segments verifying as normalized transcript substrings (`normForGrounding`, ≥40 chars, deduped by normalized quote — repetition is not more evidence). $0 — no LLM calls; fabricated segments cannot fire it; works on cached verdicts (gate-time only). Fail-closed on every malformed shape (null score, missing/short/non-string segments), never throws. `minSegments: 0` is the kill switch (gate degenerates to the plain threshold). ONE-GATE RULE: `runTriagePass` (report construction — `worth`/`rescued`/telemetry/dry-run), the synthesize fan-out, and `dream retriage` (reconcile-queue cancels + `--audit-rejects` sampling) all read this predicate — a second hand-rolled `score >= threshold` check is how an operator sweep cancels exactly the jobs the rescue admitted. Config: `dream.triage.rescue_floor` / `rescue_min_segments` / `rescue_content_types`. Pinned by `test/cycle-triage-rescue.test.ts` + the rescue suites in `test/cycle-synthesize-triage.test.ts` / `test/dream-retriage.test.ts`.
- `scripts/check-gateway-routed-no-direct-anthropic.sh` — CI guard that fails the build if `src/core/cycle/synthesize.ts` or `src/core/think/index.ts` reintroduces a runtime `new Anthropic()` constructor call or a value-shaped `import Anthropic from '@anthropic-ai/sdk'` import. Type-only imports (`import type Anthropic from '@anthropic-ai/sdk'`) stay allowed for adapter types; comment lines (`//` or ` *` prefixes) are excluded so JSDoc doesn't false-fire. Mirrors `scripts/check-jsonb-pattern.sh`. Wired into `bun run verify`. Extend `GUARDED_FILES` when migrating another file off direct SDK construction.
-- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home
-- `src/core/cycle/extract-facts.ts` — extract_facts cycle phase. Fence is canonical: per-page wipe (`deleteFactsForPage`) + reinsert from `parseFactsFence` + `extractFactsFromFenceText` + `engine.insertFacts`. The per-page wipe passes `excludeSourcePrefixes: ['cli:']` so conversation facts (written by `extract-conversation-facts`, on pages with NO `## Facts` fence to recreate them from) survive the reconcile instead of being deleted-with-nothing-to-reinsert. The destructive phase never inherits a failed sync's full-brain walk: `slugs: []` (a real incremental no-op) is distinguished from `slugs: undefined` (full-walk intent) by presence, not length. `runPhaseExtractFacts` (cycle.ts) surfaces a `warn` (`net_fact_deletion`) when the reconcile deletes at least `NET_DELETION_WARN_FLOOR` (50) more facts than it reinserts — the exact signature of a conversation-facts wipe. Empty-fence guard refuses when legacy rows (`row_num IS NULL AND entity_slug IS NOT NULL`) pend backfill (status: warn, hint: `gbrain apply-migrations --yes`). A phantom-redirect pre-pass runs AFTER the legacy-row guard, BEFORE the main reconcile loop: when `opts.brainDir` is set, `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun)` walks unprefixed-slug pages capped by `GBRAIN_PHANTOM_REDIRECT_LIMIT` (default 50). The pass returns `touched_canonicals` — canonical slugs whose disk fence merged with phantom rows; `runExtractFacts` UNIONs them into the main reconcile slug set so canonical's DB facts derive from the merged fence in the same cycle (handles phantom-had-only-on-disk-fence). `ExtractFactsResult` carries six phantom fields: `phantomsScanned`, `phantomsRedirected`, `phantomsAmbiguous`, `phantomsSkippedDrift`, `phantomsLockBusy`, `phantomsMorePending`. Three bubble to `CycleReport.totals` (`phantoms_redirected`, `phantoms_ambiguous`, `phantoms_skipped_drift`).
+- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps.
+- `src/core/cycle/extract-facts.ts` — extract_facts cycle phase. Fence is canonical: per-page wipe (`deleteFactsForPage`) + reinsert from `parseFactsFence` + `extractFactsFromFenceText` + `engine.insertFacts`. The reconcile is a no-op when the page's fence-owned DB rows already match the fence; drift on any dimension — content key `(claim, source)`, `row_num`, expiry/supersession state, or the `visibility` / `notability` cells — routes the page through the atomic wipe+reinsert (confidence is not compared). The per-page wipe passes `excludeSourcePrefixes: ['cli:']` so conversation facts (written by `extract-conversation-facts`, on pages with NO `## Facts` fence to recreate them from) survive the reconcile instead of being deleted-with-nothing-to-reinsert. The destructive phase never inherits a failed sync's full-brain walk: `slugs: []` (a real incremental no-op) is distinguished from `slugs: undefined` (full-walk intent) by presence, not length. `runPhaseExtractFacts` (cycle.ts) surfaces a `warn` (`net_fact_deletion`) when the reconcile deletes at least `NET_DELETION_WARN_FLOOR` (50) more facts than it reinserts — the exact signature of a conversation-facts wipe. Empty-fence guard refuses when legacy rows (`row_num IS NULL AND entity_slug IS NOT NULL`) pend backfill (status: warn, hint: `gbrain apply-migrations --yes`). A phantom-redirect pre-pass runs AFTER the legacy-row guard, BEFORE the main reconcile loop: when `opts.brainDir` is set, `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun)` walks unprefixed-slug pages capped by `GBRAIN_PHANTOM_REDIRECT_LIMIT` (default 50). The pass returns `touched_canonicals` — canonical slugs whose disk fence merged with phantom rows; `runExtractFacts` UNIONs them into the main reconcile slug set so canonical's DB facts derive from the merged fence in the same cycle (handles phantom-had-only-on-disk-fence). `ExtractFactsResult` carries six phantom fields: `phantomsScanned`, `phantomsRedirected`, `phantomsAmbiguous`, `phantomsSkippedDrift`, `phantomsLockBusy`, `phantomsMorePending`. Three bubble to `CycleReport.totals` (`phantoms_redirected`, `phantoms_ambiguous`, `phantoms_skipped_drift`).
- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`), render (`renderFactsTable`), and strip (`stripFactsFence({keepVisibility})` — the remote-read privacy boundary `get_page`/`fetch_page`/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: `replaceOrInsertFactsFence(body, fenceBlock)` replaces an existing fence in place or inserts a fresh `## Facts` section ABOVE the timeline sentinel (`timelineSentinelOffset`, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (`upsertFactRow`, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. `restoreHiddenFactRows(incoming, existing)` is the row-level, visibility-aware merge `import-file.ts` applies per fence-bearing column (compiled_truth AND timeline) when a remote caller writes back a page it read with hidden rows stripped — without it, a remote get→edit→put round-trip would silently drop every non-`world` fact row. Rules: only non-`world` rows of the existing fence are restoration candidates (a caller's deletion of a VISIBLE row stays honored — world rows are never restored); a hidden row whose rowNum is absent from the incoming fence is restored at its stable rowNum (cross-page `#F<N>` refs survive); a rowNum collision (a caller-authored addition landing on a hidden number the caller never saw) keeps the hidden row's number and renumbers the CALLER's row onto fresh appended numbers (upsertFactRow's append-only contract); same rowNum + same claim keeps the incoming version (idempotent full-content write-throughs); either side parsing with warnings returns null — re-rendering a fence that didn't fully parse would drop the caller's unparsed rows — and `factsGapWarning` surfaces exactly that residual loss. Pure and side-effect-free. Pinned by `test/facts-fence.test.ts` + the remote write-back describes in `test/privacy-strip-and-forget.test.ts` (row-level merge, world-only deletion honored, timeline-embedded fence round-trip).
- `src/core/fence-shared.ts` — shared pipe-table primitives for the `## Takes` (`takes-fence.ts`) and `## Facts` (`facts-fence.ts`) fences: `parseRowCells`, `isSeparatorRow`, `stripStrikethrough`, `parseStringCell`, `escapeFenceCell`. `parseRowCells` is escape-aware: `\|` stays inside its cell and decodes back to a literal `|` (exact inverse of `escapeFenceCell`), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. Pinned by the escape cases in `test/facts-fence.test.ts` + the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.
- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` → high-specificity fuzzy match for multi-token input (pg_trgm @ 0.7 threshold) → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence; shared-token company names below the threshold remain unresolved. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard).
@@ -451,7 +456,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/facts/phantom-audit.ts` — JSONL audit at `${resolveAuditDir()}/phantoms-YYYY-Www.jsonl`. Pattern copy of `src/core/audit-slug-fallback.ts` (ISO-week rotation, honors `GBRAIN_AUDIT_DIR`). Exports `logPhantomEvent(record)` + `readRecentPhantomEvents(days)` + `computePhantomAuditFilename(now?)`. Records every outcome: `redirected | ambiguous | drift | no_canonical | not_phantom_has_residue | pass_skipped_lock_busy`. Best-effort writes — stderr warn on failure, never throws. Separate file from `stub-guard-audit.ts` (distinct consumer + lifecycle: stub-guard logs PREVENTIVE blocks; phantom-audit logs CLEANUP decisions, to be read by a future `phantoms_pending` doctor check).
- `src/core/cycle/emotional-weight.ts` — Pure function `computeEmotionalWeight({tags, takes}, {highEmotionTags?, userHolder?})`. Deterministic 0..1 score: tag-emotion boost (max 0.5, case-insensitive match against `HIGH_EMOTION_TAGS` seed list), take density (0.1/take, capped at 0.3), take avg weight (0..0.1), user-holder ratio (0..0.1 over active takes; default holder `'garry'`). Total clamped to [0..1]. Anglocentric / personal-life-biased seed list intentional; override via config `emotional_weight.high_tags` (JSON array). `userHolder` overridable via `emotional_weight.user_holder`.
- `src/core/cycle/anomaly.ts` — Pure stats helpers for `find_anomalies`. `meanStddev` returns sample stddev (n-1 denominator) and (0,0) for empty input. `computeAnomaliesFromBuckets(baseline, today, sigma, limit)` takes densified daily-count buckets + today's counts per cohort, returns `AnomalyResult[]`. Zero-stddev fallback: cohort fires when `count > mean + 1`, with `sigma_observed = count - mean` as a finite sort proxy (no NaN). Brand-new cohorts (no baseline) have `mean=0, stddev=0` so the fallback fires at count >= 2. Sorted by `sigma_observed` desc, top `limit` (default 20). `page_slugs` capped at 50 per cohort.
-- `src/core/cycle/recompute-emotional-weight.ts` — Cycle phase orchestrator. Two SQL round-trips: `engine.batchLoadEmotionalInputs(slugs?)` → `computeEmotionalWeight` (per-row pure function) → `engine.setEmotionalWeightBatch(rows)`. Reads config `emotional_weight.high_tags` (JSON array, falls back to default seed list on parse error) and `emotional_weight.user_holder`. Empty `affectedSlugs` short-circuits with zero-work success. dry-run reports the would-write count without touching the DB. Engine throw bubbles into `status: 'fail'` with code `RECOMPUTE_EMOTIONAL_WEIGHT_FAIL` so the cycle continues.
+- `src/core/cycle/recompute-emotional-weight.ts` — Cycle phase orchestrator. One read plus bounded writes: `engine.batchLoadEmotionalInputs(slugs?)` → `computeEmotionalWeight` (per-row pure function) → `engine.setEmotionalWeightBatch(slice)` in slices of 1000 rows. Between slices it checks `opts.signal` (throws → `fail`), awaits `opts.yieldDuringPhase` (cycle-lock refresh / steal detection), fires `opts.onProgress`, and yields a macrotask (`setTimeout(0)`) so PGLite's synchronous statement execution never wedges the main thread for a whole-brain pass; `runCycle` wires these exactly like consolidate (`racedTimePhase` + `buildYieldDuringPhase` + `cycleSignal` + `progress.tick`). Both engines' `setEmotionalWeightBatch` rewrite only rows whose weight changes (`IS DISTINCT FROM` in the WHERE — no trigger fan-out on same-value rows) and return rows CHANGED; `details.pages_recomputed` = pages evaluated (feeds the cycle totals), `details.pages_updated` = rows changed. Reads config `emotional_weight.high_tags` (JSON array, falls back to default seed list on parse error) and `emotional_weight.user_holder`. Empty `affectedSlugs` short-circuits with zero-work success. dry-run reports the would-write count without touching the DB. Engine throw bubbles into `status: 'fail'` with code `RECOMPUTE_EMOTIONAL_WEIGHT_FAIL` so the cycle continues.
- `src/core/transcripts.ts` — `listRecentTranscripts(engine, opts)` library reused by both the `gbrain transcripts recent` CLI and the `get_recent_transcripts` MCP op. Reads `dream.synthesize.session_corpus_dir` + `dream.synthesize.meeting_transcripts_dir` config (same as `discoverTranscripts`); walks `.txt` files within `days`; applies the `isDreamOutput` guard from `transcript-discovery.ts` (skips dream-generated files); returns `{path, date, mtime, length, summary}[]` sorted newest-first. Summary mode (default true) = first non-empty line + ~250 trailing chars; full mode caps at 100KB/file. Missing/non-existent corpus dirs return `[]`, not error. Trust gate lives in the op handler, not here: the op throws `permission_denied` for `ctx.remote === true`; this is a trusted library function used by both the gated op and the local CLI.
- `src/core/operations-descriptions.ts` — Constants module for tool descriptions. Pinned via `test/operations-descriptions.test.ts`. Houses `GET_RECENT_SALIENCE_DESCRIPTION`, `FIND_ANOMALIES_DESCRIPTION`, `GET_RECENT_TRANSCRIPTS_DESCRIPTION` plus `LIST_PAGES_DESCRIPTION`, `QUERY_DESCRIPTION`, `SEARCH_DESCRIPTION`. Stable surface for the Tier-2 LLM routing eval — keeping them here keeps the test from binding to whatever is in `operations.ts` at test-run time.
- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`.
@@ -581,7 +586,7 @@ scorecards stay comparable over time. `finalizeScorecard`: `unresolvable_rate =
round-trip suite (CHECK admits unresolvable+NULL, still rejects partial+true and
unresolvable+true|false, pre-v80 NULL/NULL rows survive).
-- `src/core/cycle/base-phase.ts` — abstract `BaseCyclePhase` class. Enforces `sourceScopeOpts(ctx)` threading at the type level; rules out the source-isolation leak class structurally for every new phase. Inherits source-scope, budget meter, error envelope, progress reporter. propose_takes / grade_takes / calibration_profile all extend it. The ONE home of `CYCLE_DEADLINE_RESERVE_MS` (60s carved out of the enclosing job's remaining wall-clock — wait-poll + worker force-evict grace + cleanup headroom; patterns.ts re-exports it) and of `BasePhaseOpts.deadlineAtMs` (the enclosing minion job's absolute deadline, threaded via runCycle; null/unset for direct `gbrain dream` callers — phases then fall back to their derived defaults).
+- `src/core/cycle/base-phase.ts` — abstract `BaseCyclePhase` class. Enforces `sourceScopeOpts(ctx)` threading at the type level; rules out the source-isolation leak class structurally for every new phase. Inherits source-scope, budget meter, error envelope, progress reporter. propose_takes / grade_takes / calibration_profile all extend it. `run()` honors dry-run for every subclass at once: when `opts.dryRun` or `ctx.dryRun === true`, it returns `status: 'skipped'` / `reason: 'no_dry_run_support'` before `process()` (no LLM calls, no take_proposals / take_grade_cache / calibration_profiles writes) — the same skip shape extract and resolve_symbol_edges use; runCycle threads `dryRun` into all three call sites. The ONE home of `CYCLE_DEADLINE_RESERVE_MS` (60s carved out of the enclosing job's remaining wall-clock — wait-poll + worker force-evict grace + cleanup headroom; patterns.ts re-exports it) and of `BasePhaseOpts.deadlineAtMs` (the enclosing minion job's absolute deadline, threaded via runCycle; null/unset for direct `gbrain dream` callers — phases then fall back to their derived defaults).
- `src/core/cycle/propose-takes.ts` — LLM scans markdown prose, proposes gradeable claims to the `take_proposals` queue. Candidate discovery excludes `extract_receipt` pages before the LLM call so the phase never re-ingests its own operational receipts; nullable legacy page types remain eligible. Idempotency cache on `(source_id, page_slug, content_hash, prompt_version)` composite unique index. Fence-dedup: existing canonical takes passed to the extractor as context. Ships a stub prompt; tuned prompt arrives via the synthetic corpus build. Per-page extractor failures log a warning and continue, but a whole-run condition (per `classifyGlobalLlmError` in `src/core/ai/errors.ts`) breaks the page loop with a single combined warning line, sets `aborted_global_error`, and records a halt in the rollup — auth/billing on the first hit, bare rate_limit only after `RATE_LIMIT_HALT_STREAK` (3) consecutive hits (a successful call resets the streak). Status: `fail` when the halt happened with ZERO successful extractor calls (the whole LLM lane is down), otherwise any warnings fold into `warn` + ` (N warning(s))` summary suffix, so swallowed failures can't read as a clean `ok`. `llm_calls_succeeded`/`llm_calls_failed`/`halted` land in details. The phase wall-clock deadline is DERIVED, never a literal (a literal equal to the autopilot-cycle handler anchor, with non-co-started clocks, would make the clean `deadline_hit` partial-completion path structurally unreachable): explicit `opts.deadlineMs` wins (test seam), else `resolveProposeTakesDeadlineMs(deadlineAtMs, now)` = `PHASE_DEADLINE_FRACTION_OF_JOB` (0.8, headroom for grade_takes + calibration_profile which run after it with no deadline of their own) × (remaining job budget − `CYCLE_DEADLINE_RESERVE_MS`), clamped to the fallback (0.8 × the `autopilot-cycle` entry in `HANDLER_DEFAULT_TIMEOUT_MS` — a missing anchor throws at module LOAD, failing the whole cycle visibly). A fractioned value under `MIN_PROPOSE_TAKES_BUDGET_MS` (2 min) resolves to null and the phase returns an honest `skipped` with `reason: 'insufficient_cycle_budget'` (after the cheap provider probe, before any rollup/DB write — records neither a halt nor a completed round; next cycle retries with a fresh budget). Pinned by `test/propose-takes.test.ts` + `test/propose-takes-per-claim.test.ts` + `test/cycle-phase-deadline-drift.test.ts`. The kind vocabulary is `TAKE_KIND_VALUES` imported from `src/core/takes-fence.ts` (the fence enum — no hand-copied set); an unknown kind maps through the legacy-kind table, else `take`.
- `src/core/cycle/grade-takes.ts` — walks unresolved takes older than 6 months, retrieves evidence, asks judge model, caches verdict. Auto-resolve DISABLED by default. Conservative thresholds: >=0.95 single OR >=0.85 ensemble 3/3 unanimous. `aggregateEnsemble` reuses the cross-modal substrate; fires on the borderline 0.6-0.95 band. Writes to `take_grade_cache`. Same global-error posture as propose-takes: a judge failure that classifies as a whole-run condition breaks the take loop with `aborted_global_error` (auth/billing first hit; rate_limit after 3 consecutive takes; `fail` status when zero judge calls succeeded, else `warn` + warning count; `judge_calls_succeeded`/`judge_calls_failed`/`halted` in details). Rejected ensemble judges are classified the same way — `Promise.allSettled` never flattens a revoked key or exhausted spend limit into a silent null verdict. Per-take auto-apply failures stay per-take.
- `src/core/cycle/calibration-profile.ts` — aggregates resolved takes into 2-4 narrative pattern statements + active bias tags. Voice-gated via `gateVoice()`. Cold-brain skip when <5 resolved. Writes to `calibration_profiles` with audit columns (`voice_gate_passed`, `voice_gate_attempts`, `grade_completion`).
@@ -619,7 +624,7 @@ Key files:
- `src/core/schema-pack/mutate-audit.ts` — ISO-week JSONL at `~/.gbrain/audit/schema-mutations-YYYY-Www.jsonl`. Privacy-redacted: type names → sha8, prefixes → first slug segment only, matches `candidate-audit.ts` privacy posture. Logs BOTH success AND failure events so the `schema_pack_writability` doctor check has signal. `summarizeMutations()` is the cross-surface parity primitive.
- `src/core/schema-pack/registry.ts` — `resolvePack` walks the `extends` chain (depth cap via `EXTENDS_DEPTH_WARN` / `EXTENDS_DEPTH_HARD_CAP`), RETAINS each ancestor manifest, materializes `borrow_from`, and composes all of it into `resolved.manifest` through `mergeInheritedManifest`. Every downstream consumer reads `resolved.manifest`, so doing the merge here is what makes inheritance visible without per-consumer wiring. `borrow_from` is selective (only the named `types` / `link_types`, and only from the target's OWN declarations), non-transitive, and fail-closed — a missing target throws `UnknownPackError` via `loadByName`, matching the extends path; an omitted category borrows none of it. The alias graph + closure hash are computed on the MERGED manifest, so a cross-pack alias cycle surfaces as `AliasCycleError` at resolve. `manifest_sha8` / `packIdentity` stay the CHILD's own bytes — a parent edit does not move the child's identity, so the invalidation path is what keeps a child honest. `invalidatePackCache(name?)` walks the extends-chain reverse-graph (editing a parent pack must not leave children stale). `tryCachedPack(name)` TTL-gated fast path: inside `STAT_TTL_MS` (default 1000ms, env `GBRAIN_PACK_STAT_TTL_MS`) returns cached without statting; outside the window it stats every TRACKED file — the extends chain PLUS every borrowed pack — and cascade-invalidates on mtime change (cross-process detection), so editing a borrowed pack invalidates its borrowers. Pinned by `test/schema-pack-registry.test.ts` + `test/schema-pack-merge.test.ts`.
- `src/core/schema-pack/merge.ts` — the pure child-wins composition helper behind `resolvePack`. `mergeInheritedManifest(ancestorsBaseFirst, child, borrowed)` returns the fully-composed manifest; precedence is child → borrowed → nearest parent … → base. SIX ingest/query-shaping fields inherit: `page_types`, `link_types`, `frontmatter_links`, `enrichable_types`, `filing_rules`, `takes_kinds`. `phases` + `calibration_domains` are DELIBERATELY child-only — they gate real cycle execution (`cycle.ts` `packDeclaresPhase`), so inheriting them would silently run phases a pack never declared; `mapping_rules`, `migration_from`, `extends`, `borrow_from`, and the identity fields are child-only too (all ride the `...child` spread). `mergePageTypes` carries the ordering contract `inferTypeFromPack` depends on (first-`path_prefix`-match-wins, array order): the BASE (root, `extends: null`) pack is the ordered foundation/tail; an override of a base type keeps the base POSITION (`Map.set` updates the value, keeps insertion order) so base's curated priority survives; a genuinely-new type from ANY non-base layer — child, borrowed, or a middle pack — is PREPENDED nearest-first, so a more-derived prefix wins regardless of chain depth. `mergeByKey` keeps the first occurrence per key walking highest-precedence-first (the order-insensitive keyed fields); `frontmatter_links` keys on `page_type\x00link_type` — a NUL, not a space, because both are unconstrained strings and a space-join would collide `{"a b","c"}` with `{"a","b c"}`. `mergeUnion` backs `takes_kinds`: UNION not replace, because the Zod default makes an omitted field indistinguishable from an explicit one — so a child can ADD kinds but CANNOT narrow below base ∪ parent. Pure + deterministic: no disk, no engine. Pinned by `test/schema-pack-merge.test.ts`.
-- `src/core/schema-pack/best-effort.ts` — `loadActivePackBestEffort(ctx)` returns `ResolvedPack | null`. Single source of truth for the pack-aware wiring sites. `null` means EMPTY FILTER (NOT hardcoded defaults, which would silently violate the pack).
+- `src/core/schema-pack/best-effort.ts` — `loadActivePackBestEffort(ctx)` returns `ResolvedPack | null`. Single source of truth for the pack-aware wiring sites. `null` means EMPTY FILTER (NOT hardcoded defaults, which would silently violate the pack). Threads the tier-4 DB-plane `schema_pack` from `ctx.engine`, so every caller resolves the SAME pack `schema active` / `get_active_schema_pack` report. `readDbSchemaPack(engine?)` is the ONE spelling of that tier-4 read (null-safe, never throws, trims empty to undefined) — shared by both loaders here, the CLI inspection verbs (`schema show/graph/lint/explain`, via `readDbSchemaPackConfig` in `src/commands/schema.ts`, which keeps the cfg-null gate so an unconfigured home never cold-creates a PGLite dir) and the MCP `schema_lint`/`schema_graph`/`schema_explain_type` ops. `loadActivePackForLocalEngine(engine)` is the `remote: false` + FILE-ONLY-config variant for local engine-backed surfaces. Pinned by `test/schema-pack-best-effort.test.ts`, `test/operations-schema-pack.test.ts`, `test/schema-cli-db-config.serial.test.ts`.
- `src/core/schema-pack/type-usage.ts` — stored-type classifier behind the alias-footgun visibility surfaces: `classifyStoredType(type, pack)` → canonical | alias_of (with the canonical type + `path_prefixes[0]` filing directory) | undeclared, over a STRUCTURAL pack shape so import-file's thin `activePack` and the full manifest both satisfy it. `sanitizeTypeForDisplay` strips control chars + caps length (type strings come from frontmatter and get echoed into terminals); `renderTypeWarningSummary` renders the once-per-type-per-run lines. Consumers: `importFromContent` (advisory `ImportResult.type_warning` at the typeExplicit site — the type is still stored literally, zero filing change), sync/import summary aggregation (+ `SyncResult.type_warnings` so worker-driven syncs surface counts in job results), the `stored_type_is_alias`/`stored_type_undeclared` data-plane lint rules, all gated by config `schema.type_warnings` (default on; lint rules always active). Pinned by `test/schema-type-usage.test.ts`.
- `src/core/schema-pack/lint-rules.ts` — 14 pure rule functions. `withMutation`'s pre-write validation gate composes the 10 file-plane rules; the 4 DB-aware rules (`extractable_empty_corpus`, `mutation_count_anomaly`, `stored_type_is_alias`, `stored_type_undeclared`) need an engine (CLI `--with-db`; the stored-type pair accepts `LintOpts.sourceId` scoping, not yet threaded from the CLI). Single source of truth consumed by CLI lint + MCP `schema_lint` + the pre-write validation gate. File-plane rule `link_regex_catastrophic_backtrack` — advisory ReDoS pre-screen flagging the classic nested-quantifier shapes (`(a+)+`, `(a*)*`, `(a+)*`, `(\w+)+`) in a link_type's `inference.regex` via `NESTED_QUANTIFIER_RE`. WARNING not error: a hard reject would disable the whole pack on upgrade (pages fall back to legacy typing). The runtime input-length cap in `redos-guard.ts` is the actual safety net; this rule tells the pack author to fix the pattern.
- `src/core/schema-pack/redos-guard.ts` + `src/core/schema-pack/link-inference.ts` — ReDoS hardening for pack inference regexes. `redos-guard.ts` provides `MAX_REGEX_INPUT_CHARS` (default 64_000, env `GBRAIN_MAX_REGEX_INPUT_CHARS`) — a hard input-length cap, the real runtime safety net (catastrophic backtracking needs a long input; a link-extraction `context` is normally a sentence or short paragraph). Over the cap, `runRegexBounded` throws the tagged `RegexInputTooLargeError` and the regex is skipped (degrade-to-mentions) without entering the `node:vm`. `link-inference.ts:inferLinkTypeFromPack` no-budget branch (test contexts) routes through `runRegexBounded` so the input-length cap + per-regex vm timeout (`PER_REGEX_TIMEOUT_MS = 50`) apply on every path. Defensive hardening + diagnostics; the deterministic ~3100-file sync-wedge root cause remains open. Pinned by `test/redos-hardening.test.ts` + `test/schema-pack-lint-rules.test.ts`.
@@ -663,7 +668,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche
- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath; non-TTY requires `--yes`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with the `LIVE_SERVE` escape hatches when no token was supplied and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/e2e/bootstrap-harness-lifecycle.serial.test.ts`.
- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`.
- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure).
-- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content); also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to `entryToTurn` — that function's placeholder-only `[tool: name]` rendering is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.
+- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). `genuineUserTurnIndexes` separately records user-role turns containing real text blocks, because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.
- `src/core/transcripts/grok.ts` — the Grok Build (grok CLI) transcript adapter: one session directory (`~/.grok/sessions/<url-encoded-cwd>/<uuid>/chat_history.jsonl`) = one session; `GROK_HOME` relocates the root. Turn selection is STRUCTURAL (`mapGrokLine`, exported so the dated `SPEC_TARGET` mapping is pinned): user turns are `type:'user'` text blocks WITHOUT `synthetic_reason` (injected system_reminder/task_completed rows are `typed`, i.e. intentionally text-free, as are tool_result-only user arrays); assistant turns need non-empty string `content` (tool-only rows — `content` ''/null WITH `tool_calls` — are `typed`); system/reasoning/tool_result/backend_tool_call rows are `typed`; unknown row types `skip`. A recognised HUMAN-turn row whose content this parser cannot decode (user `content` missing / non-string / non-array / an array holding non-block entries; assistant non-string `content` with no `tool_calls`) is `malformed` and counted as SKIPPED, never typed, so a file made only of such rows is never `expectedEmpty` — the ingest drift signal fires (`bytesRead > 0`, sessions 0, `cleanScan=false`, watermark frozen) and `zeroSessionsReason` names the malformed row count, instead of an upstream schema change silently advancing the watermark past whole conversations. `chat_history.jsonl` carries NO per-message timestamps: session times come from the sibling `summary.json` (`created_at`/`last_active_at`; a malformed summary is ignored, an unparseable date is never fabricated) and, because grok writes `summary.json` at session END, an in-progress session or partial rsync falls back to the log file's own mtime — a real filesystem time — with `raw.timestamp_source` stamped `'summary.json'` vs `'file_mtime'` so consumers can tell them apart (without the fallback the render refusal would freeze the `--since-last` watermark for the whole grok root). Every message carries the session bounds (last message = `last_active_at`, the rest = start). Session id: summary → UUID dir name → `stableIdFromPath` (a sha256 prefix of the log path, never the bare `chat_history` basename, which would collapse every such session onto one page). Sidecars (updates.jsonl, events.jsonl, rewind_points.jsonl, summary.json, prompt_history.jsonl) are not sessions — discover.ts's grok-sidecar filter is scoped to PROVEN grok trees and the head sniff rejects claude-family keys (grok detection runs after claude-code; an oversized system head still detects through the truncated-line sniff); a percent-encoded cwd segment that fails to decode yields `cwd` undefined with the session id intact.
- `src/core/transcripts/capture-spec.ts` + `codex-hook-lane.ts` — the per-harness session-end capture seam. `capture-spec.ts`: the satisfies-anchored `CAPTURE_SPECS` record ({confine, parse, discover?}) for the STDIN-DRIVEN lanes (claude-code, codex); `captureSpecFor()` resolves unknown/undefined/opencode to the claude spec (golden-pinned by `test/codex-hook-lane.test.ts`); openclaw is deliberately NOT a member (its lane is in-process, trusted-plane — see context-engine.ts). `codex-hook-lane.ts`: `confineCodexTranscriptPath` (the same S3#8 ladder as the claude root, pinned at BOTH `codexSessionsDir()` AND `codexArchivedSessionsDir()` — codex MOVES a rollout into the flat `archived_sessions` store on archive, so fencing only the live store refused a still-valid path; both CODEX_HOME-resolved since the spawner IS codex; an explicitly pinned test-seam `root` stays single-root; ENOENT/ENOTDIR on the path is `missing_path` — the rung hook.ts gates its discovery fallback on — while `unreadable` is reserved for EACCES/IO faults, so the codex session-end heartbeat reason for a nonexistent `transcript_path` after a failed discovery is `transcript_missing_path`, not `transcript_unreadable`; no WSL branch v1), `parseCodexHookTranscript` (ParsedTranscript shape over the adapter's exported `mapCodexLine`; same OPT-IN `collectToolCalls` contract as `parseTranscript`, and the same `capToolCallInput` bound on observed args; head+tail over budget so session_meta identity survives; tool calls from the OBSERVED args keys — `custom_tool_call.input` fixture-verified, `function_call.arguments` source-verified at rust-v0.147.0; tolerant JSON-string parse; NO `result` join — 0.147.0 persists no success flag on `*_output` rows; `compacted` rows become boundary positions), and `discoverNewestCodexRollout` (bounded newest-first walk over the dated live store, then a flat pass over the archived store under the SAME 4096 dirent cap — skipped once the cap trips; id-in-filename match, and an id-matched archived hit keeps `transcript_discovered` (never relabelled `_newest`, which hook.ts reads as a guess and bars from the relay); symlink-reject — the fallback for `transcript_path: null` or a moved rollout, and the seam for SIGKILL'd sessions, which never fire SessionEnd). Engine-free by construction; never imports discover.ts. Pinned by `test/codex-hook-lane.test.ts` + `test/codex-hook-lane-archived.test.ts` + the runHook-driven matrix in `test/memorable-relay.serial.test.ts`.
- `src/core/wsl-paths.ts` — WSL Windows-drive path translation shared by the doctor asset checks (`src/commands/doctor-asset-paths.ts`) and hook-transcript confinement (`confineTranscriptPath` above). Exports `WINDOWS_DRIVE_PATH_RE`, `translateWindowsPath(p, mountRoot)` (`C:\Users\x\file` → `<mountRoot>/c/Users/x/file`; null for non-drive input so callers keep the original untouched), `parseWslAutomountRoot(conf)` (the `/etc/wsl.conf` `[automount] root` value, default `/mnt`), and `detectWslMountRoot()` (null off-WSL). Mechanical detection + translation only — POLICY stays with callers (skip vs stat vs confine): the hook lane confines the translated path to the known Claude config tree, doctor decides skip-vs-stat. Pinned by the WSL cases in `test/claude-code-jsonl.test.ts`.
@@ -680,7 +685,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche
- `src/core/facts/writeback-audience.ts` — personal-vs-shared classifier for the consent nudge. Declaration (`brain.audience`, stamped by company-brainify's Phase-5 handoff, the bootstrap interview's SURFACE_MULTIUSER answer — applied the moment `interview --set` records it, BEFORE the agent runs init — or the operator) BEATS the conservative heuristic (≥3 distinct non-automation MCP clients active 30d via `mcp-usage.ts`, `likely_automation` excluded); `reasons[]` always names the evidence. The machine-global file-mirror declaration speaks for the HOST brain only — a mounted/selected brain falls through to its own DB row or heuristic. Fail directions: config read failure → `unknown` (nudge stays silent), usage-read failure with a reachable DB → `personal` (missing multi-client infra is personal-shaped). Never enables anything.
- `src/core/onboard/writeback-nudge.ts` — the fire-once consent ASK (init epilogue + `runPostUpgrade`): double gate (sentinel `memory.auto_writeback_notice_shown` + setting unset), personal-audience only, suppressed on mounts/thin-clients/env bypass, `[AGENT]`-relayed disclosure + ask (non-TTY IS the relay path — deliberately unlike runInitNudge), sentinel stamped AFTER printing (a decline is permanent; a shared classification does NOT burn the sentinel), whole body try/caught (init/upgrade must survive a crashing nudge). The recurring reminder is `src/core/advisor/collect-writeback-consent.ts` (info, `ask_user`, NO dispatch_id — consent is never `--apply`-able; local-only; fires only AFTER the sentinel so the advisor is never the first ask).
- `src/core/bootstrap/instructions-block.ts` — the managed harness block (`<!-- gbrain:ambient-writeback:begin/end -->`): spliceCompiledBlock discipline verbatim (idempotent replace-interior, THROW on damaged markers, marker-equal body lines neutralized), header names mode + serve endpoint (multi-brain last-wins stays visible), remove/strip helpers never delete a user file. Harness lane (`src/core/bootstrap/harness.ts`): `kind:'instructions'` targets (additive under receipt version 1 — old binaries won't unwire them, documented) for user-scope CLAUDE.md + `$CODEX_HOME/AGENTS.md` (paths + the AGENTS.override.md exclusivity probe are dated PROVISIONAL spec entries in `host-specs.ts`); enabled ⇒ install, disabled ⇒ CONVERGE (strip blocks + receipt targets + advisory line; a strip FAILURE is recorded as a failed `instructions` receipt target so --status/--remove/the next converge keep tracking the orphan); registrar mode (non-loopback --url) NEVER installs blocks — the local mirror speaks for the local brain, and the remote brain's own MCP instructions carry the contract when its operator opts in; a block installs only when the SAME host's MCP target confirmed (both lanes — a foreign-registration refusal or failed write must not leave a block directing saves at a server this run never registered), and a failed final smoke STRIPS the blocks this run installed (targets marked failed) so no block outlives its rolled-back registration; `--remove`/`--status` wired.
- - Stop-hook backstop lane: `hookStop` in `src/commands/hook.ts` (own 2s deadline inside Stop's 10s cap, fail-open exit 0, file-plane gate, 128KB-tail transcript parse with ONE 2MB-cap retry when no user turn is found — turn OFFSET from EOF ≠ turn size; a big tool_result would otherwise silently lose the turn — then gate → secret-scanned `bankWritebackTurn` [corpus-segments.ts: `<session>.wb-<hash24>[.src-<sourceId>].txt` — the source segment lets the SWEEP fallback file the turn into the session's own source; scanner-unavailable = fail-closed skip] → `requestContextPack(bankOnly, flushCorpusFile, trigger:'writeback-bank', sourceId from GBRAIN_SOURCE)`; every outcome a typed `writeback-bank` heartbeat reason — by-design skips [gate reasons, no_user_turn, flush_skip_*] ride `outcome:'ok'`, 'degraded' is INFRA faults only) → `src/mcp/context-pack-handler.ts` tags `.wb-` basenames `lane:'writeback'` → `checkpoint-harvest.ts`'s writeback lane (AUTHORITATIVE serve-side `memory.auto_writeback` re-check with `{gate:true}` + loadConfig drift input — off ⇒ terminal `.ingested {skipped:'writeback_off'}`; `plane_drift`/invalid mode/read_error/non-transport extraction skip [`extract_skipped_*`: refusal/content_filter/malformed_output class] ⇒ NO sidecar, file survives for the sweep; salient ⇒ `notabilityFilter:'medium-and-up'`; `source:'hook:writeback'`; NO manifest publish; per-session prompt-harvest cap `WRITEBACK_SESSION_CAP=30` in a true-LRU counter map [delete-before-set on increment], budget burned only on real enqueues, overflow = ACK-only skip the sweep batch-extracts; heartbeats under `event:'writeback'` with PERSISTED inserted/duplicate/superseded). The sweep's corpus pass recognizes `.wb-` files, applies the same gate semantics, routes to the FILENAME-banked source (isValidSourceId-checked, pass source as fallback), and records `skipped_reason` in its terminal sidecar (`src/core/sweep.ts`) — leftover banked turns never bypass the OFF gate and never silently zero out. wb-file state machine: ack-only skips leave the file for the sweep; `writeback_off` is the one terminal skip sidecar.
+ - Stop-hook backstop lane: `hookStop` in `src/commands/hook.ts` (own 2s deadline inside Stop's 10s cap, fail-open exit 0, file-plane gate, 128KB-tail transcript parse selecting the newest structurally genuine user turn via `genuineUserTurnIndexes`, with ONE 2MB-cap retry when the cheap tail contains none — turn OFFSET from EOF ≠ turn size, and Claude's user-role tool-result placeholders neither shadow the prompt nor suppress the retry — then gate → secret-scanned `bankWritebackTurn` [corpus-segments.ts: `<session>.wb-<hash24>[.src-<sourceId>].txt` — the source segment lets the SWEEP fallback file the turn into the session's own source; scanner-unavailable = fail-closed skip] → `requestContextPack(bankOnly, flushCorpusFile, trigger:'writeback-bank', sourceId from GBRAIN_SOURCE)`; every outcome a typed `writeback-bank` heartbeat reason — by-design skips [gate reasons, no_user_turn, flush_skip_*] ride `outcome:'ok'`, 'degraded' is INFRA faults only) → `src/mcp/context-pack-handler.ts` tags `.wb-` basenames `lane:'writeback'` → `checkpoint-harvest.ts`'s writeback lane (AUTHORITATIVE serve-side `memory.auto_writeback` re-check with `{gate:true}` + loadConfig drift input — off ⇒ terminal `.ingested {skipped:'writeback_off'}`; `plane_drift`/invalid mode/read_error/non-transport extraction skip [`extract_skipped_*`: refusal/content_filter/malformed_output class] ⇒ NO sidecar, file survives for the sweep; salient ⇒ `notabilityFilter:'medium-and-up'`; `source:'hook:writeback'`; NO manifest publish; per-session prompt-harvest cap `WRITEBACK_SESSION_CAP=30` in a true-LRU counter map [delete-before-set on increment], budget burned only on real enqueues, overflow = ACK-only skip the sweep batch-extracts; heartbeats under `event:'writeback'` with PERSISTED inserted/duplicate/superseded). The sweep's corpus pass recognizes `.wb-` files, applies the same gate semantics, routes to the FILENAME-banked source (isValidSourceId-checked, pass source as fallback), and records `skipped_reason` in its terminal sidecar (`src/core/sweep.ts`) — leftover banked turns never bypass the OFF gate and never silently zero out. wb-file state machine: ack-only skips leave the file for the sweep; `writeback_off` is the one terminal skip sidecar.
- Read-time TTL validity (there is no sweeper): ACTIVE fact reads in BOTH engines (`listFactsByEntity/Since/BySession`, both `findCandidateDuplicates` branches, `countUnconsolidatedFacts`, `getFactsHealth` active buckets) carry `AND (valid_until IS NULL OR valid_until > now())` — `valid_until` is temporal validity, not retention; history paths (`listSupersessions`, `findTrajectory`, `--asof`) deliberately still see lapsed rows; a re-stated expired fact re-inserts fresh. Pinned by `test/facts/ttl-validity.test.ts` + engine-parity additions.
- Diagnostics: `src/commands/doctor/checks/memory-writeback.ts` (`memory_writeback`, BRAIN category) — quiet-ok when off, but the OFF branch still probes receipt + canonical instruction paths and WARNS on a lingering block (off-but-still-instructing) with the converge command; plane-compare warns when the file mirror disagrees with the DB row (the Stop hook acting on the wrong truth) naming the re-sync; a read_error reports the state as UNKNOWN, never "off (default)"; resolved bundle + BOTH visibility postures + audience/reasons; instruction blocks receipt-vs-live-probe-vs-drift compare (drift fix names the `config set` + `bootstrap harness` combo — the config set re-stamps the posture mirror so the re-render converges even after an out-of-band visibility flip) + AGENTS.override.md detection — and a receipt target in state `failed` is a STANDING warn regardless of the live probe (the one physical-survival path — a smoke-rollback strip that itself threw — leaves a current-looking block directing sessions at a rolled-back endpoint, and only the receipt state knows) naming the `bootstrap harness --yes` / `--remove` converge; validity-lapsed count; 7d counters (verbs usage sidecar's additive `remember_status` [stamped in `src/mcp/dispatch.ts`, ALL-MCP-callers semantics labeled honestly] + `writeback`/`writeback-bank` heartbeat events; `turns_banked` counts flush_skip_* — banked, enqueue declined) with the local/lossy disclosure. Null-engine runs report the file mirror honestly.
- Tests: `test/writeback-config.test.ts`, `test/mcp-instructions-writeback.test.ts`, `test/facts/writeback-gate.test.ts`, `test/hook-writeback-stop.serial.test.ts`, writeback-lane cases in `test/checkpoint-harvest.serial.test.ts`, `test/bootstrap-instructions-block.test.ts` + harness serial additions, `test/writeback-nudge.serial.test.ts`, `test/doctor-memory-writeback.serial.test.ts`, the hermetic 5-step `test/ambient-writeback-lifecycle.serial.test.ts`, and the NON-GATING real-codex door (`test/e2e/bootstrap-real-codex.serial.test.ts`, ambient-writeback describe).
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index 5ba007e4f8..67926cc358 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -135,7 +135,7 @@ For `detail: 'high'` searches, `src/core/search/expansion.ts` runs a Haiku-class
The fix is budget-normalized weighted RRF, composed in `src/core/search/fusion-lists.ts`. Every vector list is a role-tagged arm (`original` | `variant` | `clause` | `image`) — tagged objects, never a positional convention, so a failed arm or a fell-open image branch can't mis-tag a list. The `original` arm always fuses at weight 1; the non-empty `variant`/`clause` arms share ONE total weight budget, `search.expansion_variant_budget` (`weight_i = b / n_voting_arms`, each row scored `weight / (k + rank)`), so total expansion influence is exactly `b` however many variants the LLM produced. `null` — the default in all three mode bundles — is the legacy equal-weight fusion (every list weight 1, byte-identical). A budget in (0, 4] is set with `gbrain config set search.expansion_variant_budget <b>`, per call via `HybridSearchOpts.expansionVariantBudget`, or pinned per eval arm with `gbrain eval longmemeval --expansion-variant-budget <b>` (sweep it against frozen `--expansion-replay` variants so cells differ only in `b`). Arithmetic: two variants agreeing on a distractor at rank 0 tie the original's rank-0 vote exactly at `b = 1.0`; legacy with two variants is ≈ `b = 2.0`; `b = 0.5` subordinates them. The knob is a no-op when expansion is off and folds into the query-cache key (`evb=`). Outcome (ranker wave, 2026-09-06, recorded Haiku variants replayed at every budget): the mechanism is real — strict `recall_all@5` rises from 255/470 at the legacy weighting to 394/470 at budget 0.25 — but its pre-registered rule (≥ plain hybrid − 2 on the 430-question decision set, no type losing > 1) failed at every budget (0.25: −43; plain hybrid 439/470), so every bundle keeps `expansion_variant_budget: null` and the knob is an operator lever. The receipts point at a trigger rather than a weight (expand only when the original query's evidence is weak), filed as the next pre-registered mechanism.
-Expansion is opt-in per mode bundle (`tokenmax` on by default; `balanced` + `conservative` off). Default off in the cheap tiers because the LLM call adds ~$0.001/query and ~200ms — real money at scale. The `query` op is the exception: it defaults `expand: true` per call (pass `expand: false` to opt out) — expansion-by-default is what makes it the concept/landscape verb.
+The mode bundles carry an `expansion` value (`tokenmax` true; `balanced` + `conservative` false — off in the cheap tiers because the LLM call adds ~$0.001/query and ~200ms, real money at scale), but the bundle value (and the `search.expansion` config key) only reaches a caller that leaves `expansion` unset AND wires an `expandFn`, and no shipped verb does today. The `query` op defaults `expand: true` per call in every mode (pass `expand: false` / `--no-expand` to opt out) — expansion-by-default is what makes it the concept/landscape verb — while `search`, the memory verbs and the eval harnesses pin expansion per call. `gbrain search modes` reports the bundle value, not what `query` does.
## Putting it together
@@ -371,7 +371,10 @@ Markdown chunk creation applies the strict protected-body sanitizer before
splitting text. For remote reads, all existing chunks are withheld until a
successful rebuild records the current chunker version. Public pages require
this rebuild too; trusted local chunk reads remain available. Body or chunk changes
-invalidate that record until the next successful rebuild. Direct page reads
+invalidate that record until the next successful rebuild. While pages are withheld,
+remote `search` / `query` report `degraded: [safe_index_pending]` (the MCP
+empty-result block names it) instead of a clean miss, and `gbrain doctor` counts
+the withheld pages and points at the `gbrain reindex --markdown` fix. Direct page reads
continue to use current source and visibility policy plus body sanitization.
Run rebuild commands from a local installation on the brain host; thin clients
diff --git a/docs/architecture/pack-upgrade-mechanism.md b/docs/architecture/pack-upgrade-mechanism.md
index 11a1364b8f..382b0ceb93 100644
--- a/docs/architecture/pack-upgrade-mechanism.md
+++ b/docs/architecture/pack-upgrade-mechanism.md
@@ -54,7 +54,7 @@ that tuple lights up the `pack_upgrade_available` onboard check.
│ gbrain onboard --check shows finding │
│ gbrain onboard --check --explain shows per-cluster narrative │
│ User reviews; if OK, runs: │
-│ gbrain jobs submit unify-types --allow-protected \ │
+│ gbrain jobs submit unify-types \ │
│ --params '{"target_pack":"gbrain-base-v2","apply":true}' │
│ (omit "apply":true for a dry-run; that is the default) │
│ (Autopilot never auto-fires this; manual_only) │
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 71dc8e916c..d12b0c1d6c 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -55,7 +55,7 @@ from the markdown contract.
| **Takes** (incl. hunches, bets) | `## Takes` fenced table between `<!--- gbrain:takes:begin -->` / `:end -->` markers | `takes` | `extract takes` |
| **Facts** | `## Facts` fenced table between `<!--- gbrain:facts:begin -->` / `:end -->` markers | `facts` | `extract_facts` cycle phase |
| **Links** | Inline `[text](slug)` / `[[slug]]` in markdown body + frontmatter `direction: incoming` | `links` | `extract links` |
-| **Timeline** | `## Timeline` section after `<!-- timeline -->` sentinel | `timeline_entries` | `extract timeline` |
+| **Timeline** | Dated markers anywhere in the page body — compiled truth AND the `## Timeline` section: `- **YYYY-MM-DD** \| Source — Summary` bullets, `### YYYY-MM-DD — Title` headers (FS extract), and inline `[Source: <text>, YYYY-MM-DD]` citations (one row per citation, dated by the citation, summary = the bullet/paragraph it sits in). The `<!-- timeline -->` sentinel only splits compiled_truth from timeline for storage; it does not scope extraction | `timeline_entries` | `extract timeline` + `put_page`'s `auto_timeline` |
| **Tags** | Frontmatter `tags:` YAML array | `tags` | `importFromFile` (reconciles per-page on import) |
| **emotional_weight** | Recomputed from takes + tags | `pages.emotional_weight` (signal column) | `recompute_emotional_weight` cycle phase |
| **synthesis_evidence** | FK into `takes` rows (`slug#N`) inside synthesis pages | `synthesis_evidence` | `extract takes` (transitively) |
diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.md
index a93532b1a7..525d72de83 100644
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@ -293,13 +293,13 @@ other config field):
```bash
gbrain reinit-pglite --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024
-gbrain reindex --code --yes
+gbrain reindex-code --yes
```
(`gbrain config set embedding_model` is refused because the schema column
has to resize alongside the config.)
-`gbrain reindex --code` prints a recommendation when the configured
+`gbrain reindex-code` prints a recommendation when the configured
embedding model isn't code-tuned. Suppress with
`GBRAIN_NO_CODE_MODEL_NUDGE=1` if you've intentionally chosen another
provider (single-vendor procurement, compliance, no Voyage key).
diff --git a/docs/architecture/type-taxonomy.md b/docs/architecture/type-taxonomy.md
index 625bdcc126..b092e3009d 100644
--- a/docs/architecture/type-taxonomy.md
+++ b/docs/architecture/type-taxonomy.md
@@ -73,8 +73,7 @@ gbrain onboard --check # surfaces pack_upgrade_available
↓
gbrain onboard --check --explain # per-cluster narrative dry-run
↓
-gbrain jobs submit unify-types \ # PROTECTED + manual_only
- --allow-protected \
+gbrain jobs submit unify-types \ # PROTECTED + manual_only (CLI submit trusts it)
--params '{"target_pack":"gbrain-base-v2","apply":true}'
# omit "apply":true → dry-run (default)
↓
@@ -126,7 +125,7 @@ For brains with substantial custom types that deserve their own canonical
1. Fork gbrain-base-v2: `gbrain schema fork gbrain-base-v2 my-pack`
2. Edit your fork to add page_types + mapping_rules covering your
custom domain.
-3. Target your fork: `gbrain jobs submit unify-types --allow-protected
+3. Target your fork: `gbrain jobs submit unify-types
--params '{"target_pack":"my-pack","apply":true}'` (omit `"apply":true`
for a dry-run preview — that is the default)
diff --git a/docs/eval-bench.md b/docs/eval-bench.md
index e3fa8f3fc1..8be463844a 100644
--- a/docs/eval-bench.md
+++ b/docs/eval-bench.md
@@ -464,7 +464,8 @@ What the arms say:
and autocut off, expansion costs thirteen questions against `balanced`
(+2 / −15: multi-session −7, temporal −5) plus the Haiku call per query.
`gbrain config set search.mode balanced` keeps the reranker and drops
- expansion; `gbrain config set search.expansion_variant_budget 0.25`
+ expansion (`gbrain query` still expands in every mode unless `--no-expand`);
+ `gbrain config set search.expansion_variant_budget 0.25`
recovers most of the loss if you keep it on.
- **Slot starvation is not the miss class** (from the 2026-09-02 sibling run;
no in-repo arm yet): session-diverse over-fetch fills every top-5 to 5.00
diff --git a/docs/guides/agent-to-gbrain.md b/docs/guides/agent-to-gbrain.md
index 84f7f33a0d..b487b89c7f 100644
--- a/docs/guides/agent-to-gbrain.md
+++ b/docs/guides/agent-to-gbrain.md
@@ -88,7 +88,7 @@ This is THE onboarding-paths table. Other docs link here; none copy it.
| Path | When to use | Credential kind | Print vs write | Serve location |
|---|---|---|---|---|
| `gbrain agent register <name> --harness <h>` | The packaged path: onboarding an agent harness (Claude Code, Codex, opencode, your OpenClaw) onto a shared brain. Presets (`daily-driver`, `coding-agent`), starter tool surface, 30-day token TTL, `--reissue` secret rotation. | Scoped OAuth client + a minted access token (source-scoped, expiring) | PRINTS the harness block (redacted unless `--show-token`); writes nothing to harness configs | Runs ON the brain host against a remote-reachable `gbrain serve --http`; `--url` or `--port` required (a live PGLite serve blocks it by design — stop the serve first; a serve too old to enforce scoped tokens is refused — upgrade it, or pass `--allow-old-serve` to accept the risk) |
-| `gbrain connect <mcp-url> --token <t>` | You already hold a bearer token and want ONE coding agent pointed at a running serve, from any machine. | Legacy bearer token (full-access unless minted with `--scopes`); `--oauth` variant for OAuth-capable connectors | Prints the add command by default; `--install` runs it | Any machine; targets a remote `gbrain serve --http` |
+| `gbrain connect <mcp-url> --token <t>` | You already hold a bearer token and want ONE coding agent pointed at a running serve, from any machine. | Legacy bearer token (full-access unless minted with `--scopes`); `--oauth` variant for OAuth-capable connectors. `/mcp` verifies both kinds; a client status flag of `needsAuth` from an unauthenticated probe is not a bearer failure — see [DEPLOY.md — Dual-mode auth](../mcp/DEPLOY.md#3-expose-the-server) | Prints the add command by default; `--install` runs it | Any machine; targets a remote `gbrain serve --http` |
| `gbrain bootstrap harness` | Framework-spawned harnesses (`claude -p` / `codex exec` / `opencode run`) on the SAME box that hosts the brain; wires MCP registration + lifecycle hooks with receipts and mint-first token rotation. | Legacy bearer token, minted per run and rotated by receipt | WRITES managed config blocks (Claude Code user scope, codex TOML, opencode JSONC) + hooks | Local loopback serve on the same box (non-loopback URL requires an explicit supplied token) |
| `gbrain auth register-client <name>` | The raw primitive: custom flows — PKCE/authorization-code clients, bound `submit_agent` clients, slug-prefix write fences, provisioning scripts that parse output. | Scoped OAuth client only (no token exchange, no TTL default beyond the server's) | Prints `client_id` + `client_secret` one time; you do all wiring | Credential is server-side state; run on the brain host |
diff --git a/docs/guides/ambient-recall.md b/docs/guides/ambient-recall.md
index aba6aa866f..8066278305 100644
--- a/docs/guides/ambient-recall.md
+++ b/docs/guides/ambient-recall.md
@@ -67,9 +67,12 @@ synopses.
## Budgets
Every pack/delta call takes `budget_tokens`. The server packs highest-priority
-arms first (cards → facts for packs; pages → facts for deltas) and reports
-`budget_used` + `dropped_count`; the injectable `text` field is rendered from
-the packed sets, so it honors the same budget the structured arrays report. It
+arms first (cards → facts for packs; pages → facts for deltas — a delta never
+drops threads, their lines are reserved ahead of pages and facts),
+costing each item as the line it renders to and reserving the envelope +
+section headers up front, and reports `budget_used` (the token estimate of
+`text`) + `dropped_count`; the injectable `text` field is rendered from the
+packed sets, so it never exceeds the budget the structured arrays report. It
never trims client-side — you always know what was left out (`dropped_count`,
and `has_more` on deltas). Pick a budget to fit the boundary: a session-start
pack can afford more than a heartbeat delta.
diff --git a/docs/guides/bootstrap.md b/docs/guides/bootstrap.md
index f5bf403ea3..115a67144e 100644
--- a/docs/guides/bootstrap.md
+++ b/docs/guides/bootstrap.md
@@ -23,8 +23,9 @@ follows is `BOOTSTRAP_FOR_AGENTS.md` at the repo root, fetched at the
| Hooks (Claude Code, ON by default) | local installs: `.claude/settings.local.json` (gitignored); cloud sandboxes: the COMMITTED `.claude/settings.json` (PATH-resolved, fail-open commands) | each prompt; fail-open; `--no-hooks` opts out at install, `GBRAIN_HOOKS=0` disables at runtime |
| Codex SessionEnd hook (session capture only) | user-global `hooks.json` + a config.toml trust entry under CODEX_HOME (both managed by bootstrap — codex hooks are silently inert without the trust entry) | at codex session end, machine-wide; `--no-hooks` opts out, `GBRAIN_HOOKS=0` disables |
| Memorable relay (OFF by default, disclosure-gated) | receipt + relay spawn from the session-end hooks / OpenClaw compaction; the third-party `memorable` CLI sends the redacted trace off-machine — see `docs/memorable-agents.md` | only after `gbrain config set integrations.memorable.enabled true` is accepted by a human; `GBRAIN_MEMORABLE=0` kills it |
-| Per-turn persistence | Stop hook → debounced, detached scan-gated push (per workspace; 5 min default, every turn in cloud sandboxes) | after each assistant turn; `GBRAIN_STOP_PUSH=0` disables; `GBRAIN_STOP_PUSH_DEBOUNCE_MIN` / config `hooks.stop_push_debounce_min` tune it |
-| Session persistence | SessionEnd hook → scan-gated commit+push | at session end (note: the harness never fires SessionEnd on `/exit` — the per-turn push is what covers that) |
+| Per-turn persistence | Stop hook → debounced, detached scan-gated push (per workspace; 5 min default, every turn in cloud sandboxes) | after each assistant turn; `GBRAIN_STOP_PUSH=0` disables; `GBRAIN_STOP_PUSH_DEBOUNCE_MIN` / config `hooks.stop_push_debounce_min` tune it (Stop path only — the two rows below have neither) |
+| Session persistence | SessionEnd hook → detached scan-gated commit+push; no per-path switch or debounce — spawns on every SessionEnd (the child commits only when the tree is dirty and otherwise just pushes); `GBRAIN_HOOKS=0` is the only off-switch | at session end (note: the harness never fires SessionEnd on `/exit` — the per-turn push is what covers that); heartbeat `session-end` entries carry `reason: push_spawned`, so an auto-commit can be attributed to this path |
+| Crash recovery | SessionStart hook → detached scan-gated push when the workspace has uncommitted changes or commits ahead of origin (bootstrap workspaces only, after the repo phase completes); no switch or debounce beyond `GBRAIN_HOOKS=0` | at session start; heartbeat `session-start` entries carry `reason: push_spawned` |
| Compaction checkpoints | PreCompact hook → secret-scanned boundary segment banked to the corpus dir; a live serve harvests it into facts + `brain://` links (see `docs/guides/checkpoint-compaction.md`) | at each Claude Code compaction; links render as `## Compaction checkpoints` on the post-compaction session start |
| Ambient-writeback instruction blocks (OFF by default — only when `memory.auto_writeback` is enabled, and installed by HARNESS mode, not the workspace install) | managed `<!-- gbrain:ambient-writeback -->` blocks in user-scope `CLAUDE.md` (Claude Code) + `$CODEX_HOME/AGENTS.md` (Codex); the Stop-hook backstop banks gated user turns for serve-side extraction (see `docs/guides/ambient-writeback.md`) | while enabled; re-run `bootstrap harness` after config changes; off-mode re-runs remove the blocks |
| Push-failure visibility | next turn's context + a user-visible notice; re-announces every 30 min while failing | whenever a background push fails |
diff --git a/docs/guides/compiled-truth.md b/docs/guides/compiled-truth.md
index 8c28aea482..4ec006c0e1 100644
--- a/docs/guides/compiled-truth.md
+++ b/docs/guides/compiled-truth.md
@@ -127,7 +127,20 @@ support that claim.
above); everything above it is compiled truth, everything below is
timeline.
-5. **Don't skip the Assessment section.** The assessment is the value. "Strong
+5. **The sentinel does not scope timeline extraction — dated citations above
+ it mint rows too.** Every trusted write (`put_page`/`capture`, `auto_timeline`
+ on by default) and `extract timeline` scan the WHOLE page for dated markers:
+ `- **YYYY-MM-DD** | ...` bullets and inline `[Source: ..., YYYY-MM-DD]`
+ citations. The citation shape the quality convention mandates on every fact
+ therefore files one permanent timeline row per citation when it sits in
+ compiled truth (dated by the citation, summary = the bullet/paragraph it sits
+ in, code spans stripped). The example page above keeps its citations below
+ the sentinel, so it does not show the hazard. The one placement that mints
+ nothing is a citation alone in its own paragraph — blank line above and
+ below. `gbrain config set auto_timeline off` disables the write-path
+ extraction; there is no timeline-remove command, only exact-duplicate dedup.
+
+6. **Don't skip the Assessment section.** The assessment is the value. "Strong
technical leader" is something no API can provide. It's YOUR read on this
person. That's what makes the brain page better than LinkedIn.
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index 9974d4a451..1d4e55ccd5 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -116,11 +116,17 @@ A dot-directory you deliberately keep content in (say `.decisions/`) can be
waived back in with `--include-hidden '<glob>'` on `gbrain sync` — the glob
names exactly which hidden paths to admit
(`gbrain sync --include-hidden '.decisions/**'`); everything else hidden
-stays pruned, and vendored/generated exclusions are never waived. Two
-bounds: the flag scopes a single sync invocation (it cannot combine with
-`--all` — register the subdirectory as the source's `local_path` instead),
-and it does not reach a non-git directory's filesystem-walk import fallback
-(every git-tracked source, the normal case, is covered).
+stays pruned, and vendored/generated exclusions are never waived. The flag
+scopes a single sync invocation and cannot combine with `--all`; to make the
+waiver hold on every path — `sync --all`, autopilot, the dream cycle — persist
+it as the `sync.include_hidden` config key (same dialect as `sync.exclude`; a
+trailing `/` means the whole subtree). Unset admits nothing, and a per-call
+flag unions with the persisted list rather than replacing it. One remaining
+bound: neither form reaches a non-git directory's filesystem-walk import
+fallback (every git-tracked source, the normal case, is covered).
+
+**Say to your agent:** *"index my repo's .github folder on every sync"* — your
+agent runs `gbrain config set sync.include_hidden '.github/'`.
Everything else is ordinary synced content — including `ops/` (the bundled
daily-task-manager skill files its canonical page under `ops/tasks`).
diff --git a/docs/guides/multi-language-fts.md b/docs/guides/multi-language-fts.md
index 10fb0ceca5..4b98440c01 100644
--- a/docs/guides/multi-language-fts.md
+++ b/docs/guides/multi-language-fts.md
@@ -106,6 +106,14 @@ command runs, or Postgres will reject the trigger recreation with
- Keep `GBRAIN_FTS_LANGUAGE` set consistently in every environment that
writes to the brain (CLI shells, MCP server, cron jobs) — a writer without
the env var tokenizes new rows in `english` until the next reindex.
+- **Interrupted reindex:** the trigger flip commits before the backfill, so a
+ `reindex-search-vector` run killed mid-way (crash, full disk, SIGKILL)
+ leaves new writes in the new language and un-backfilled rows in the old one
+ — keyword search then matches only part of the corpus. The command records
+ an in-progress marker plus a per-batch checkpoint, `gbrain doctor` fails
+ with `fts_reindex_incomplete` until the run completes, and re-running with
+ the same `GBRAIN_FTS_LANGUAGE` resumes from the checkpoint rather than
+ starting over. Budget minutes, not seconds, on brains with 100K+ chunks.
- **CJK (Chinese / Japanese / Korean):** none of the built-in snowball
configurations can tokenize CJK text, so the FTS arm would return nothing
for CJK queries. Both engines detect CJK queries and route them to a
diff --git a/docs/guides/search-modes.md b/docs/guides/search-modes.md
index 7d8ef73620..f08929c283 100644
--- a/docs/guides/search-modes.md
+++ b/docs/guides/search-modes.md
@@ -37,6 +37,14 @@ and maintenance commands remain available.
| `reranker` (cross-encoder) | off | `voyage:rerank-2.5` | `voyage:rerank-2.5` |
| `autocut` (rerank-cliff cut) | off | off | off |
+The `expansion` row is not decisive for any shipped verb today: `gbrain query`
+(the only verb that can expand) expands by default in every mode — pass
+`--no-expand` / `expand: false` to opt out — while `gbrain search`, the memory
+verbs and the eval harnesses pin expansion per call. The bundle value (and the
+`search.expansion` config key) only reaches a caller that leaves `expansion`
+unset AND wires an `expandFn`; none ship today. `gbrain search modes` reports
+the bundle value, not what `query` does.
+
- **`conservative`** — smallest payloads. Pairs naturally with a cheap
downstream model (Haiku-class) or a high query volume.
- **`balanced`** — the default and the fallback when no mode is set.
@@ -47,7 +55,8 @@ Seven of the knobs deserve a sentence:
- **`expansion`** rewrites your query into multiple variants via a cheap
LLM call per search (adds roughly $1.50 per 1K queries) — better recall,
- small extra cost.
+ small extra cost. `gbrain query` expands in every mode unless `--no-expand`;
+ this knob does not turn it off (see the caption under the table).
- **`expansion_variant_budget`** (config key
`search.expansion_variant_budget`) is the total RRF weight the expansion
variants share at fusion time (`weight_i = b / n_voting_arms`; the original
diff --git a/docs/guides/skillopt.md b/docs/guides/skillopt.md
index 63d79f6edd..e91e7bdc1e 100644
--- a/docs/guides/skillopt.md
+++ b/docs/guides/skillopt.md
@@ -198,10 +198,14 @@ runs, set:
`1`/`true` points the child's `CLAUDE_CONFIG_DIR` at an isolated empty
per-process directory; any other value is used verbatim as the config-dir
path (pre-seed one if you want a fixed minimal config). **Opt-in on
-purpose:** on non-macOS installs the config dir also holds the OAuth session
-credentials, so the empty-dir form logs the child out there (macOS keeps
-credentials in the keychain and survives). If rollouts start failing auth
-after flipping this on, that is why.
+purpose:** the config dir also holds the CLI's session credentials, so the
+empty-dir form logs the child out wherever the CLI reads its session from the
+config dir — macOS included (observed with Claude Code 2.1.x). If rollouts
+start failing auth (`Not logged in · Please run /login`) after flipping this
+on, that is why: the run now ends `errored` with that message as the failure
+detail instead of finishing as a `no_improvement` with a 0.000 score. For a
+hermetic run that stays authenticated, use the explicit-path form and
+pre-seed that directory with a logged-in config.
## When NOT to use SkillOpt
diff --git a/docs/integrations/README.md b/docs/integrations/README.md
index 32033f1dc5..9472b6ed66 100644
--- a/docs/integrations/README.md
+++ b/docs/integrations/README.md
@@ -46,6 +46,10 @@ These require manual setup (no self-installing recipe yet):
| [Meeting & Call Webhooks](meeting-webhooks.md) | Circleback meeting transcripts + Quo/OpenPhone SMS/calls |
| [qm Harness](qm-harness.md) | gbrain as the company brain for a qm (multi-user agent harness) deployment — central HTTP MCP, per-scope clients, roster provisioning, write fencing |
+Something came in wrong? [Reliability repair](reliability-repair.md) covers what
+`gbrain doctor` flags after import (double-encoded JSONB values, truncated
+markdown bodies) and the commands that fix each one.
+
## How to Read a Recipe
Integration recipes are markdown files with YAML frontmatter. Your agent reads
diff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.md
index b33cbfb9f3..74887c2143 100644
--- a/docs/integrations/embedding-providers.md
+++ b/docs/integrations/embedding-providers.md
@@ -110,7 +110,7 @@ gbrain init --pglite --embedding-model voyage:voyage-code-3 --embedding-dimensio
To switch an existing brain, run `gbrain migrate embeddings --to voyage:voyage-code-3 --dim 1024` (works on both engines; resumable, cost-previewed with `--dry-run` — see [`docs/guides/embedding-migration.md`](../guides/embedding-migration.md)). `gbrain config set embedding_model` is refused — the schema column has to resize, and the migration command is the path that does that safely.
-`gbrain reindex --code` will print a recommendation when run against a brain whose configured embedding model isn't code-tuned; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1` if you've intentionally chosen another model (single-vendor procurement, compliance, etc.).
+`gbrain reindex-code` will print a recommendation when run against a brain whose configured embedding model isn't code-tuned; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1` if you've intentionally chosen another model (single-vendor procurement, compliance, etc.).
### Google Gemini
diff --git a/docs/integrations/pre-commit.md b/docs/integrations/pre-commit.md
index b647132e48..86ecd257f1 100644
--- a/docs/integrations/pre-commit.md
+++ b/docs/integrations/pre-commit.md
@@ -23,7 +23,8 @@ The same eight validation classes the `frontmatter-guard` skill and
## Install
-For all registered sources that are git repos:
+For all registered sources inside a git repo (the source's own repo, or a
+subdirectory of a host repo — the same shapes `gbrain sync` accepts):
```bash
gbrain frontmatter install-hook
@@ -41,9 +42,36 @@ For force-overwrite of an existing pre-commit hook (writes a `.bak`):
gbrain frontmatter install-hook --force
```
-The hook lands at `<source>/.githooks/pre-commit`. If `core.hooksPath` is
-unset, the install also runs `git config core.hooksPath .githooks` so the
-hook is picked up without manual git config.
+The hook lands at `<git root>/.githooks/pre-commit` — the source's own repo,
+or the enclosing host repo when the source is registered as a subdirectory of
+one (see the topology cases below). If `core.hooksPath` is unset, the install
+also runs `git config core.hooksPath .githooks` so the hook is picked up
+without manual git config. Pointing `core.hooksPath` at `.githooks` makes git
+run every executable script in that directory and ignore `.git/hooks/*` for
+every hook type, so the installer writes the gbrain hook but leaves
+`core.hooksPath` unset (`hook written …; core.hooksPath left unset`) and
+prints the reason plus the manual wiring step when:
+
+- `core.hooksPath` is already set — in any scope, a global one from husky,
+ secret-scanner templates or dotfiles counts — to somewhere other than
+ `.githooks` (git reads hooks only from there, so the gbrain hook would be
+ inert) — copy `.githooks/pre-commit` into that directory, or point
+ `core.hooksPath` at `.githooks`; a value that already resolves to
+ `.githooks` is left alone and counts as wired;
+- `.githooks/` already holds other executable hook scripts (third-party
+ clones commit `post-commit`, `pre-push`, … there as a convention) — review
+ them, then `git -C <root> config core.hooksPath .githooks`;
+- `.git/hooks/` holds an active hook (executable, not `*.sample` — a host
+ repo's own pre-push, commit-msg, framework-installed hooks, …) — move them
+ into `.githooks/`, then run the same command.
+
+A source is skipped only when it sits outside any git repo (`skipped, Not
+inside a git repository: …`), its path contains a line terminator, which
+the generated shell script could not carry safely (`skipped, source path
+contains a line terminator; refusing to install hook`), or `.githooks/` /
+`.githooks/pre-commit` is a symlink (`Refusing to write through a symlink: …`
+— the installer never writes or removes through the link; the other sources
+still install).
## Bypass
@@ -82,6 +110,18 @@ that's not the brain repo itself, you may want a separate hook strategy:
- **Brain repo is a separate registered source** (e.g. `~/brain` registered
as a source, host repo is `~/agent-fork`): install in the brain repo only;
agent-fork code doesn't need this hook.
+- **Brain is a subdirectory of the host repo** (the `<workspace>/brain` layout
+ `gbrain bootstrap` creates and registers with
+ `gbrain sources add <id> --path <workspace>/brain`): the hook installs at the
+ host repo root, scoped to `brain/` — staged files elsewhere in the host repo
+ (README, AGENTS.md, code) are never validated. Several nested sources in one
+ host repo share a single hook (their scopes union; `--uninstall --source
+ <id>` drops only that source's scope); a source registered at the root
+ widens it to the whole repo. Known limitation: a nested page that declares
+ `slug:` explicitly can be reported as `SLUG_MISMATCH`, because
+ `frontmatter validate` derives the expected slug from the git root; pages
+ gbrain writes itself carry no `slug:`, so bootstrap-created brains are
+ unaffected.
- **Brain repo is auto-generated** (e.g. by a sync daemon writing to a
bucket): skip the hook entirely; gate at the writer instead via
`import { writeBrainPage } from 'gbrain/brain-writer'` (planned in a
diff --git a/docs/integrations/reliability-repair.md b/docs/integrations/reliability-repair.md
index b0f7ddc30e..5bed56f0d2 100644
--- a/docs/integrations/reliability-repair.md
+++ b/docs/integrations/reliability-repair.md
@@ -48,12 +48,16 @@ across every affected column. Idempotent. Second run reports 0 rows. Use
`--dry-run` to preview, `--json` for structured output. The `v0_12_2`
version migration runs this automatically on `gbrain upgrade`.
-For truncated markdown bodies (source-dependent):
+For truncated markdown bodies (source-dependent): the importer skips a file
+whose content hash has not changed, and trailing whitespace is trimmed before
+hashing, so a re-import needs a real edit to the page body. Make the edit, then
+re-import:
```
-gbrain sync --force
-# or per-page
-gbrain import <slug> --force
+gbrain sync # git-backed brain: commit the edit first
+gbrain sync --working-tree # or import the uncommitted working tree
+gbrain import <brain-root> --fresh # or re-import the root you originally imported;
+ # --fresh ignores a resume checkpoint that would skip the path
```
gbrain cannot recover content that is already lost if you no longer have
diff --git a/docs/mcp/ALTERNATIVES.md b/docs/mcp/ALTERNATIVES.md
index 2605c69436..0f57c1ff3f 100644
--- a/docs/mcp/ALTERNATIVES.md
+++ b/docs/mcp/ALTERNATIVES.md
@@ -26,21 +26,34 @@ ngrok http 8787 --url your-brain.ngrok.app
See the [ngrok-tunnel recipe](../../recipes/ngrok-tunnel.md) for full setup
including auth token configuration and fixed domain setup.
-## Tailscale Funnel
+## Tailscale Serve (tailnet-only) / Funnel (public)
-[Tailscale Funnel](https://tailscale.com/kb/1223/tailscale-funnel) gives you
-a permanent public HTTPS URL with automatic TLS. Free tier available. Best for
-private networks where you control both endpoints.
+[Tailscale](https://tailscale.com) gives you a permanent MagicDNS name with
+automatic TLS. Free tier available. Two modes, one command apart:
+
+| | `tailscale serve` | `tailscale funnel` |
+|--|---|---|
+| Reachable from | Your tailnet only | The public internet |
+| Best for | Your own devices; nothing exposed | Cloud connectors (ChatGPT, Claude.ai) that must reach you |
+| Docs | [Tailscale Serve](https://tailscale.com/kb/1312/serve) | [Tailscale Funnel](https://tailscale.com/kb/1223/tailscale-funnel) |
```bash
# 1. Install Tailscale
brew install tailscale
-# 2. Expose your MCP server
+# 2. Start gbrain with the HTTPS issuer Tailscale presents (default 127.0.0.1 bind is right)
+gbrain serve --http --port 8787 --public-url https://your-machine.your-tailnet.ts.net
+
+# 3a. Tailnet-only
+tailscale serve --bg 8787
+# 3b. Public
tailscale funnel 8787
-# Your brain is now at https://your-machine.ts.net
+# Your brain is now at https://your-machine.your-tailnet.ts.net/mcp
```
+For a plain-HTTP, bearer-only LAN endpoint with no TLS at all, see
+[DEPLOY.md — Tailnet / LAN-only](DEPLOY.md#tailnet--lan-only-no-public-tunnel).
+
## Fly.io / Railway (always-on)
For production deployments that need to run 24/7 without your machine:
diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.md
index 2e0add4784..e088131765 100644
--- a/docs/mcp/DEPLOY.md
+++ b/docs/mcp/DEPLOY.md
@@ -114,6 +114,45 @@ and per-client config export.
> stderr warning fires at startup). Multi-tenant deployments should leave it on
> the redacted default.
+### Owner login links for AI agents
+
+**Say to your agent:** *"Give me the GBrain admin login link"* — the agent
+uses the existing HTTP mint endpoint described below.
+
+When an authenticated owner asks **"Give me the GBrain admin login link"**,
+use the existing single-use login flow. A static `/admin/` URL opens the login
+page; it does not authenticate the owner.
+
+1. Confirm the requesting owner and a private destination for the login link.
+2. Obtain the running server's bootstrap credential through the host's existing
+ protected credential mechanism. `GBRAIN_ADMIN_BOOTSTRAP_TOKEN` is the supported
+ deployment setting. Never expose its value in chat, logs, shell arguments,
+ or a URL. If the credential is unavailable, report that specific setup blocker;
+ do not claim the login-link capability is missing.
+3. Send `POST /admin/api/issue-magic-link` to the running server, with the
+ bootstrap credential in the `Authorization: Bearer` header through that
+ protected mechanism. An MCP client bearer token or client secret is not the
+ server bootstrap credential.
+4. The response contains `url` and `expires_in` (300 seconds). The returned URL
+ uses the server's configured `--public-url`; without it, the fallback is
+ localhost. Ensure the deployment has an owner-reachable public URL rather
+ than substituting a remembered tunnel address.
+5. Deliver the returned short-lived login link only to the requesting owner in
+ private. In a shared channel, acknowledge private delivery without reproducing
+ the link. Never put it into a public issue or commit.
+
+**Do not GET or fetch the generated login URL to verify it.** That redeems the
+single-use nonce before the owner can use it. Check the base `/admin/` page and
+non-secret response metadata separately. The link expires after five minutes,
+cannot be replayed, and is invalidated by a server restart. Successful redemption
+establishes the admin browser session and redirects to `/admin/`.
+
+This logs the owner into the dashboard; it does not create, reveal, or rotate an
+MCP client credential. Register the intended OAuth client separately in the
+credential-reveal screen below. For unattended deployments, provision the
+bootstrap credential through the operator's protected configuration before
+starting the server; generated secrets are deliberately hidden in captured logs.
+
### 2. Register OAuth clients
Register clients from the **`/admin` dashboard**:
@@ -206,7 +245,14 @@ gbrain serve --http --port 3131 --bind 0.0.0.0 --public-url https://your-brain.n
When `--public-url` is set without `--bind`, a stderr WARN fires at
startup so the misconfiguration ("the tunnel is up but my agent gets
-ECONNREFUSED") is loud.
+ECONNREFUSED") is loud. Binding `0.0.0.0` without `GBRAIN_HTTP_CORS_ORIGIN`
+warns too: browser-based clients get no CORS header until you set the
+allowlist (see [SECURITY.md — CORS](../../SECURITY.md#cors)).
+
+`--source-guard` is a stdio-lane flag: with `--http` it prints a warning and
+is ignored. HTTP writes are fenced by each token's scopes instead, so
+operators migrating from stdio mint narrowed tokens
+(`gbrain auth create <name> --scopes read`) rather than relying on the guard.
```bash
brew install ngrok
@@ -225,6 +271,53 @@ resource_metadata="<that URL>"`, so an MCP client pointed at
`https://your-brain.ngrok.app/mcp` finds the token endpoint from a fresh
connection without any pasted URLs.
+**Dual-mode auth on `/mcp`.** The same route verifies OAuth 2.1 access
+tokens and `gbrain auth create` bearers (OAuth first, then the
+`access_tokens` fallback). The 401 + `resource_metadata` challenge is emitted
+by the MCP SDK middleware for ANY request lacking an `Authorization` header
+(RFC 9728 / MCP auth spec §5.1 discovery) and says nothing about whether a
+configured token works. A client status probe that omits the header will
+therefore report `needsAuth` / `authentication_required` even while the
+configured bearer succeeds. Judge auth from `whoami`
+(`transport: legacy|oauth`) or `gbrain auth test <url> --token <t>`; treat a
+client's needsAuth flag as advisory unless the authenticated call itself
+returns 401 / `invalid_token`.
+
+#### Tailnet / LAN-only (no public tunnel)
+
+Two shapes work without exposing anything to the internet. In both, clients
+authenticate with `gbrain auth create` bearer tokens.
+
+**Tailscale Serve (HTTPS, tailnet-only).** Keep the default `127.0.0.1`
+bind, let Tailscale terminate TLS on the tailnet, and point `--public-url` at
+your MagicDNS name:
+
+```bash
+gbrain serve --http --port 3131 --public-url https://your-machine.your-tailnet.ts.net
+tailscale serve --bg 3131
+```
+
+Clients on the tailnet use `https://your-machine.your-tailnet.ts.net/mcp`.
+The "--public-url is set but --bind is not" WARN is expected in this shape —
+Tailscale Serve forwards to loopback. `tailscale serve` stays inside your
+tailnet; `tailscale funnel` is public exposure (see
+[ALTERNATIVES.md](ALTERNATIVES.md)).
+
+**Plain HTTP, bearer-only.** Bind the tailnet/LAN interface and omit
+`--public-url` entirely:
+
+```bash
+gbrain serve --http --port 3131 --bind 100.x.y.z # or --bind 0.0.0.0
+```
+
+The OAuth issuer defaults to `http://localhost:3131`, which the MCP SDK
+accepts, and bearer-token verification never reads the issuer. Clients connect
+to `http://100.x.y.z:3131/mcp` with `Authorization: Bearer …`. OAuth discovery
+is the one thing this shape does not offer (the advertised issuer is
+loopback), so OAuth-only clients such as ChatGPT need the HTTPS shape above.
+Passing `--public-url http://100.x.y.z:3131` instead fails at startup — see
+[Troubleshooting](#troubleshooting).
+
### 4. Scopes and localOnly
Every operation is tagged `read | write | admin`. Operations flagged
@@ -398,9 +491,28 @@ Include the Authorization header: `Authorization: Bearer YOUR_TOKEN`
**"invalid_token" error**
Run `gbrain auth list` to see active tokens.
+**Client status shows needsAuth / authentication_required but tool calls succeed**
+The client probed `/mcp` without an `Authorization` header and read the
+spec-mandated discovery 401 as a failed login. Both OAuth tokens and legacy
+bearers are accepted on `/mcp`; confirm with `whoami` (`transport: legacy`)
+or `gbrain auth test <url> --token <t>` and only re-authenticate if THAT
+call returns 401. See
+[Dual-mode auth on /mcp](#3-expose-the-server).
+
**"service_unavailable" error**
Database connection failed. Check your Supabase dashboard for outages.
+**"Issuer URL must be HTTPS" at startup**
+The MCP SDK rejects a non-HTTPS OAuth issuer unless the host is `localhost`
+or `127.0.0.1`, so `--public-url http://<lan-or-tailnet-ip>:3131` exits
+before the server listens. Either terminate TLS in front (Tailscale Serve,
+ngrok, Cloudflare Tunnel) and pass the `https://` URL, or drop `--public-url`
+for a bearer-only LAN endpoint — both shapes are in
+[Tailnet / LAN-only](#tailnet--lan-only-no-public-tunnel). Last resort, for
+plain-HTTP OAuth discovery on a private network you fully control: the SDK's
+own `MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL=1` opt-in. Bearer auth works
+either way; OAuth clients may still refuse a non-HTTPS issuer.
+
**Claude Desktop doesn't connect**
Remote servers must be added via Settings > Integrations, NOT
`claude_desktop_config.json`. See [CLAUDE_DESKTOP.md](CLAUDE_DESKTOP.md).
diff --git a/docs/mcp/HERMES-CLI-PIN.md b/docs/mcp/HERMES-CLI-PIN.md
index 8d7a25f18c..07fe57b4e1 100644
--- a/docs/mcp/HERMES-CLI-PIN.md
+++ b/docs/mcp/HERMES-CLI-PIN.md
@@ -12,9 +12,9 @@ file, the workflow pins, and the affected assertions together.
version stamp; CI installs the RELEASE TAG `v2026.8.3` = commit `3c27eb62` — the two
differ by post-release main commits, same declared version. If a CI door run ever
diverges from these notes, re-observe against the tag checkout.)
-- Installer sha256: `2076946edc23b3aed4a82ccb2e6b38ab593575626206dbdd192384e375b6d57c`
- (observed 2026-08-31; the served `scripts/install.sh` matched byte-for-byte
- against the upstream repo at `a071fc80d`). Full-script review notes for
+- Installer sha256: `5854b15670b51a8daae8f59ddfa917062de9f74be261eb73b4b8d719710f8968`
+ (observed 2026-09-09; the served `scripts/install.sh` matched byte-for-byte
+ against the upstream repo at `95d426560`). Full-script review notes for
this pin: the door flags (`--skip-setup`/`--non-interactive`/`--skip-browser`/
`--skip-computer-use`/`--branch`/`--commit`/`--force-commit`) are intact
and unknown flags hard-fail (`exit 1`, so a dropped flag can never silently
@@ -23,7 +23,7 @@ file, the workflow pins, and the affected assertions together.
duckduckgo connectivity probe); no eval/base64 obfuscation; sudo limited to
distro package installs (the one setuid chrome-sandbox sudo is
desktop-build-only, never in the door path); the Node support gate is
- 24.11+; the `run_locked_uv_sync` helper runs the Tier-0 `uv sync --locked`
+ 22.22+/24.11+/26+; the `run_locked_uv_sync` helper runs the Tier-0 `uv sync --locked`
with PROJECT `[tool.uv]` config discovery enabled in a subshell while
user/system uv config is redirected to an empty XDG dir, so the sync is
hash-verified instead of falling through to the non-hash-verified PyPI
@@ -116,7 +116,7 @@ non-interactive. `hermes cron tick` = run due jobs once and exit. `hermes cron l
`git -C ~/.hermes/hermes-agent rev-parse HEAD` and loud-fails on any mismatch, so an
installer that silently ignores unknown flags (or a moved checkout layout) can never
run unpinned upstream code on a runner that later holds secrets.
-- `HERMES_INSTALL_SHA256: "2076946edc23b3aed4a82ccb2e6b38ab593575626206dbdd192384e375b6d57c"`
+- `HERMES_INSTALL_SHA256: "5854b15670b51a8daae8f59ddfa917062de9f74be261eb73b4b8d719710f8968"`
- Door test asserts `hermes --version` output contains `v$HERMES_VERSION` when the env var is set.
- `hermes --version` output shape: `Hermes Agent v0.20.0 (2026.8.3)` + install dir + python lines.
- Missing-secret posture is SPLIT by trigger: on `pull_request` the paid leg is
diff --git a/docs/mcp/OPENCLAW.md b/docs/mcp/OPENCLAW.md
index 025ce2d781..5d8dc1faf0 100644
--- a/docs/mcp/OPENCLAW.md
+++ b/docs/mcp/OPENCLAW.md
@@ -16,42 +16,47 @@ manifest carries an `mcpServers.gbrain` entry that runs the bundled
plugins use; it resolves your installed `gbrain` via `GBRAIN_BIN`, then
`~/.bun/bin/gbrain`, then `PATH`, so it works under launchd's bare PATH and
never needs a build step) plus the bundled skills — and declares the
-`gbrain-context` context engine. To route
-OpenClaw's context-engine slot through gbrain, set:
+`gbrain-context` context engine. To route OpenClaw's context-engine slot
+through gbrain, two steps, in this order:
-```
-plugins.slots.contextEngine = gbrain-context
-```
+1. Install and enable the plugin by its own id, `gbrain-context-engine`
+ (the `id` in `openclaw.plugin.json`).
+2. Set the slot to the engine id the plugin registers:
+
+ ```
+ plugins.slots.contextEngine = gbrain-context
+ ```
+
+The slot value is the engine id, not the plugin id, so setting the slot alone
+does not activate the plugin — and an unregistered engine falls back to
+OpenClaw's default silently. Do step 1 first.
-## Option 2: Direct `~/.openclaw/config.json`
-
-The same shape gbrain's own CI uses (see the "Configure OpenClaw MCP" step in
-`.github/workflows/e2e.yml`):
-
-```json
-{
- "mcpServers": {
- "gbrain": {
- "command": "gbrain",
- "args": ["serve"],
- "env": {
- "DATABASE_URL": "postgresql://...",
- "GBRAIN_HOME": "/home/alice-example"
- }
- }
- }
-}
+## Option 2: `openclaw mcp add`
+
+OpenClaw keeps MCP servers under `mcp.servers` in `~/.openclaw/openclaw.json`
+(`openclaw config schema` shows the key path). Register gbrain with the CLI:
+
+```bash
+openclaw mcp add gbrain --command "$(command -v gbrain)" --arg serve --env GBRAIN_HOME=$HOME
```
-The `env` block is optional: a PGLite brain needs no `DATABASE_URL`, and
-`GBRAIN_HOME` only matters when the brain home isn't `~/.gbrain`. Append
-`"--surface", "verbs"` to `args` for the seven-verb memory protocol
-([MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)) instead of the full
-operation catalog.
+Use an absolute `--command` path: the launchd-started gateway's `PATH` does
+not include `~/.bun/bin`, so a bare `gbrain` fails to spawn. `--env` is
+optional: a PGLite brain needs no `DATABASE_URL`
+(`--env DATABASE_URL=postgresql://...` for Postgres), and `GBRAIN_HOME` only
+matters when the brain home isn't `~/.gbrain`. For the seven-verb memory
+protocol ([MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)) instead of the
+full operation catalog, pass `--surface verbs` as additional `--arg` values
+(check `openclaw mcp add --help` for your version's spelling).
+
+Leave `GBRAIN_SOURCE` unset in the MCP env unless you deliberately want
+single-source retrieval: a pin scopes every tool (search, `get_brain_identity`
+counts, …) to that one source, and nothing warns on reads.
## Verify
-Start an agent turn and ask it to use the brain:
+`openclaw mcp list` should show `gbrain`. Then start an agent turn and ask it
+to use the brain:
```
Call get_brain_identity, then search my brain for [topic].
@@ -62,5 +67,6 @@ brain can do (gated by `mcp.publish_skills` on the host).
## Remove
-Delete the `mcpServers.gbrain` block from `~/.openclaw/config.json`, or
-uninstall the bundle plugin.
+Delete `mcp.servers.gbrain` from `~/.openclaw/openclaw.json` (or run
+`openclaw mcp remove gbrain` if your version has it), or uninstall the bundle
+plugin.
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 66f4ed8cf4..fe9eb07918 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -289,8 +289,10 @@ after compaction to rehydrate what the summary dropped. Composes existing arms
(`entity` card builder + the hot-facts arm); never calls an LLM.
`entities` is comma-separated, capped at 8 (the response echoes the capped list). `budget_tokens` packs
-server-side (cards first, then facts) and the response reports
-`budget_used` + `dropped_count` — it never trims client-side. `since` filters
+server-side (cards first, then facts; each item costs its rendered line and the
+envelope + section headers are reserved first, so `text` fits the budget) and the
+response reports `budget_used` (the token estimate of `text`) + `dropped_count`
+— it never trims client-side. `since` filters
open-thread events to those after the cursor. **Visibility is WORLD-ONLY by
default** on every arm (a pack is injected into an agent context window that may
be logged or synced to a cloud model). `include_private` widens ALL arms in
@@ -299,7 +301,8 @@ remote caller never widens (fail-closed).
Response: `{ protocol_version, entities, cards[], open_threads[], facts[], text,
degraded_reason?, budget_tokens?, budget_used?, dropped_count? }`. `text` is the
-pre-rendered, envelope-wrapped injectable block.
+pre-rendered, envelope-wrapped injectable block; with `budget_tokens` it is
+rendered from the packed sets and never exceeds the declared budget.
### delta(since?, entities?, budget_tokens?, session_id?, include_private?) — read, zero LLM
@@ -327,9 +330,17 @@ of livelocking. Stateless callers resume by passing the response's
Response: `{ protocol_version, since, pages[], facts[], threads[], text,
has_more, next_cursor: { since, slug }, degraded_reason?, budget_tokens?,
-budget_used?, dropped_count? }`. `text` is rendered from the budget-packed sets
-(it honors the declared budget) and `since` is always normalized ISO (never the
-raw input string).
+budget_used?, dropped_count? }`. `budget_tokens` applies to pages and facts
+(pages pack first, then facts) — each item costs its rendered line and the
+envelope + section headers are reserved first, so `text` (rendered from the
+packed sets) fits the declared budget. **Threads are never truncated**: every
+open-thread event after `since` is delivered and its line is reserved ahead of
+pages and facts, so `dropped_count` / `has_more` count only pages and facts.
+If the envelope + headers + threads alone exceed `budget_tokens`, all threads
+are still returned and `budget_used` (the token estimate of `text`) reports the
+real rendered size, which then exceeds the budget. Cursor semantics are the v1
+page keyset alone — facts and threads never move `next_cursor`. `since` is
+always normalized ISO (never the raw input string).
## Latency classes (per verb)
diff --git a/llms-full.txt b/llms-full.txt
index 0227acb265..912fa0ecf2 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1201,6 +1201,11 @@ project resolves through `src/core/search/mode.ts`.
| `autocut` (rerank-cliff cut) | off | off | off |
| `searchLimit` default | 10 | 25 | 50 |
+The `expansion` row governs no shipped verb today: `gbrain query` expands by
+default in every mode (`--no-expand` / `expand: false` opts out); `search`, the
+memory verbs and the eval harnesses pin it per call; only a caller that leaves
+`expansion` unset AND wires an `expandFn` would inherit the bundle value.
+
**Cost anchors (downstream agent input cost — gbrain itself is rounding error).**
The corner-to-corner spread is 25x once you pair mode with downstream model.
Chunks ~400 tokens avg. Per-query cost @ 10K queries/month (typical
@@ -1218,8 +1223,9 @@ Mismatches (tokenmax+Haiku, conservative+Opus) waste capacity differently
— too-big payload overwhelms a cheap model; too-small payload starves an
expensive one.
-tokenmax adds ~\$1.50 per 1K queries in Haiku expansion calls on top of
-the matrix (\$15/mo @ 10K). Semantic result caching is temporarily disabled; budget for fresh retrieval on every query. **The matrix
+`gbrain query` adds ~\$1.50 per 1K queries for the Haiku expansion call in
+EVERY mode (\$15/mo @ 10K; `--no-expand` skips it) — `gbrain search` and the
+memory verbs never expand, so no mode buys that line item back. Semantic result caching is temporarily disabled; budget for fresh retrieval on every query. **The matrix
has three verbatim homes: this section, the `gbrain init` picker copy
(`src/commands/init-mode-picker.ts`), and `INSTALL_FOR_AGENTS.md` Step
3.5** — update all three when refreshing.
@@ -2145,6 +2151,9 @@ Per-query cost @ 10K queries/mo (typical single-user volume):
> 3) tokenmax (recommended default — preserves v0.31.x retrieval shape) —
> no budget, LLM expansion ON, 50 chunks. Best for Opus/frontier models.
>
+> ("no expansion" governs `gbrain search` and callers that leave expansion
+> unset; `gbrain query` expands in every mode unless you pass `--no-expand`.)
+>
> Cost depends on BOTH the mode AND the downstream model you run. See the
> matrix above for the 9-cell breakdown.
@@ -2861,7 +2870,7 @@ commands, embedding costs, and the restrictions that remain after rebuilding.
- **[Muse personal agent](docs/guides/muse.md)** — first verify its durable user-files location, then install the local CLI. Native MCP configuration and skill activation are not assumed.
- **[Grok Build](docs/mcp/GROK.md)** — `grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- gbrain serve --surface verbs`. The add is lazy (exit 0 without connecting) — verify with `grok mcp doctor gbrain`, which spawns the server and reports `7 tools discovered`. Verified against Grok Build v1.0.4.
- **[opencode](docs/mcp/OPENCODE.md)** (opencode.ai / SST — not OpenClaw) — `opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- gbrain serve --surface verbs`, or let `gbrain bootstrap hooks --harness opencode` write the config for you (opencode is a bootstrap-supported harness — it reads AGENTS.md natively). The add is lazy — verify with `opencode mcp list`, which spawns the server (`✓ gbrain connected`). Remote: `gbrain connect https://your-host/mcp --token gbrain_xxx --agent opencode [--install]` — the config stores only the `{env:GBRAIN_REMOTE_TOKEN}` interpolation. Verified against opencode v1.18.18.
-- **[OpenClaw](docs/mcp/OPENCLAW.md)** — the ClawHub bundle plugin registers gbrain automatically (`openclaw.plugin.json` ships in this repo), or add `{"command": "gbrain", "args": ["serve"]}` to `~/.openclaw/config.json`'s `mcpServers`.
+- **[OpenClaw](docs/mcp/OPENCLAW.md)** — the ClawHub bundle plugin registers gbrain automatically (`openclaw.plugin.json` ships in this repo), or register the stdio server with `openclaw mcp add gbrain --command "$(command -v gbrain)" --arg serve --env GBRAIN_HOME=$HOME` (absolute path: the launchd gateway PATH lacks `~/.bun/bin`); verify with `openclaw mcp list`.
- **[Claude Desktop (Cowork)](docs/mcp/CLAUDE_DESKTOP.md)** — Settings → Integrations → add the URL of your HTTP server. Remote only; the local `claude_desktop_config.json` does not work for remote servers.
- **[Claude Cowork (team plan)](docs/mcp/CLAUDE_COWORK.md)** — org Owner adds the connector under Organization Settings → Connectors.
- **[Perplexity Computer](docs/mcp/PERPLEXITY.md)** — `gbrain connect https://your-host/mcp --agent perplexity --oauth --register` mints a least-privilege OAuth client and prints the Issuer/Client ID/Secret to paste into Settings → Connectors (OAuth is the right path for a cloud connector; a bearer token also works for local use). Pro subscription required.
@@ -3001,7 +3010,7 @@ Most personal-knowledge tools force one fixed layout: their idea of "notes" + "p
**gbrain doesn't have a fixed layout.** It ships with bundled schema packs and lets you author your own when none fit:
- **`gbrain-base-v2`** (default) — 15-type DRY/MECE canonical taxonomy (14 canonical + `note` catch-all): `person`, `company`, `media`, `tweet`, `social-digest`, `analysis`, `atom`, `concept`, `source`, `deal`, `email`, `slack`, `writing`, `project`, `note`. Subtypes/format/origin pushed to frontmatter.
-- **`gbrain-base`** (legacy) — the wider 24-type layout. Stays bundled for back-compat; brains on it can upgrade via `gbrain onboard --check --explain` → `gbrain jobs submit unify-types --allow-protected --params '{"target_pack":"gbrain-base-v2","apply":true}'` (omit `"apply":true` for a dry-run preview — that is the default).
+- **`gbrain-base`** (legacy) — the wider 24-type layout. Stays bundled for back-compat; brains on it can upgrade via `gbrain onboard --check --explain` → `gbrain jobs submit unify-types --params '{"target_pack":"gbrain-base-v2","apply":true}'` (omit `"apply":true` for a dry-run preview — that is the default).
- **`gbrain-recommended`** — extends `gbrain-base` with the 13 additional directories from `docs/GBRAIN_RECOMMENDED_SCHEMA.md` (source, place, trip, conversation, personal, civic, project, etc.). Activate with `gbrain schema use gbrain-recommended`.
- **Your own pack** — `gbrain schema detect` clusters your actual filesystem into proposed types, `gbrain schema suggest` runs an LLM pass over them, and `gbrain schema review-candidates --apply` promotes the ones you like. Three commands and the brain knows your shape. Authoring a successor pack (declares `migration_from:` so existing brains can opt in): see [`docs/architecture/pack-upgrade-mechanism.md`](docs/architecture/pack-upgrade-mechanism.md).
@@ -4394,11 +4403,17 @@ A dot-directory you deliberately keep content in (say `.decisions/`) can be
waived back in with `--include-hidden '<glob>'` on `gbrain sync` — the glob
names exactly which hidden paths to admit
(`gbrain sync --include-hidden '.decisions/**'`); everything else hidden
-stays pruned, and vendored/generated exclusions are never waived. Two
-bounds: the flag scopes a single sync invocation (it cannot combine with
-`--all` — register the subdirectory as the source's `local_path` instead),
-and it does not reach a non-git directory's filesystem-walk import fallback
-(every git-tracked source, the normal case, is covered).
+stays pruned, and vendored/generated exclusions are never waived. The flag
+scopes a single sync invocation and cannot combine with `--all`; to make the
+waiver hold on every path — `sync --all`, autopilot, the dream cycle — persist
+it as the `sync.include_hidden` config key (same dialect as `sync.exclude`; a
+trailing `/` means the whole subtree). Unset admits nothing, and a per-call
+flag unions with the persisted list rather than replacing it. One remaining
+bound: neither form reaches a non-git directory's filesystem-walk import
+fallback (every git-tracked source, the normal case, is covered).
+
+**Say to your agent:** *"index my repo's .github folder on every sync"* — your
+agent runs `gbrain config set sync.include_hidden '.github/'`.
Everything else is ordinary synced content — including `ops/` (the bundled
daily-task-manager skill files its canonical page under `ops/tasks`).
@@ -5858,6 +5873,45 @@ and per-client config export.
> stderr warning fires at startup). Multi-tenant deployments should leave it on
> the redacted default.
+### Owner login links for AI agents
+
+**Say to your agent:** *"Give me the GBrain admin login link"* — the agent
+uses the existing HTTP mint endpoint described below.
+
+When an authenticated owner asks **"Give me the GBrain admin login link"**,
+use the existing single-use login flow. A static `/admin/` URL opens the login
+page; it does not authenticate the owner.
+
+1. Confirm the requesting owner and a private destination for the login link.
+2. Obtain the running server's bootstrap credential through the host's existing
+ protected credential mechanism. `GBRAIN_ADMIN_BOOTSTRAP_TOKEN` is the supported
+ deployment setting. Never expose its value in chat, logs, shell arguments,
+ or a URL. If the credential is unavailable, report that specific setup blocker;
+ do not claim the login-link capability is missing.
+3. Send `POST /admin/api/issue-magic-link` to the running server, with the
+ bootstrap credential in the `Authorization: Bearer` header through that
+ protected mechanism. An MCP client bearer token or client secret is not the
+ server bootstrap credential.
+4. The response contains `url` and `expires_in` (300 seconds). The returned URL
+ uses the server's configured `--public-url`; without it, the fallback is
+ localhost. Ensure the deployment has an owner-reachable public URL rather
+ than substituting a remembered tunnel address.
+5. Deliver the returned short-lived login link only to the requesting owner in
+ private. In a shared channel, acknowledge private delivery without reproducing
+ the link. Never put it into a public issue or commit.
+
+**Do not GET or fetch the generated login URL to verify it.** That redeems the
+single-use nonce before the owner can use it. Check the base `/admin/` page and
+non-secret response metadata separately. The link expires after five minutes,
+cannot be replayed, and is invalidated by a server restart. Successful redemption
+establishes the admin browser session and redirects to `/admin/`.
+
+This logs the owner into the dashboard; it does not create, reveal, or rotate an
+MCP client credential. Register the intended OAuth client separately in the
+credential-reveal screen below. For unattended deployments, provision the
+bootstrap credential through the operator's protected configuration before
+starting the server; generated secrets are deliberately hidden in captured logs.
+
### 2. Register OAuth clients
Register clients from the **`/admin` dashboard**:
@@ -5950,7 +6004,14 @@ gbrain serve --http --port 3131 --bind 0.0.0.0 --public-url https://your-brain.n
When `--public-url` is set without `--bind`, a stderr WARN fires at
startup so the misconfiguration ("the tunnel is up but my agent gets
-ECONNREFUSED") is loud.
+ECONNREFUSED") is loud. Binding `0.0.0.0` without `GBRAIN_HTTP_CORS_ORIGIN`
+warns too: browser-based clients get no CORS header until you set the
+allowlist (see [SECURITY.md — CORS](../../SECURITY.md#cors)).
+
+`--source-guard` is a stdio-lane flag: with `--http` it prints a warning and
+is ignored. HTTP writes are fenced by each token's scopes instead, so
+operators migrating from stdio mint narrowed tokens
+(`gbrain auth create <name> --scopes read`) rather than relying on the guard.
```bash
brew install ngrok
@@ -5969,6 +6030,53 @@ resource_metadata="<that URL>"`, so an MCP client pointed at
`https://your-brain.ngrok.app/mcp` finds the token endpoint from a fresh
connection without any pasted URLs.
+**Dual-mode auth on `/mcp`.** The same route verifies OAuth 2.1 access
+tokens and `gbrain auth create` bearers (OAuth first, then the
+`access_tokens` fallback). The 401 + `resource_metadata` challenge is emitted
+by the MCP SDK middleware for ANY request lacking an `Authorization` header
+(RFC 9728 / MCP auth spec §5.1 discovery) and says nothing about whether a
+configured token works. A client status probe that omits the header will
+therefore report `needsAuth` / `authentication_required` even while the
+configured bearer succeeds. Judge auth from `whoami`
+(`transport: legacy|oauth`) or `gbrain auth test <url> --token <t>`; treat a
+client's needsAuth flag as advisory unless the authenticated call itself
+returns 401 / `invalid_token`.
+
+#### Tailnet / LAN-only (no public tunnel)
+
+Two shapes work without exposing anything to the internet. In both, clients
+authenticate with `gbrain auth create` bearer tokens.
+
+**Tailscale Serve (HTTPS, tailnet-only).** Keep the default `127.0.0.1`
+bind, let Tailscale terminate TLS on the tailnet, and point `--public-url` at
+your MagicDNS name:
+
+```bash
+gbrain serve --http --port 3131 --public-url https://your-machine.your-tailnet.ts.net
+tailscale serve --bg 3131
+```
+
+Clients on the tailnet use `https://your-machine.your-tailnet.ts.net/mcp`.
+The "--public-url is set but --bind is not" WARN is expected in this shape —
+Tailscale Serve forwards to loopback. `tailscale serve` stays inside your
+tailnet; `tailscale funnel` is public exposure (see
+[ALTERNATIVES.md](ALTERNATIVES.md)).
+
+**Plain HTTP, bearer-only.** Bind the tailnet/LAN interface and omit
+`--public-url` entirely:
+
+```bash
+gbrain serve --http --port 3131 --bind 100.x.y.z # or --bind 0.0.0.0
+```
+
+The OAuth issuer defaults to `http://localhost:3131`, which the MCP SDK
+accepts, and bearer-token verification never reads the issuer. Clients connect
+to `http://100.x.y.z:3131/mcp` with `Authorization: Bearer …`. OAuth discovery
+is the one thing this shape does not offer (the advertised issuer is
+loopback), so OAuth-only clients such as ChatGPT need the HTTPS shape above.
+Passing `--public-url http://100.x.y.z:3131` instead fails at startup — see
+[Troubleshooting](#troubleshooting).
+
### 4. Scopes and localOnly
Every operation is tagged `read | write | admin`. Operations flagged
@@ -6142,9 +6250,28 @@ Include the Authorization header: `Authorization: Bearer YOUR_TOKEN`
**"invalid_token" error**
Run `gbrain auth list` to see active tokens.
+**Client status shows needsAuth / authentication_required but tool calls succeed**
+The client probed `/mcp` without an `Authorization` header and read the
+spec-mandated discovery 401 as a failed login. Both OAuth tokens and legacy
+bearers are accepted on `/mcp`; confirm with `whoami` (`transport: legacy`)
+or `gbrain auth test <url> --token <t>` and only re-authenticate if THAT
+call returns 401. See
+[Dual-mode auth on /mcp](#3-expose-the-server).
+
**"service_unavailable" error**
Database connection failed. Check your Supabase dashboard for outages.
+**"Issuer URL must be HTTPS" at startup**
+The MCP SDK rejects a non-HTTPS OAuth issuer unless the host is `localhost`
+or `127.0.0.1`, so `--public-url http://<lan-or-tailnet-ip>:3131` exits
+before the server listens. Either terminate TLS in front (Tailscale Serve,
+ngrok, Cloudflare Tunnel) and pass the `https://` URL, or drop `--public-url`
+for a bearer-only LAN endpoint — both shapes are in
+[Tailnet / LAN-only](#tailnet--lan-only-no-public-tunnel). Last resort, for
+plain-HTTP OAuth discovery on a private network you fully control: the SDK's
+own `MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL=1` opt-in. Bearer auth works
+either way; OAuth clients may still refuse a non-HTTPS issuer.
+
**Claude Desktop doesn't connect**
Remote servers must be added via Settings > Integrations, NOT
`claude_desktop_config.json`. See [CLAUDE_DESKTOP.md](CLAUDE_DESKTOP.md).
@@ -6463,8 +6590,10 @@ after compaction to rehydrate what the summary dropped. Composes existing arms
(`entity` card builder + the hot-facts arm); never calls an LLM.
`entities` is comma-separated, capped at 8 (the response echoes the capped list). `budget_tokens` packs
-server-side (cards first, then facts) and the response reports
-`budget_used` + `dropped_count` — it never trims client-side. `since` filters
+server-side (cards first, then facts; each item costs its rendered line and the
+envelope + section headers are reserved first, so `text` fits the budget) and the
+response reports `budget_used` (the token estimate of `text`) + `dropped_count`
+— it never trims client-side. `since` filters
open-thread events to those after the cursor. **Visibility is WORLD-ONLY by
default** on every arm (a pack is injected into an agent context window that may
be logged or synced to a cloud model). `include_private` widens ALL arms in
@@ -6473,7 +6602,8 @@ remote caller never widens (fail-closed).
Response: `{ protocol_version, entities, cards[], open_threads[], facts[], text,
degraded_reason?, budget_tokens?, budget_used?, dropped_count? }`. `text` is the
-pre-rendered, envelope-wrapped injectable block.
+pre-rendered, envelope-wrapped injectable block; with `budget_tokens` it is
+rendered from the packed sets and never exceeds the declared budget.
### delta(since?, entities?, budget_tokens?, session_id?, include_private?) — read, zero LLM
@@ -6501,9 +6631,17 @@ of livelocking. Stateless callers resume by passing the response's
Response: `{ protocol_version, since, pages[], facts[], threads[], text,
has_more, next_cursor: { since, slug }, degraded_reason?, budget_tokens?,
-budget_used?, dropped_count? }`. `text` is rendered from the budget-packed sets
-(it honors the declared budget) and `since` is always normalized ISO (never the
-raw input string).
+budget_used?, dropped_count? }`. `budget_tokens` applies to pages and facts
+(pages pack first, then facts) — each item costs its rendered line and the
+envelope + section headers are reserved first, so `text` (rendered from the
+packed sets) fits the declared budget. **Threads are never truncated**: every
+open-thread event after `since` is delivered and its line is reserved ahead of
+pages and facts, so `dropped_count` / `has_more` count only pages and facts.
+If the envelope + headers + threads alone exceed `budget_tokens`, all threads
+are still returned and `budget_used` (the token estimate of `text`) reports the
+real rendered size, which then exceeds the budget. Cursor semantics are the v1
+page keyset alone — facts and threads never move `next_cursor`. `since` is
+always normalized ISO (never the raw input string).
## Latency classes (per verb)
@@ -7139,12 +7277,16 @@ across every affected column. Idempotent. Second run reports 0 rows. Use
`--dry-run` to preview, `--json` for structured output. The `v0_12_2`
version migration runs this automatically on `gbrain upgrade`.
-For truncated markdown bodies (source-dependent):
+For truncated markdown bodies (source-dependent): the importer skips a file
+whose content hash has not changed, and trailing whitespace is trimmed before
+hashing, so a re-import needs a real edit to the page body. Make the edit, then
+re-import:
```
-gbrain sync --force
-# or per-page
-gbrain import <slug> --force
+gbrain sync # git-backed brain: commit the edit first
+gbrain sync --working-tree # or import the uncommitted working tree
+gbrain import <brain-root> --fresh # or re-import the root you originally imported;
+ # --fresh ignores a resume checkpoint that would skip the path
```
gbrain cannot recover content that is already lost if you no longer have
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index e98ac19a21..ca10f5bf55 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.50.0.0",
+ "version": "0.50.1.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 75450e0ee5..9061677602 100644
--- a/package.json
+++ b/package.json
@@ -174,7 +174,7 @@
"bun": ">=1.3.11"
},
"license": "MIT",
- "version": "0.50.0.0",
+ "version": "0.50.1.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.33",
"@hono/node-server": "^2.0.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 1a3ccf9b01..433d6db3fb 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.50.0.0",
+ "version": "0.50.1.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index 9b9e43e9be..10282cfe0b 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.50.0.0",
+ "version": "0.50.1.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 77ba824bc6..505be6c2aa 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.50.0.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.50.1.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
index 24e34bec0a..76e64960e1 100644
--- a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
@@ -131,18 +131,27 @@ Attribute the user's direct statements with `[Source: User, YYYY-MM-DD]`.
Without capture authorization, use the information in the current conversation
without persisting it. Explicit remembering does not enable ongoing capture.
-### Phase 2.5: Structured Graph Updates (automatic)
-
-Every `put_page` call automatically extracts entity references and writes them
-to the graph (`links` table) with inferred relationship types. Stale links
-(refs no longer in the page text) are removed in the same call. This is
-"auto-link" reconciliation.
-
-- No manual `add_link` calls needed for ordinary page writes.
+### Phase 2.5: Structured Graph Updates (auto-link)
+
+"Auto-link" reconciliation extracts entity references from a page and writes
+them to the graph (`links` table) with inferred relationship types; stale
+links (refs no longer in the page text) are removed. WHO runs it depends on
+the write path:
+
+- **Trusted local writes** (`gbrain put`, `gbrain capture`,
+ `gbrain call put_page`) auto-link inline and return
+ `auto_links: { created, removed, errors }`.
+- **MCP callers (stdio AND HTTP)** return `auto_links: { skipped: "remote", hint }`
+ and `auto_timeline: { skipped: "remote" }`. Body wikilinks are saved as text.
+ A stdio `gbrain serve` reconciles the edges asynchronously with its
+ maintenance sweep (startup + 10-minute idle ticks).
+ `gbrain serve --http` does not self-sweep — reconcile on demand with
+ `gbrain sweep --once` (delegates to the live serve over IPC) or
+ `gbrain extract links --source db`.
+ Use `add_link` for relationships you need immediately. Untrusted body text can plant
+ ranking-boosting edges, which is why the inline path is local-only.
- Inferred link types: `attended` (meeting -> person), `works_at`, `invested_in`,
`founded`, `advises`, `source` (frontmatter), `mentions` (default).
-- The `put_page` MCP response includes `auto_links: { created, removed, errors }`
- so the agent can verify outcomes.
- To disable: `gbrain config set auto_link false`. Default is on.
- Timeline entries with specific dates still need explicit `gbrain timeline-add`
(or batch via `gbrain extract timeline --source db`).
diff --git a/plugin-variants/gbrain-coding/skills/context-audit/SKILL.md b/plugin-variants/gbrain-coding/skills/context-audit/SKILL.md
index 3e3d606f91..9890bfb1bd 100644
--- a/plugin-variants/gbrain-coding/skills/context-audit/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/context-audit/SKILL.md
@@ -81,8 +81,14 @@ This skill guarantees:
(`gbrain bootstrap interview --set KEY "..."` then
`gbrain bootstrap render --only <FILE> --force`), never as a direct edit.
See [skills/soul-audit/SKILL.md](../soul-audit/SKILL.md) for the mechanics.
-- **Measured, not guessed.** Token figures come from the deterministic
- pre-pass (`wc -c` / ~4 chars-per-token), never invented.
+- **Estimated with a stated basis, never invented.** Token figures come from
+ the deterministic pre-pass (`wc -c` bytes/2.8 — Claude-family tokenizers
+ run ~2.6-3.5 bytes/token on markdown dense with paths and code spans; 2.8 is
+ the calibrated midpoint of measured always-loaded markdown, see #4988). The
+ report prints the divisor so a reader can
+ re-derive every number. If the host client reports an exact per-category
+ context breakdown (e.g. Claude Code `/context`), that figure outranks the
+ estimate — quote it and use it for the stack total.
- **Native judging.** The draft report is quality-gated through
`gbrain eval cross-modal` — no raw model API calls, no hardcoded model IDs.
- **Cost line.** Default judging is ONE cheap model (the user's utility-tier
@@ -97,8 +103,9 @@ This skill guarantees:
List the always-loaded files for this harness and measure each:
```bash
+# bytes/2.8 (calibrated for Claude-family tokenizers on markdown, #4988); integer ceil: (n*10+27)/28
for f in CLAUDE.md AGENTS.md SOUL.md USER.md ACCESS_POLICY.md HEARTBEAT.md MEMORY.md; do
- [ -f "$f" ] && echo "$f: $(wc -c < "$f") chars (~$(( $(wc -c < "$f") / 4 )) tokens)"
+ [ -f "$f" ] && echo "$f: $(wc -c < "$f") bytes (~$(( ( $(wc -c < "$f") * 10 + 27 ) / 28 )) tokens)"
done
```
@@ -138,7 +145,7 @@ Write the draft report to a temp file, then gate it:
JUDGE=$(gbrain config get models.tier.utility)
gbrain eval cross-modal \
- --task "Context-stack token-hygiene audit: every finding cites file + quoted evidence; savings are measured (chars/4), not guessed; findings ranked by token savings; every rendered-file recommendation targets the interview answer bank or template, never a direct edit; risk class on every row" \
+ --task "Context-stack token-hygiene audit: every finding cites file + quoted evidence; savings are estimated (bytes/2.8, divisor stated in the report), never invented; findings ranked by token savings; every rendered-file recommendation targets the interview answer bank or template, never a direct edit; risk class on every row" \
--output /tmp/context-audit-draft.md \
--slug context-audit-report \
--cycles 1 \
@@ -170,6 +177,7 @@ harness-routing convention the user can set up (see the cron-scheduler skill)
# Context Audit — YYYY-MM-DD
Stack total: ~NN,NNN tokens across N files (drift since last audit: +/-N,NNN)
+Estimate basis: bytes/2.8 | host-reported exact total (e.g. `/context`): NN,NNN or n/a
Findings: N (~NN,NNN tokens recoverable) | Contradictions: N
Judge verdict: PASS (single-model, utility tier) | receipt: <path>
@@ -208,8 +216,8 @@ belongs: source file, answer bank/template, memory store, or a new skill.
the single-cheap-model pass is the default for cost reasons.
- **Auditing on-demand content as if always-loaded.** Skills and reference
docs don't pay the per-turn tax; flagging them inflates savings numbers.
-- **Inventing token counts.** Measure with the pre-pass; estimates are labeled
- as `~N` chars/4 approximations.
+- **Inventing token counts.** Run the pre-pass; estimates are labeled `~N`
+ with the divisor stated, and a host-reported exact figure always wins.
- **Rewriting identity content yourself.** If a finding is about WHAT an
identity file says (wrong persona, outdated profile), route to soul-audit —
the interview is the only author of that content.
diff --git a/plugin-variants/gbrain-coding/skills/conventions/schema-evolution.md b/plugin-variants/gbrain-coding/skills/conventions/schema-evolution.md
index 535096d2d8..8bd70c7f5a 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/schema-evolution.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/schema-evolution.md
@@ -124,7 +124,7 @@ pointing at the `unify-types` PROTECTED Minion handler.
v0.41.22 ships **gbrain-base-v2** as the declared successor to
[email protected] — collapses 94 noisy types to 15 canonical via
declarative mapping_rules. Run via `gbrain onboard --check --explain`
-(preview) → `gbrain jobs submit unify-types --allow-protected --params
+(preview) → `gbrain jobs submit unify-types --params
'{"target_pack":"gbrain-base-v2","apply":true}'` (apply — `apply`
defaults to false, so a bare submit is a dry run). See
`skills/schema-unify/SKILL.md` for the full playbook.
diff --git a/plugin-variants/gbrain-coding/skills/enrich/SKILL.md b/plugin-variants/gbrain-coding/skills/enrich/SKILL.md
index 5237f7f798..33ae1c0ae3 100644
--- a/plugin-variants/gbrain-coding/skills/enrich/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/enrich/SKILL.md
@@ -277,8 +277,11 @@ Active items, pending decisions, things to track.
**Note (v0.10.1):** Links between brain pages are auto-created on every
`put_page` call (auto-link post-hook). Step 7 focuses on content
cross-references (updating related pages' compiled truth with new signal
-from this enrichment), not on creating links. Verify via the `auto_links`
-field in the put_page response (`{ created, removed, errors }`).
+from this enrichment), not on creating links. On a trusted local write the
+put_page response carries `auto_links: { created, removed, errors }`; MCP
+writes (stdio and HTTP) return `auto_links: { skipped: "remote", hint }`
+instead — edges are reconciled by the serve maintenance sweep or
+`gbrain sweep --once`, and `add_link` covers an edge you need immediately.
Timeline entries still need explicit `gbrain timeline-add` calls.
## Bulk Enrichment Rules
diff --git a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md b/plugin-variants/gbrain-coding/skills/maintain/SKILL.md
index f08e4e81be..73f3f6d45e 100644
--- a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/maintain/SKILL.md
@@ -180,7 +180,11 @@ counted as warnings, not edits. Telemetry lands in
Reads recent reflections within `dream.patterns.lookback_days` (default 30),
runs a single Sonnet pass to surface recurring themes, and writes pattern
pages to `wiki/personal/patterns/<theme>` when ≥`dream.patterns.min_evidence`
-(default 3) reflections support a pattern.
+(default 3) reflections support a pattern. A completed run records the newest
+reflection it consumed (`dream.patterns.last_evidence_ts`); until a reflection
+in the window is newer than that, re-runs skip with `no_new_evidence` instead
+of paying for another model pass — `gbrain dream --phase patterns --once`
+forces one.
**Quality bar (Iron Law for synthesis):**
1. Quote the user verbatim. Quotation marks are ONLY for spans reproducible
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index fbf6db251a..e4cf5439c6 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.50.0.0",
+ "version": "0.50.1.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 74f4c99931..94fe2c7ac1 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.50.0.0",
+ "version": "0.50.1.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index 39fc2a0c21..cbab857c08 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.50.0.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.50.1.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin-variants/gbrain-daily/skills/conventions/schema-evolution.md b/plugin-variants/gbrain-daily/skills/conventions/schema-evolution.md
index 535096d2d8..8bd70c7f5a 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/schema-evolution.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/schema-evolution.md
@@ -124,7 +124,7 @@ pointing at the `unify-types` PROTECTED Minion handler.
v0.41.22 ships **gbrain-base-v2** as the declared successor to
[email protected] — collapses 94 noisy types to 15 canonical via
declarative mapping_rules. Run via `gbrain onboard --check --explain`
-(preview) → `gbrain jobs submit unify-types --allow-protected --params
+(preview) → `gbrain jobs submit unify-types --params
'{"target_pack":"gbrain-base-v2","apply":true}'` (apply — `apply`
defaults to false, so a bare submit is a dry run). See
`skills/schema-unify/SKILL.md` for the full playbook.
diff --git a/plugin/README.md b/plugin/README.md
index 88b82391fd..3cedcc2e59 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.50.0.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.50.1.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/plugin/skills/brain-ops/SKILL.md b/plugin/skills/brain-ops/SKILL.md
index 24e34bec0a..76e64960e1 100644
--- a/plugin/skills/brain-ops/SKILL.md
+++ b/plugin/skills/brain-ops/SKILL.md
@@ -131,18 +131,27 @@ Attribute the user's direct statements with `[Source: User, YYYY-MM-DD]`.
Without capture authorization, use the information in the current conversation
without persisting it. Explicit remembering does not enable ongoing capture.
-### Phase 2.5: Structured Graph Updates (automatic)
-
-Every `put_page` call automatically extracts entity references and writes them
-to the graph (`links` table) with inferred relationship types. Stale links
-(refs no longer in the page text) are removed in the same call. This is
-"auto-link" reconciliation.
-
-- No manual `add_link` calls needed for ordinary page writes.
+### Phase 2.5: Structured Graph Updates (auto-link)
+
+"Auto-link" reconciliation extracts entity references from a page and writes
+them to the graph (`links` table) with inferred relationship types; stale
+links (refs no longer in the page text) are removed. WHO runs it depends on
+the write path:
+
+- **Trusted local writes** (`gbrain put`, `gbrain capture`,
+ `gbrain call put_page`) auto-link inline and return
+ `auto_links: { created, removed, errors }`.
+- **MCP callers (stdio AND HTTP)** return `auto_links: { skipped: "remote", hint }`
+ and `auto_timeline: { skipped: "remote" }`. Body wikilinks are saved as text.
+ A stdio `gbrain serve` reconciles the edges asynchronously with its
+ maintenance sweep (startup + 10-minute idle ticks).
+ `gbrain serve --http` does not self-sweep — reconcile on demand with
+ `gbrain sweep --once` (delegates to the live serve over IPC) or
+ `gbrain extract links --source db`.
+ Use `add_link` for relationships you need immediately. Untrusted body text can plant
+ ranking-boosting edges, which is why the inline path is local-only.
- Inferred link types: `attended` (meeting -> person), `works_at`, `invested_in`,
`founded`, `advises`, `source` (frontmatter), `mentions` (default).
-- The `put_page` MCP response includes `auto_links: { created, removed, errors }`
- so the agent can verify outcomes.
- To disable: `gbrain config set auto_link false`. Default is on.
- Timeline entries with specific dates still need explicit `gbrain timeline-add`
(or batch via `gbrain extract timeline --source db`).
diff --git a/plugin/skills/context-audit/SKILL.md b/plugin/skills/context-audit/SKILL.md
index 3e3d606f91..9890bfb1bd 100644
--- a/plugin/skills/context-audit/SKILL.md
+++ b/plugin/skills/context-audit/SKILL.md
@@ -81,8 +81,14 @@ This skill guarantees:
(`gbrain bootstrap interview --set KEY "..."` then
`gbrain bootstrap render --only <FILE> --force`), never as a direct edit.
See [skills/soul-audit/SKILL.md](../soul-audit/SKILL.md) for the mechanics.
-- **Measured, not guessed.** Token figures come from the deterministic
- pre-pass (`wc -c` / ~4 chars-per-token), never invented.
+- **Estimated with a stated basis, never invented.** Token figures come from
+ the deterministic pre-pass (`wc -c` bytes/2.8 — Claude-family tokenizers
+ run ~2.6-3.5 bytes/token on markdown dense with paths and code spans; 2.8 is
+ the calibrated midpoint of measured always-loaded markdown, see #4988). The
+ report prints the divisor so a reader can
+ re-derive every number. If the host client reports an exact per-category
+ context breakdown (e.g. Claude Code `/context`), that figure outranks the
+ estimate — quote it and use it for the stack total.
- **Native judging.** The draft report is quality-gated through
`gbrain eval cross-modal` — no raw model API calls, no hardcoded model IDs.
- **Cost line.** Default judging is ONE cheap model (the user's utility-tier
@@ -97,8 +103,9 @@ This skill guarantees:
List the always-loaded files for this harness and measure each:
```bash
+# bytes/2.8 (calibrated for Claude-family tokenizers on markdown, #4988); integer ceil: (n*10+27)/28
for f in CLAUDE.md AGENTS.md SOUL.md USER.md ACCESS_POLICY.md HEARTBEAT.md MEMORY.md; do
- [ -f "$f" ] && echo "$f: $(wc -c < "$f") chars (~$(( $(wc -c < "$f") / 4 )) tokens)"
+ [ -f "$f" ] && echo "$f: $(wc -c < "$f") bytes (~$(( ( $(wc -c < "$f") * 10 + 27 ) / 28 )) tokens)"
done
```
@@ -138,7 +145,7 @@ Write the draft report to a temp file, then gate it:
JUDGE=$(gbrain config get models.tier.utility)
gbrain eval cross-modal \
- --task "Context-stack token-hygiene audit: every finding cites file + quoted evidence; savings are measured (chars/4), not guessed; findings ranked by token savings; every rendered-file recommendation targets the interview answer bank or template, never a direct edit; risk class on every row" \
+ --task "Context-stack token-hygiene audit: every finding cites file + quoted evidence; savings are estimated (bytes/2.8, divisor stated in the report), never invented; findings ranked by token savings; every rendered-file recommendation targets the interview answer bank or template, never a direct edit; risk class on every row" \
--output /tmp/context-audit-draft.md \
--slug context-audit-report \
--cycles 1 \
@@ -170,6 +177,7 @@ harness-routing convention the user can set up (see the cron-scheduler skill)
# Context Audit — YYYY-MM-DD
Stack total: ~NN,NNN tokens across N files (drift since last audit: +/-N,NNN)
+Estimate basis: bytes/2.8 | host-reported exact total (e.g. `/context`): NN,NNN or n/a
Findings: N (~NN,NNN tokens recoverable) | Contradictions: N
Judge verdict: PASS (single-model, utility tier) | receipt: <path>
@@ -208,8 +216,8 @@ belongs: source file, answer bank/template, memory store, or a new skill.
the single-cheap-model pass is the default for cost reasons.
- **Auditing on-demand content as if always-loaded.** Skills and reference
docs don't pay the per-turn tax; flagging them inflates savings numbers.
-- **Inventing token counts.** Measure with the pre-pass; estimates are labeled
- as `~N` chars/4 approximations.
+- **Inventing token counts.** Run the pre-pass; estimates are labeled `~N`
+ with the divisor stated, and a host-reported exact figure always wins.
- **Rewriting identity content yourself.** If a finding is about WHAT an
identity file says (wrong persona, outdated profile), route to soul-audit —
the interview is the only author of that content.
diff --git a/plugin/skills/conventions/schema-evolution.md b/plugin/skills/conventions/schema-evolution.md
index 535096d2d8..8bd70c7f5a 100644
--- a/plugin/skills/conventions/schema-evolution.md
+++ b/plugin/skills/conventions/schema-evolution.md
@@ -124,7 +124,7 @@ pointing at the `unify-types` PROTECTED Minion handler.
v0.41.22 ships **gbrain-base-v2** as the declared successor to
[email protected] — collapses 94 noisy types to 15 canonical via
declarative mapping_rules. Run via `gbrain onboard --check --explain`
-(preview) → `gbrain jobs submit unify-types --allow-protected --params
+(preview) → `gbrain jobs submit unify-types --params
'{"target_pack":"gbrain-base-v2","apply":true}'` (apply — `apply`
defaults to false, so a bare submit is a dry run). See
`skills/schema-unify/SKILL.md` for the full playbook.
diff --git a/plugin/skills/enrich/SKILL.md b/plugin/skills/enrich/SKILL.md
index 5237f7f798..33ae1c0ae3 100644
--- a/plugin/skills/enrich/SKILL.md
+++ b/plugin/skills/enrich/SKILL.md
@@ -277,8 +277,11 @@ Active items, pending decisions, things to track.
**Note (v0.10.1):** Links between brain pages are auto-created on every
`put_page` call (auto-link post-hook). Step 7 focuses on content
cross-references (updating related pages' compiled truth with new signal
-from this enrichment), not on creating links. Verify via the `auto_links`
-field in the put_page response (`{ created, removed, errors }`).
+from this enrichment), not on creating links. On a trusted local write the
+put_page response carries `auto_links: { created, removed, errors }`; MCP
+writes (stdio and HTTP) return `auto_links: { skipped: "remote", hint }`
+instead — edges are reconciled by the serve maintenance sweep or
+`gbrain sweep --once`, and `add_link` covers an edge you need immediately.
Timeline entries still need explicit `gbrain timeline-add` calls.
## Bulk Enrichment Rules
diff --git a/plugin/skills/frontmatter-guard/SKILL.md b/plugin/skills/frontmatter-guard/SKILL.md
index 77919debb8..654f8cc1ca 100644
--- a/plugin/skills/frontmatter-guard/SKILL.md
+++ b/plugin/skills/frontmatter-guard/SKILL.md
@@ -229,4 +229,4 @@ title: "My "Quoted" Title"
**Don't run `audit` on a brain where sources aren't registered.** The CLI returns "no registered sources to audit" gracefully, but the migration emits a `skipped: no_sources` phase result. Don't paper over this with a manual path-walk; the right fix is to register the source via `gbrain sources add`.
-**Don't install the pre-commit hook on non-git brain dirs.** The install-hook command skips them automatically with a one-line note. If you see "skipped — not a git repo" and want validation at write time anyway, use the `audit` command on a cron schedule.
+**Don't install the pre-commit hook on brain dirs outside any git repo.** The install-hook command skips them automatically with a one-line note (a brain that is a subdirectory of a host repo is fine — the hook installs at the host root, scoped to that subdirectory). If you see "skipped, not a git repo" and want validation at write time anyway, use the `audit` command on a cron schedule.
diff --git a/plugin/skills/maintain/SKILL.md b/plugin/skills/maintain/SKILL.md
index f08e4e81be..73f3f6d45e 100644
--- a/plugin/skills/maintain/SKILL.md
+++ b/plugin/skills/maintain/SKILL.md
@@ -180,7 +180,11 @@ counted as warnings, not edits. Telemetry lands in
Reads recent reflections within `dream.patterns.lookback_days` (default 30),
runs a single Sonnet pass to surface recurring themes, and writes pattern
pages to `wiki/personal/patterns/<theme>` when ≥`dream.patterns.min_evidence`
-(default 3) reflections support a pattern.
+(default 3) reflections support a pattern. A completed run records the newest
+reflection it consumed (`dream.patterns.last_evidence_ts`); until a reflection
+in the window is newer than that, re-runs skip with `no_new_evidence` instead
+of paying for another model pass — `gbrain dream --phase patterns --once`
+forces one.
**Quality bar (Iron Law for synthesis):**
1. Quote the user verbatim. Quotation marks are ONLY for spans reproducible
diff --git a/plugin/skills/schema-unify/SKILL.md b/plugin/skills/schema-unify/SKILL.md
index f16841f630..9e2dd9927f 100644
--- a/plugin/skills/schema-unify/SKILL.md
+++ b/plugin/skills/schema-unify/SKILL.md
@@ -89,7 +89,6 @@ The handler is PROTECTED (manual_only) — autopilot will never auto-fire it. Su
```bash
gbrain jobs submit unify-types \
- --allow-protected \
--params '{"target_pack":"gbrain-base-v2","apply":true}'
```
@@ -97,7 +96,7 @@ On PGLite (the install default), or on any setup without a running `gbrain jobs
```bash
gbrain jobs submit unify-types \
- --allow-protected --follow \
+ --follow \
--params '{"target_pack":"gbrain-base-v2","apply":true}'
```
@@ -208,7 +207,7 @@ Worried about a specific cluster's mapping?
Inputs:
- A brain on `gbrain-base` (or any pack with `migration_from: gbrain-base-v2`).
-- Write access to submit a PROTECTED Minion handler (`--allow-protected`).
+- Trusted local CLI access on the brain host: `gbrain jobs submit` grants the PROTECTED-handler opt-in itself for protected names; the remote MCP `submit_job` op cannot.
- ~10 min wallclock on a 186K-page brain.
Outputs:
@@ -230,7 +229,7 @@ Failure modes:
## Anti-Patterns
DON'T:
-- Submit `unify-types` directly via the MCP `submit_job` op without `--allow-protected`. PROTECTED handlers require trusted local callers; remote MCP rejection is the intentional trust boundary.
+- Submit `unify-types` via the remote MCP `submit_job` op. PROTECTED handlers require trusted local callers (`gbrain jobs submit` on the brain host); remote MCP rejection is the intentional trust boundary.
- Edit `mapping_rules` in `gbrain-base-v2.yaml` to skip clusters you don't trust. Fork the pack instead (`gbrain schema fork`) so the source-of-truth migration stays consistent across brains.
- Run `unify-types` from inside an autopilot tick. The check is `manual_only` — autopilot deliberately never auto-fires it because pack upgrades are one-time consenting taxonomy decisions.
- Hard-delete soft-deleted source pages before the 72h restore window. Use `gbrain restore <slug>` first if rollback is needed.
diff --git a/scripts/check-key-files-current-state.sh b/scripts/check-key-files-current-state.sh
index b2e855514e..e1086e926f 100755
--- a/scripts/check-key-files-current-state.sh
+++ b/scripts/check-key-files-current-state.sh
@@ -6,7 +6,7 @@
# per file. This guard makes that recurrence structurally impossible. A written
# rule caused the disease; a CI guard cures it.
#
-# TWO HARD GATES (fail the build):
+# THREE HARD GATES (fail the build):
# 1. Bolded-release-clause ban — the reference docs (docs/architecture/KEY_FILES.md,
# docs/architecture/thin-client.md, docs/TESTING.md) describe CURRENT behavior
# only. Release history lives in CHANGELOG.md + git. The bolded `**v0.<digit>`
@@ -15,6 +15,9 @@
# marker is banned, so this never false-fires on legitimate version mentions.
# 2. CLAUDE.md size cap — the structural backstop. Even if someone ignores the
# prose rule and pads CLAUDE.md, the size gate catches it.
+# 3. One KEY_FILES.md bullet per src file — a cherry-pick that keeps both sides
+# of a hunk leaves two "- `src/x.ts`" bullets describing two different
+# "current states" for one file. Merge into the survivor, never append a twin.
#
# SOFT WARNS (stderr, non-fatal): prose history markers that suggest narration
# creeping back ("pre-fix", ", then v0.", "superseded by") in the reference docs.
@@ -73,6 +76,21 @@ if [ -f "$claude" ]; then
fi
fi
+# ── Gate 3: one KEY_FILES.md bullet per src file ───────────────────────────
+# ponytail: KNOWN_DUP_PATHS seeds the pairs that pre-date the gate so it lands
+# green; merge a pair and delete its entry here — never add to this list.
+KNOWN_DUP_PATHS='src/cli.ts|src/commands/dream.ts|src/core/context/resolve-ipc.ts|src/core/context/turn-context.ts|src/core/cycle/transcript-discovery.ts'
+key_files="$ROOT/docs/architecture/KEY_FILES.md"
+if [ -f "$key_files" ]; then
+ dups=$(grep -oE '^- `src/[^`]+`' "$key_files" | sort | uniq -d | grep -vE "^- \`($KNOWN_DUP_PATHS)\`$" || true)
+ if [ -n "$dups" ]; then
+ fail=1
+ echo "FAIL: docs/architecture/KEY_FILES.md has more than one bullet for the same src file (two 'current states' for one file):" >&2
+ printf '%s\n' "$dups" | sed 's/^/ /' >&2
+ echo " Fold the newer sentences into the existing bullet and delete the twin." >&2
+ fi
+fi
+
# ── Soft warns: prose history markers creeping into reference docs ──────────
for rel in "${REFERENCE_DOCS[@]}"; do
doc="$ROOT/$rel"
diff --git a/scripts/check-privacy.sh b/scripts/check-privacy.sh
index ca2e947afc..4adcd5d55f 100755
--- a/scripts/check-privacy.sh
+++ b/scripts/check-privacy.sh
@@ -117,10 +117,10 @@ ALLOW_LIST=(
'skills/migrations/v0.9.0.md'
'skills/migrations/v0.14.0.md'
'test/storage-status.test.ts'
- # CHANGELOG.md documents the rule (the v0.25.1 entry references the
- # banned literals in describing what's banned). Same exception status
- # as CLAUDE.md and this script itself: meta-documentation needs to
- # name the patterns it forbids.
+ # CHANGELOG.md: the v0.25.1 entry documents the BANNED_PATHS literals in
+ # describing what the guard forbids, so it is exempt from the PATH check
+ # only. The fork-name check still runs on it (see the loop below): the
+ # notes are the most-read public artifact and the name has leaked there.
'CHANGELOG.md'
# skills/migrations/v0.25.1.md is the agent-readable upgrade
# walkthrough; it explains the privacy-guard extension to the
@@ -185,11 +185,18 @@ while IFS= read -r file; do
[ -z "$file" ] && continue
[ ! -f "$file" ] && continue
if is_allowed "$file"; then
+ # CHANGELOG.md is allow-listed for the BANNED_PATHS literals only; the
+ # fork-name check applies to it like any other public artifact.
+ if [ "$file" = "CHANGELOG.md" ] && grep -in "$BANNED_NAME" "$file" >/dev/null 2>&1; then
+ echo "[check-privacy] BANNED NAME in $file:" >&2
+ grep -in "$BANNED_NAME" "$file" | sed 's|^| |' >&2
+ FOUND=1
+ fi
continue
fi
# Case-insensitive grep; only specific extensions + known docs.
case "$file" in
- *.md|*.ts|*.mjs|*.js|*.py|*.sh|*.json|*.yaml|*.yml|*.txt|README*|CHANGELOG*|CLAUDE*|AGENTS*)
+ *.md|*.ts|*.tsx|*.mjs|*.js|*.jsx|*.py|*.sh|*.json|*.yaml|*.yml|*.txt|README*|CHANGELOG*|CLAUDE*|AGENTS*)
if grep -in "$BANNED_NAME" "$file" >/dev/null 2>&1; then
echo "[check-privacy] BANNED NAME in $file:" >&2
grep -in "$BANNED_NAME" "$file" | sed 's|^| |' >&2
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 4add9996df..e986907d3f 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -225,7 +225,16 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
// Schema source of truth: any change must pass the cross-engine drift gate.
"src/schema.sql": ["test/e2e/schema-drift.test.ts"],
"src/core/pglite-schema.ts": ["test/e2e/schema-drift.test.ts"],
- "src/core/migrate.ts": ["test/e2e/schema-drift.test.ts", "test/e2e/migrate-chain.test.ts"],
+ "src/core/migrate.ts": [
+ "test/e2e/schema-drift.test.ts",
+ "test/e2e/migrate-chain.test.ts",
+ "test/e2e/link-source-check-repair-postgres.test.ts",
+ ],
+ // #4613: the links_link_source_check self-heal must use migration v114's
+ // two-phase DDL (DROP + ADD NOT VALID, then VALIDATE outside the txn) on real
+ // Postgres — lock semantics PGLite can't observe. Keyed on the repair module
+ // and on migrate.ts (the definition it reproduces).
+ "src/core/link-source-check-repair.ts": ["test/e2e/link-source-check-repair-postgres.test.ts"],
// MCP stdio + HTTP transports share dispatch.
"src/mcp/**": ["test/e2e/mcp.test.ts", "test/e2e/http-transport.test.ts"],
// G6: the --surface verbs CEILING journey over a real `serve --http` boot
diff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.ts
index ac385fecde..1f3494e66d 100644
--- a/scripts/generate-flag-registry.ts
+++ b/scripts/generate-flag-registry.ts
@@ -11,11 +11,12 @@
* dispatch markers — `case 'X':` labels AND every `if (command === 'X' …)`
* head, plain or compound (see segmentDispatchBlocks) — collect every
* `import('./commands/Y.ts')` inside each block, then scan the
- * case-block text (with `//` and `/* *\/` comments stripped — prose next to a
- * marker is not consumption; see stripComments) plus each imported module
- * (plus one level of that module's ./relative same-directory imports) for
- * `--flag` string literals — including
- * help text, which deliberately over-includes: accepting a flag the handler
+ * case-block text plus each imported module (plus one level of that module's
+ * ./relative same-directory imports) for `--flag` string literals. `//` and
+ * `/* *\/` comments are stripped at EVERY depth before the scan (prose is not
+ * consumption; see stripComments) — a helper's doc comment must not legalise a
+ * flag for a command that merely imports one function from it. String
+ * literals include help text, which deliberately over-includes: accepting a flag the handler
* ignores is the pre-#2185 status quo for that flag, while missing a real
* flag would break working invocations on upgrade.
*
@@ -335,10 +336,17 @@ export function buildFlagRegistry(): Record<string, string[]> {
const surface = [modPath, ...facadeExpansion(modPath)];
for (const sfPath of surface) {
const sfSrc = readSrc(sfPath);
- depthZeroText += sfSrc;
- for (const f of flagsInText(sfSrc)) { flags.add(f); depthZero.add(f); }
+ // Comments are prose at every depth, not just in the dispatch block:
+ // a helper's doc comment ("Used by --fresh + after manual reset" in
+ // backfill-base.ts) handed reindex-search-vector a --fresh it never
+ // parses the moment the command imported one function from it.
+ // Consumed flags are always string literals, so stripping can only
+ // remove phantoms.
+ const sfCode = stripComments(sfSrc);
+ depthZeroText += sfCode;
+ for (const f of flagsInText(sfCode)) { flags.add(f); depthZero.add(f); }
for (const dep of relativeImports(sfSrc, dirname(sfPath))) {
- for (const f of flagsInText(readSrc(dep))) flags.add(f);
+ for (const f of flagsInText(stripComments(readSrc(dep)))) flags.add(f);
}
}
}
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 2041ac1457..052fc48299 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -4,40 +4,40 @@
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
src/cli.ts 4087 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review
-src/commands/autopilot.ts 2668 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint)
+src/commands/autopilot.ts 2671 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint); +5 #4952 (refs #4399): syncEnabled=false skip in the freshness dispatch loop
src/commands/doctor.ts 4641 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-up
src/commands/embed.ts 2147 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment)
src/commands/extract-conversation-facts.ts 2105 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed
-src/commands/extract.ts 2536 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode)
-src/commands/jobs.ts 3174 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled)
-src/commands/serve-http.ts 3313 ratchet +20 #4866: RFC 9728 PRM resource=/mcp + root-path alias rewrite; grown v0.46.25.0 D2: /mcp per-request teardown (#2844); grown wave-g (#4474): resolve-IPC socket under --http via shared helper; +15: metrics wiring — tracker mount + admin-gated /metrics route, helpers live in serve-http-metrics.ts (#3893); +7 test-gap wave C6: adminAuthRateLimiter on admin login + magic-link issuance, 429 JSON envelope; +29 ambient-writeback: per-request buildMcpInstructions (writeback bundle + write-scope gate + allowed-ops extract_facts probe); +6 adversarial fix wave: remember-op bound-client fence probe gates the ambient section; +2 #4748: startup resolveMcpInstructions (deployment identity) threaded into the per-request MCP server | merged v0.48.1.0: master #4788 writeback resolve + wave #4748 identity; master: | merged v0.48.1.0 true-up; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; +12: reject snapshot-bound webhook ingestion outside the shared MCP grant contract; merged v0.49: one owner-consent route with shared grant editing
-src/core/ai/gateway.ts 4846 ratchet +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards
-src/commands/sync.ts 5929 ratchet +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed
+src/commands/extract.ts 2643 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges
+src/commands/jobs.ts 3177 ratchet +3 #4786 x #2139 pre-landing: sync handler gates embed-backfill on syncProducedEmbeddableContent (no_new_content skip reason); grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled)
+src/commands/serve-http.ts 3382 ratchet lowered to the merged line count after master v0.50.0.0 shrank the file; +20 #4866: RFC 9728 PRM resource=/mcp + root-path alias rewrite; grown v0.46.25.0 D2: /mcp per-request teardown (#2844); grown wave-g (#4474): resolve-IPC socket under --http via shared helper; +15: metrics wiring — tracker mount + admin-gated /metrics route, helpers live in serve-http-metrics.ts (#3893); +7 test-gap wave C6: adminAuthRateLimiter on admin login + magic-link issuance, 429 JSON envelope; +29 ambient-writeback: per-request buildMcpInstructions (writeback bundle + write-scope gate + allowed-ops extract_facts probe); +6 adversarial fix wave: remember-op bound-client fence probe gates the ambient section; +2 #4748: startup resolveMcpInstructions (deployment identity) threaded into the per-request MCP server | merged v0.48.1.0: master #4788 writeback resolve + wave #4748 identity; master: | merged v0.48.1.0 true-up; +40 #4955: trackServerSockets() holds accepted sockets via WeakRef — Bun never emits socket close on server-side sockets, so the strong Set retained one socket per connection forever; +19 pre-landing review: bounded close() backstop in waitForHttpServerLifecycle (WeakRef-collected keep-alive wrappers leave native handles close() waits on); +10 pre-landing review r2: a close() error landing after the deadline is logged, not dropped
+src/core/ai/gateway.ts 4914 ratchet +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback)
+src/commands/sync.ts 5967 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed
src/core/cycle.ts 3207 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false
src/core/cycle/synthesize.ts 3216 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance)
src/core/cycle/extract-atoms.ts 1742 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once
src/core/engine.ts 2645 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc
-src/core/import-file.ts 2251 ratchet grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing
-src/core/migrate.ts 690 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards
+src/core/import-file.ts 2278 ratchet +3 pre-landing review: refreshSourcePath short-circuits on the getPage-projected source_path (no per-unchanged-file UPDATE); re-summed to the merged line count after merging master v0.50.0.0 with the wave; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); +24 #4588: refreshSourcePath heals a drifted source_path on the import skip path
+src/core/migrate.ts 712 region-exempt runner-region count re-summed after merging master v0.50.0.0 with the wave; append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); +19 (#4613: links_link_source_check every-pass self-heal wiring, logic lives in link-source-check-repair.ts); +3 (#4613 pre-landing review: ledger gate >= v114 around the self-heal)
src/core/operations.ts 321 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS
-src/core/pglite-engine.ts 6118 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity
-src/core/postgres-engine.ts 5577 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin)
-src/core/search/hybrid.ts 3295 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31)
-src/core/types.ts 2118 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs
+src/core/pglite-engine.ts 6126 ratchet re-summed to the merged line count after merging master v0.50.0.0 with the wave; +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity
+src/core/postgres-engine.ts 5590 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); +13: #4558 migrateFactsToCanonical row_num offset past canonical MAX
+src/core/search/hybrid.ts 3306 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call
+src/core/types.ts 2126 ratchet +2 pre-landing review: Page.source_path (getPage projection feeds the import skip-path short-circuit); +6 #5004: safe_index_pending degraded stage + doc; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs
src/core/minions/queue.ts 2484 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced
src/commands/init.ts 2050 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 normalized ZE provider check; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init
-src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900); bounded recipe diagnostics; master integration: grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
+src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1905 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards
src/commands/bootstrap.ts 2115 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics
src/core/minions/worker.ts 1546 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch
src/commands/sources.ts 1963 ratchet grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services
-src/core/link-extraction.ts 1785 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class)
+src/core/link-extraction.ts 1860 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments
src/core/embedding-migration.ts 1545 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers)
src/core/github-source.ts 1560 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment)
src/commands/hook.ts 1881 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
src/core/chunkers/code.ts 1582 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
-src/core/config.ts 1777 ratchet 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
-src/core/bootstrap/harness.ts 2420 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
+src/core/config.ts 1842 ratchet 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)
+src/core/bootstrap/harness.ts 2443 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)
src/core/oauth-provider.ts 1235 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
src/core/ops/pages.ts 1484 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
-src/core/search/mode.ts 1752 ratchet +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6)
+src/core/search/mode.ts 1756 ratchet +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 62770982c8..128e7fc0a2 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -15,7 +15,7 @@ test/auto-link-targeted-probe-2544.test.ts #2544 — auto-link behavior through
test/autopilot-auto-drain-wiring.test.ts autopilot auto-drain wiring 8 readFileSync
test/autopilot-cycle-failure-classification.test.ts autopilot cycle-failure classification — only 'failed' trips the circuit breaker 2 readFileSync
test/autopilot-cycle-failure-classification.test.ts runPhaseOrphans ratio threshold — no more absolute count > 20 3 readFileSync
-test/autopilot-fanout-wiring.test.ts autopilot.ts ↔ dispatchPerSource wiring 15 readFileSync
+test/autopilot-fanout-wiring.test.ts autopilot.ts ↔ dispatchPerSource wiring 16 readFileSync
test/autopilot-install.test.ts autopilot install — reload-safety (#2608) 1 readFileSync
test/autopilot-install.test.ts autopilot showStatus — wrapper-path detection 1 readFileSync
test/autopilot-install.test.ts autopilot wiring: chat-unavailable boot warning (#2608) 1 readFileSync
@@ -73,6 +73,7 @@ test/compile-view.test.ts compileView — determinism 3 readFileSync
test/compile-view.test.ts compileView — source isolation + read errors 3 readFileSync
test/config.test.ts config source correctness 1 readFileSync
test/connection-resilience.test.ts Eng-review D3 — executeRaw has no per-call retry wrapper 3 readFileSync
+test/context-audit-skill.test.ts #4988 context-audit skill states its token-estimate basis 3 readFileSync
test/contextual-retrieval-service-pure.test.ts inline import contextual synopsis containment 1 readFileSync
test/conversation-facts-type-allowlist-drift.test.ts (file-level) 18 readFileSync
test/cycle-abort.test.ts #1972 — complete cooperative-abort coverage 3 readFileSync
@@ -96,6 +97,11 @@ test/destructive-guard.test.ts assessDestructiveImpact 5 readFileSync
test/destructive-guard.test.ts formatters (display helpers) 4 readFileSync
test/destructive-guard.test.ts purgeExpiredSources — clone cleanup containment 1 readFileSync
test/detached-stderr.test.ts jobs.ts detach branch (source pin, #4418) 2 readFileSync
+test/docs-bootstrap-persistence-table.test.ts #4986 bootstrap.md scopes the Stop-push knobs and lists every push path 2 readFileSync
+test/docs-mcp-deploy.test.ts DEPLOY.md documents dual-mode /mcp auth (#4893) 1 readFileSync
+test/docs-mcp-deploy.test.ts DEPLOY.md documents the owner magic-link flow (#5007) 5 readFileSync
+test/docs-mcp-deploy.test.ts DEPLOY.md documents the tailnet/LAN-only serve --http shape (#4500) 3 readFileSync
+test/docs-timeline-extraction-guide.test.ts #4987 timeline extraction docs describe the real trigger 2 readFileSync
test/doctor-atom-provenance-drift.test.ts computeAtomProvenanceDriftCheck 18 doctor-source-helper
test/doctor-embedding-env-override.test.ts cross-surface parity (source-grep regression guard) 1 doctor-source-helper
test/doctor-fix.test.ts gbrain doctor --fix CLI integration 3 readFileSync
@@ -144,13 +150,15 @@ test/eval-takes-bootstrap.test.ts corpus integrity 4 readFileSync
test/exit-classification.test.ts consumer wire-up — helper used by all 3 sites (no inline filters left) 5 doctor-source-helper,readFileSync
test/extract-atoms-drain-errors.test.ts runExtractAtomsDrainForSource forwards typed per-item failures (#4730) 1 readFileSync
test/extract-atoms-drain.test.ts extract-atoms-drain Minion handler retries on provider_failure (issue #3218) 2 readFileSync
+test/extract-atoms-drain.test.ts protected-names register comment names the real trust mechanism 1 readFileSync
test/extract-atoms-drain.test.ts shared wiring helper holds the cycle lock (5A) 2 readFileSync
+test/extract-include-frontmatter-config.serial.test.ts no extraction path hardcodes includeFrontmatter 1 readFileSync
test/extract-workers.test.ts extract.ts → workers wiring (T7) 10 readFileSync
test/facts-backstop-remedy-verb.test.ts facts backstop thin-client-fallback remedy verb (#4489) 3 readFileSync
test/features.test.ts CLI routing 2 bun-file
test/fence-extraction.test.ts Layer 8 D2 — markdown fence extraction 18 readFileSync
test/files.test.ts collectFiles (production import) 9 readFileSync
-test/files.test.ts files upload-raw git-storage branch (#2297) 5 readFileSync
+test/files.test.ts files upload-raw git-storage branch (#2297) 6 readFileSync
test/files.test.ts files verify git lane (per-source root resolution) 1 readFileSync
test/files.test.ts storage precondition — the silent-no-op class (#4022) 3 readFileSync
test/filing-rules-resolution.serial.test.ts per-source filing-rules resolution 3 readFileSync
@@ -166,6 +174,7 @@ test/fix-wave-structural.test.ts v0.41.8.0 #1340 — PGLite WASM init classifier
test/fix-wave-structural.test.ts v0.42.20.0 — background-work registry drains every sink before disconnect 9 readFileSync
test/fix-wave-structural.test.ts v0.42.20.0 — search-cache drained via the background-work registry 1 readFileSync
test/fix-wave-structural.test.ts v0.42.43.0 #2095 — volunteer-events sink + cycle purge wiring (structural pins) 2 readFileSync
+test/frontmatter-install-hook.test.ts frontmatter install-hook (B13) 22 readFileSync
test/harness-onboarding.test.ts harness identity and private handoff 5 readFileSync
test/hook-command.serial.test.ts user-prompt 14 readFileSync
test/integrations-install.test.ts installRecipeIntoHostRepo — happy path 6 readFileSync
@@ -175,9 +184,11 @@ test/jobs-gateway-refresh-set.test.ts #3387 — GATEWAY_REFRESH_JOB_NAMES ⇔ re
test/jobs-list-get-json.serial.test.ts help advertises --json on list/get/stats (#3685) 2 readFileSync
test/jobs-thin-client-date-rehydration.test.ts thin-client unpack sites route through rehydrateJobDates (source audit) 2 readFileSync
test/jobs-worker-startup-recovery.test.ts work-handler recovery placement (structural) 1 readFileSync
+test/link-source-check-repair.test.ts regex literal drift guard (#4613) 1 readFileSync
test/longmemeval-embed-cache.test.ts EmbeddingCache — canonical hash 4 readFileSync
test/loops-extract-wiring.test.ts jobs.ts wiring 2 readFileSync
test/loops-extract-wiring.test.ts relational edge vocabulary 2 readFileSync
+test/mcp-registration-blocks.test.ts OpenClaw stdio registration docs (#4842) 2 readFileSync
test/migrate-stdout-clean.test.ts migration output stays off stdout 2 readFileSync
test/migrate.test.ts PR #356 + #363 — session timeouts applied via startup parameters 1 readFileSync
test/migrate.test.ts PR #356 — LATEST_VERSION is max(versions), not array[-1] 2 readFileSync
@@ -257,6 +268,7 @@ test/serve-stdin-eof-drain.test.ts serve-sync-runner stays off the boot path (#4
test/skillify-scaffold.test.ts 11-item scaffold contract (T9 + Phase 3 cross-modal eval) 1 readFileSync
test/skillify-scaffold.test.ts applyScaffold 3 readFileSync
test/skillify-scaffold.test.ts planScaffold 13 readFileSync
+test/skillopt/deadline-and-hermetic.test.ts #4741 — hermetic-config docs make no platform-survives-logout claim 2 readFileSync
test/skillpack-harness-bridge.test.ts review-driven hardening (ship pre-landing findings) 5 readFileSync
test/skillpack-harvest.test.ts addToBundleManifest 1 readFileSync
test/skillpack-harvest.test.ts runHarvest — happy path 2 readFileSync
diff --git a/skills/brain-ops/SKILL.md b/skills/brain-ops/SKILL.md
index 24e34bec0a..76e64960e1 100644
--- a/skills/brain-ops/SKILL.md
+++ b/skills/brain-ops/SKILL.md
@@ -131,18 +131,27 @@ Attribute the user's direct statements with `[Source: User, YYYY-MM-DD]`.
Without capture authorization, use the information in the current conversation
without persisting it. Explicit remembering does not enable ongoing capture.
-### Phase 2.5: Structured Graph Updates (automatic)
-
-Every `put_page` call automatically extracts entity references and writes them
-to the graph (`links` table) with inferred relationship types. Stale links
-(refs no longer in the page text) are removed in the same call. This is
-"auto-link" reconciliation.
-
-- No manual `add_link` calls needed for ordinary page writes.
+### Phase 2.5: Structured Graph Updates (auto-link)
+
+"Auto-link" reconciliation extracts entity references from a page and writes
+them to the graph (`links` table) with inferred relationship types; stale
+links (refs no longer in the page text) are removed. WHO runs it depends on
+the write path:
+
+- **Trusted local writes** (`gbrain put`, `gbrain capture`,
+ `gbrain call put_page`) auto-link inline and return
+ `auto_links: { created, removed, errors }`.
+- **MCP callers (stdio AND HTTP)** return `auto_links: { skipped: "remote", hint }`
+ and `auto_timeline: { skipped: "remote" }`. Body wikilinks are saved as text.
+ A stdio `gbrain serve` reconciles the edges asynchronously with its
+ maintenance sweep (startup + 10-minute idle ticks).
+ `gbrain serve --http` does not self-sweep — reconcile on demand with
+ `gbrain sweep --once` (delegates to the live serve over IPC) or
+ `gbrain extract links --source db`.
+ Use `add_link` for relationships you need immediately. Untrusted body text can plant
+ ranking-boosting edges, which is why the inline path is local-only.
- Inferred link types: `attended` (meeting -> person), `works_at`, `invested_in`,
`founded`, `advises`, `source` (frontmatter), `mentions` (default).
-- The `put_page` MCP response includes `auto_links: { created, removed, errors }`
- so the agent can verify outcomes.
- To disable: `gbrain config set auto_link false`. Default is on.
- Timeline entries with specific dates still need explicit `gbrain timeline-add`
(or batch via `gbrain extract timeline --source db`).
diff --git a/skills/context-audit/SKILL.md b/skills/context-audit/SKILL.md
index 3e3d606f91..9890bfb1bd 100644
--- a/skills/context-audit/SKILL.md
+++ b/skills/context-audit/SKILL.md
@@ -81,8 +81,14 @@ This skill guarantees:
(`gbrain bootstrap interview --set KEY "..."` then
`gbrain bootstrap render --only <FILE> --force`), never as a direct edit.
See [skills/soul-audit/SKILL.md](../soul-audit/SKILL.md) for the mechanics.
-- **Measured, not guessed.** Token figures come from the deterministic
- pre-pass (`wc -c` / ~4 chars-per-token), never invented.
+- **Estimated with a stated basis, never invented.** Token figures come from
+ the deterministic pre-pass (`wc -c` bytes/2.8 — Claude-family tokenizers
+ run ~2.6-3.5 bytes/token on markdown dense with paths and code spans; 2.8 is
+ the calibrated midpoint of measured always-loaded markdown, see #4988). The
+ report prints the divisor so a reader can
+ re-derive every number. If the host client reports an exact per-category
+ context breakdown (e.g. Claude Code `/context`), that figure outranks the
+ estimate — quote it and use it for the stack total.
- **Native judging.** The draft report is quality-gated through
`gbrain eval cross-modal` — no raw model API calls, no hardcoded model IDs.
- **Cost line.** Default judging is ONE cheap model (the user's utility-tier
@@ -97,8 +103,9 @@ This skill guarantees:
List the always-loaded files for this harness and measure each:
```bash
+# bytes/2.8 (calibrated for Claude-family tokenizers on markdown, #4988); integer ceil: (n*10+27)/28
for f in CLAUDE.md AGENTS.md SOUL.md USER.md ACCESS_POLICY.md HEARTBEAT.md MEMORY.md; do
- [ -f "$f" ] && echo "$f: $(wc -c < "$f") chars (~$(( $(wc -c < "$f") / 4 )) tokens)"
+ [ -f "$f" ] && echo "$f: $(wc -c < "$f") bytes (~$(( ( $(wc -c < "$f") * 10 + 27 ) / 28 )) tokens)"
done
```
@@ -138,7 +145,7 @@ Write the draft report to a temp file, then gate it:
JUDGE=$(gbrain config get models.tier.utility)
gbrain eval cross-modal \
- --task "Context-stack token-hygiene audit: every finding cites file + quoted evidence; savings are measured (chars/4), not guessed; findings ranked by token savings; every rendered-file recommendation targets the interview answer bank or template, never a direct edit; risk class on every row" \
+ --task "Context-stack token-hygiene audit: every finding cites file + quoted evidence; savings are estimated (bytes/2.8, divisor stated in the report), never invented; findings ranked by token savings; every rendered-file recommendation targets the interview answer bank or template, never a direct edit; risk class on every row" \
--output /tmp/context-audit-draft.md \
--slug context-audit-report \
--cycles 1 \
@@ -170,6 +177,7 @@ harness-routing convention the user can set up (see the cron-scheduler skill)
# Context Audit — YYYY-MM-DD
Stack total: ~NN,NNN tokens across N files (drift since last audit: +/-N,NNN)
+Estimate basis: bytes/2.8 | host-reported exact total (e.g. `/context`): NN,NNN or n/a
Findings: N (~NN,NNN tokens recoverable) | Contradictions: N
Judge verdict: PASS (single-model, utility tier) | receipt: <path>
@@ -208,8 +216,8 @@ belongs: source file, answer bank/template, memory store, or a new skill.
the single-cheap-model pass is the default for cost reasons.
- **Auditing on-demand content as if always-loaded.** Skills and reference
docs don't pay the per-turn tax; flagging them inflates savings numbers.
-- **Inventing token counts.** Measure with the pre-pass; estimates are labeled
- as `~N` chars/4 approximations.
+- **Inventing token counts.** Run the pre-pass; estimates are labeled `~N`
+ with the divisor stated, and a host-reported exact figure always wins.
- **Rewriting identity content yourself.** If a finding is about WHAT an
identity file says (wrong persona, outdated profile), route to soul-audit —
the interview is the only author of that content.
diff --git a/skills/conventions/schema-evolution.md b/skills/conventions/schema-evolution.md
index 535096d2d8..8bd70c7f5a 100644
--- a/skills/conventions/schema-evolution.md
+++ b/skills/conventions/schema-evolution.md
@@ -124,7 +124,7 @@ pointing at the `unify-types` PROTECTED Minion handler.
v0.41.22 ships **gbrain-base-v2** as the declared successor to
[email protected] — collapses 94 noisy types to 15 canonical via
declarative mapping_rules. Run via `gbrain onboard --check --explain`
-(preview) → `gbrain jobs submit unify-types --allow-protected --params
+(preview) → `gbrain jobs submit unify-types --params
'{"target_pack":"gbrain-base-v2","apply":true}'` (apply — `apply`
defaults to false, so a bare submit is a dry run). See
`skills/schema-unify/SKILL.md` for the full playbook.
diff --git a/skills/enrich/SKILL.md b/skills/enrich/SKILL.md
index 5237f7f798..33ae1c0ae3 100644
--- a/skills/enrich/SKILL.md
+++ b/skills/enrich/SKILL.md
@@ -277,8 +277,11 @@ Active items, pending decisions, things to track.
**Note (v0.10.1):** Links between brain pages are auto-created on every
`put_page` call (auto-link post-hook). Step 7 focuses on content
cross-references (updating related pages' compiled truth with new signal
-from this enrichment), not on creating links. Verify via the `auto_links`
-field in the put_page response (`{ created, removed, errors }`).
+from this enrichment), not on creating links. On a trusted local write the
+put_page response carries `auto_links: { created, removed, errors }`; MCP
+writes (stdio and HTTP) return `auto_links: { skipped: "remote", hint }`
+instead — edges are reconciled by the serve maintenance sweep or
+`gbrain sweep --once`, and `add_link` covers an edge you need immediately.
Timeline entries still need explicit `gbrain timeline-add` calls.
## Bulk Enrichment Rules
diff --git a/skills/frontmatter-guard/SKILL.md b/skills/frontmatter-guard/SKILL.md
index 77919debb8..654f8cc1ca 100644
--- a/skills/frontmatter-guard/SKILL.md
+++ b/skills/frontmatter-guard/SKILL.md
@@ -229,4 +229,4 @@ title: "My "Quoted" Title"
**Don't run `audit` on a brain where sources aren't registered.** The CLI returns "no registered sources to audit" gracefully, but the migration emits a `skipped: no_sources` phase result. Don't paper over this with a manual path-walk; the right fix is to register the source via `gbrain sources add`.
-**Don't install the pre-commit hook on non-git brain dirs.** The install-hook command skips them automatically with a one-line note. If you see "skipped — not a git repo" and want validation at write time anyway, use the `audit` command on a cron schedule.
+**Don't install the pre-commit hook on brain dirs outside any git repo.** The install-hook command skips them automatically with a one-line note (a brain that is a subdirectory of a host repo is fine — the hook installs at the host root, scoped to that subdirectory). If you see "skipped, not a git repo" and want validation at write time anyway, use the `audit` command on a cron schedule.
diff --git a/skills/maintain/SKILL.md b/skills/maintain/SKILL.md
index f08e4e81be..73f3f6d45e 100644
--- a/skills/maintain/SKILL.md
+++ b/skills/maintain/SKILL.md
@@ -180,7 +180,11 @@ counted as warnings, not edits. Telemetry lands in
Reads recent reflections within `dream.patterns.lookback_days` (default 30),
runs a single Sonnet pass to surface recurring themes, and writes pattern
pages to `wiki/personal/patterns/<theme>` when ≥`dream.patterns.min_evidence`
-(default 3) reflections support a pattern.
+(default 3) reflections support a pattern. A completed run records the newest
+reflection it consumed (`dream.patterns.last_evidence_ts`); until a reflection
+in the window is newer than that, re-runs skip with `no_new_evidence` instead
+of paying for another model pass — `gbrain dream --phase patterns --once`
+forces one.
**Quality bar (Iron Law for synthesis):**
1. Quote the user verbatim. Quotation marks are ONLY for spans reproducible
diff --git a/skills/schema-unify/SKILL.md b/skills/schema-unify/SKILL.md
index f16841f630..9e2dd9927f 100644
--- a/skills/schema-unify/SKILL.md
+++ b/skills/schema-unify/SKILL.md
@@ -89,7 +89,6 @@ The handler is PROTECTED (manual_only) — autopilot will never auto-fire it. Su
```bash
gbrain jobs submit unify-types \
- --allow-protected \
--params '{"target_pack":"gbrain-base-v2","apply":true}'
```
@@ -97,7 +96,7 @@ On PGLite (the install default), or on any setup without a running `gbrain jobs
```bash
gbrain jobs submit unify-types \
- --allow-protected --follow \
+ --follow \
--params '{"target_pack":"gbrain-base-v2","apply":true}'
```
@@ -208,7 +207,7 @@ Worried about a specific cluster's mapping?
Inputs:
- A brain on `gbrain-base` (or any pack with `migration_from: gbrain-base-v2`).
-- Write access to submit a PROTECTED Minion handler (`--allow-protected`).
+- Trusted local CLI access on the brain host: `gbrain jobs submit` grants the PROTECTED-handler opt-in itself for protected names; the remote MCP `submit_job` op cannot.
- ~10 min wallclock on a 186K-page brain.
Outputs:
@@ -230,7 +229,7 @@ Failure modes:
## Anti-Patterns
DON'T:
-- Submit `unify-types` directly via the MCP `submit_job` op without `--allow-protected`. PROTECTED handlers require trusted local callers; remote MCP rejection is the intentional trust boundary.
+- Submit `unify-types` via the remote MCP `submit_job` op. PROTECTED handlers require trusted local callers (`gbrain jobs submit` on the brain host); remote MCP rejection is the intentional trust boundary.
- Edit `mapping_rules` in `gbrain-base-v2.yaml` to skip clusters you don't trust. Fork the pack instead (`gbrain schema fork`) so the source-of-truth migration stays consistent across brains.
- Run `unify-types` from inside an autopilot tick. The check is `manual_only` — autopilot deliberately never auto-fires it because pack upgrades are one-time consenting taxonomy decisions.
- Hard-delete soft-deleted source pages before the 72h restore window. Use `gbrain restore <slug>` first if rollback is needed.
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index dd4175a342..0e7c6e74a0 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -20,7 +20,7 @@
"brain-ingest-gate/routing-eval.jsonl": "281e94affbb8631ef7ff44203884cce1c03c468b27f893829da1e6e439401a33",
"brain-link-discipline/SKILL.md": "489268f71a01abb6213df8a8bb5f4d16d587b09dd670ac3c47876a8ed808b5ae",
"brain-link-discipline/routing-eval.jsonl": "0adea4c6d72fdb849c12fe2cad718568b9ab704299b00b093c40c2284faf684c",
- "brain-ops/SKILL.md": "4953e2d9d516957b7d9bd349a3e0bae89b1424eb070f68d943a1a078b254ac21",
+ "brain-ops/SKILL.md": "e4bc71357893b9268048ce53d72e04db123b877f85fe0242bddaaa5bb6d344f2",
"brain-pdf/SKILL.md": "13c3e3162763a4503685db0a10663475d3687c4874b5f04d539af83a990f643e",
"brain-pdf/routing-eval.jsonl": "119e4fa113ea45783cee4499e63a729fdeecb4d9a45d47497754b4f5b21d0734",
"brain-taxonomist/SKILL.md": "dea4557b540868ec2c56bf43ee7f63c5d03a22d4047cd0dfbeaf19adef334f60",
@@ -42,7 +42,7 @@
"company-brainify/routing-eval.jsonl": "6f27f835eda9ae77a2b694534c78a043a871349820e8c638c3d8bbba6d3aa17b",
"concept-synthesis/SKILL.md": "ed02d2e385143b16a1e69ee5934288fb4d0b755f68c4312faff663e6b2d7c4ed",
"concept-synthesis/routing-eval.jsonl": "96dbd7d9c1b606e9e06262d0c06282399741e2bccb8eeb7b9ca88c20f44cda0e",
- "context-audit/SKILL.md": "6c811783349f740f039078bef991077bdc85007b2f730897465266e4c31b66da",
+ "context-audit/SKILL.md": "450c7529b6d1eee7fbd7c87b8d24e88b58c32a097e79ef7e598d4c94a98a5b5c",
"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",
"conventions/brain-first.md": "d9b18321150830d38586f5bd23ce9de735f08ac3b54d7ac63bc3184a61e17ef1",
"conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6",
@@ -55,7 +55,7 @@
"conventions/quality.md": "8aa681001114689d34268ccadaf0e2ff07b8f68aa5987c093a8c4a7a744f12a6",
"conventions/regex-discipline.md": "d96a9baa6f27184e165889a9c655607366a739d851684d9f41cdec294f99edac",
"conventions/salience-and-recency.md": "0ee7f0216f36a5e321673740d148cb0f1113268df19301bb2473a48a728a500b",
- "conventions/schema-evolution.md": "b5cdd5a17e43b4f2d0546ebf8c421cc0378cbcf74cb2fe97199e115ccb05f9c2",
+ "conventions/schema-evolution.md": "24028e39facb22fd9abbfeea047e2a2538470d0681461b69d3ed64fe59341233",
"conventions/search-modes.md": "550a94923e483e0b61e3d9eb6242f13a08e0a37a1eb1b95d4111bfa6ecc7658d",
"conventions/subagent-routing.md": "8b8830b815a9a8581a12b489f966c0b0a39eb9b5f66e905a691a03653eef348d",
"conventions/test-before-bulk.md": "6b2c52cda9e2cd5f04c15152b3d92aeb7187ab193a15082be0f8a3991a6a5725",
@@ -78,10 +78,10 @@
"draft-in-voice/routing-eval.jsonl": "590fc16277ed7c3338776e7fac6daf1270b91058941f8101079bb295d2d8f787",
"eiirp/SKILL.md": "d58464cd02a6e5a21d2ad23cf946fbe97ab197de029cfc29e437265ce4c74eb2",
"eiirp/routing-eval.jsonl": "d0000eec8154ba48488eed07e8f1a6a0ccb66d0b39e41f29d279a875c1673227",
- "enrich/SKILL.md": "9988168348f6c3391d3aeec6621f9c99c8d75d1e1bfdd6c44d48e4c1067ab775",
+ "enrich/SKILL.md": "a876b1f89ab0b492bcf3ebbe3447f682ecbcf4f83d213d3ca854c3922f2b3fb5",
"fact-check/SKILL.md": "21a28e6cf6c5494e7c3e97dfa6bf6139b97c735fc229c974bbad89db4a2ff4a9",
"fact-check/routing-eval.jsonl": "7519c6eada244813264b0df34ed67613e2d4404cfdf3cb209051b461749f5662",
- "frontmatter-guard/SKILL.md": "a20fed7da1aecc38818f2b649df0ac3c8a218a742efbe2a774d3cea34a728e7d",
+ "frontmatter-guard/SKILL.md": "9d341bc1e02aa09528718e020b092102490d3de06701b18e319d31fb72e6d4d2",
"frontmatter-guard/routing-eval.jsonl": "243c28b04b557bac5360318c0f47bb6f1dd56d2f720aad3763b93fc0b2ea081e",
"functional-area-resolver/SKILL.md": "52df04bc4f8e678f931c3b2078b2126524e6d2d72676ad46b6b710d13271b46c",
"functional-area-resolver/routing-eval.jsonl": "f80674d915acdfe229046737a5b171da834be15ac6524b5a3fd18048e9b37028",
@@ -92,7 +92,7 @@
"idea-lineage/SKILL.md": "bbf37781d93b71ddc7909ecc5ab635872c874fb8591995dbf88b45ffeac6b1de",
"idea-lineage/routing-eval.jsonl": "ee2e00704b9accb7dd58bb8f126a3bc04a2c40be499180fa505dbf6d5061cd41",
"ingest/SKILL.md": "dc40ecc0072806fb8c7bb6ab9cf1f103842e05653eb55d67632d7e3ffc4dd7d2",
- "maintain/SKILL.md": "987b470e34a6cad2c3c12f9b4a77183fdeee0dcb918f792b7545e6f552fd4aa1",
+ "maintain/SKILL.md": "e0bfe8769b2fe19a28c22a36f3e24f5df83201fba0d08050824ff8b913cdf74d",
"manifest.json": "c7fb80201fea7eafb815d1e242002c5838f3c853f857fd203ef34ee84dd2f057",
"measure-before-you-fix/SKILL.md": "1fd3b40ab65cbd08f50dea16107701859165469be3c85c57d779c7b4bbf92db8",
"measure-before-you-fix/routing-eval.jsonl": "0661df9974a9cfe31216d574b1db0ef341945c2eb844ebf4ab6920fcbbc90d6c",
@@ -161,7 +161,7 @@
"resolve-before-asking/SKILL.md": "1882c45b2e603bbb1e251d388cc2682270ee7eae99211d5a5322430f4667fb39",
"resolve-before-asking/routing-eval.jsonl": "bac1bcf30337f5255ef4ce1a2a8a2b38d58ebcd576503c483190c79ec6e69489",
"schema-author/SKILL.md": "1dd11a44dabcb7d57244be4cf5f4903feb9d146bcbb4363fc150daefc01d04ce",
- "schema-unify/SKILL.md": "e9ac84018d673d35f749a1f74380d635512308fa50951995a7cb339ab4c85fa6",
+ "schema-unify/SKILL.md": "31227b5a9d90e0f1482b52cfd6d23a71575cdbc36f2edcfa8f0170bfb7b95467",
"setup/SKILL.md": "03216a34292ccc44984bca614d5dcf5f2afd1d762a0222c603dd2bc67f047a22",
"signal-detector/SKILL.md": "ea090be2fedeb528c3b3a4b3c649abd3ff07b3ecdc6266bf2930364537683489",
"skill-autobench/SKILL.md": "144572ec76f3784a97645dfde587ab13d77e804f50b00dc7fbe678204de6ff21",
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index 4d349c32e7..1b08f92812 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -1073,6 +1073,13 @@ export function parseAuthCreateArgs(rest: string[]): { name: string; takesHolder
const AUTH_USAGE = `GBrain Token Management
+Admin dashboard login (running HTTP server):
+ For "Give me the GBrain admin login link", use POST /admin/api/issue-magic-link
+ with the server bootstrap credential through the host's protected credential flow.
+ It returns a five-minute, single-use owner login link. Deliver it privately;
+ do not GET the generated link to check it. A static /admin/ URL only opens the login page.
+ This does not create an MCP bearer token. See docs/mcp/DEPLOY.md.
+
Usage:
gbrain auth create <name> [--takes-holders world,garry,brain] [--scopes read,write]
Create a legacy bearer token. v0.28: --takes-holders
diff --git a/src/commands/autopilot-fanout.ts b/src/commands/autopilot-fanout.ts
index 43773b6e70..5c00117701 100644
--- a/src/commands/autopilot-fanout.ts
+++ b/src/commands/autopilot-fanout.ts
@@ -37,6 +37,7 @@ import type { BrainEngine, SourceRow } from '../core/engine.ts';
import type { MinionQueue } from '../core/minions/queue.ts';
import { SOURCE_FRESHNESS_PHASES, MAINTENANCE_PHASES, LAST_GLOBAL_AT_KEY } from '../core/cycle.ts';
import { sourceConfigHasRemoteUrl, sourceLocalPathSkipWarning } from '../core/sources-load.ts';
+import { isSyncDisabledConfig } from '../core/sync-policy.ts';
import { AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES } from './autopilot-remediation-policy.ts';
// #2194 fix #2: failure cooldown. A source whose autopilot-cycle keeps
@@ -505,7 +506,12 @@ export async function dispatchPerSource(
const coalesced: string[] = [];
for (const src of dispatch) {
try {
- const shouldPull = sourceConfigHasRemoteUrl(src.config);
+ // #4399: config.syncEnabled=false excludes the source from automatic
+ // sync. It still gets its lint/backlinks/extract cycle and freshness
+ // stamp; only the sync phase (and the pull that feeds it) is dropped —
+ // normalizeQueuedSourcePhases passes a freshness subset through as-is.
+ const syncDisabled = isSyncDisabledConfig(src.config);
+ const shouldPull = sourceConfigHasRemoteUrl(src.config) && !syncDisabled;
const job = await queue.add(
'autopilot-cycle',
{
@@ -515,7 +521,7 @@ export async function dispatchPerSource(
// Freshness is stamped by bounded deterministic work only. LLM-backed
// source enrichment (atoms, takes, thin-page development, etc.) is
// explicit/background work and cannot hold source freshness hostage.
- phases: SOURCE_FRESHNESS_PHASES,
+ phases: syncDisabled ? SOURCE_FRESHNESS_PHASES.filter((p) => p !== 'sync') : SOURCE_FRESHNESS_PHASES,
},
{
queue: 'default',
diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.ts
index 094898710a..70ff616840 100644
--- a/src/commands/autopilot.ts
+++ b/src/commands/autopilot.ts
@@ -46,6 +46,7 @@ import { evaluateQuietHours } from '../core/minions/quiet-hours.ts';
import { inspectLock } from '../core/db-lock.ts';
import { registerCleanup } from '../core/process-cleanup.ts';
import { loadAllSources, sourceConfigHasRemoteUrl, sourceLocalPathSkipWarning, relativeSourceLocalPathSkipWarning } from '../core/sources-load.ts';
+import { isSyncDisabledConfig } from '../core/sync-policy.ts';
import { resolveAutopilotDispatchTimeoutMs } from './autopilot-timeout.ts';
import {
autopilotRemediationIdempotencyKey,
@@ -1086,6 +1087,10 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
const now = Date.now();
for (const src of sources) {
if (!src.local_path) continue;
+ // #4399: config.syncEnabled=false excludes a source from AUTOMATIC
+ // sync (this loop, the full-cycle fan-out, `sync --all`); an
+ // explicit `gbrain sync --source <id>` is unaffected.
+ if (isSyncDisabledConfig(src.config)) continue;
// A local_path this machine cannot use — relative (#3696: cwd is
// launchd's, not the registering shell's) or absent on disk and
// not a managed clone sync can re-create — would sync a phantom
diff --git a/src/commands/brainstorm.ts b/src/commands/brainstorm.ts
index 3f1e0b8655..a0dc79ad00 100644
--- a/src/commands/brainstorm.ts
+++ b/src/commands/brainstorm.ts
@@ -264,12 +264,21 @@ async function runBrainstormCli(
// catch. Without this CLI formatter, the typed error reaches main()'s
// generic catch which prints `e.message` only — losing the structured
// `.hint` field that's the whole point of the orchestrator-level wrap.
+ // Save policy: brainstorm defaults to save-on; lsd defaults to save-off.
+ // CLI --save / --no-save overrides the default. The slug is minted BEFORE
+ // the run so the orchestrator can bank it in the checkpoint: a `--resume`
+ // after a judge failure then hands back the slug the failed run saved
+ // under, and the re-scored page overwrites it instead of forking a second
+ // page under a fresh nonce.
+ const shouldSave = parsed.save ?? profile.default_save;
+ const freshSlug = buildIdeaSlug(parsed.question, profile.label);
let result;
try {
result = await runBrainstorm(engine, config, {
question: parsed.question,
profile: effectiveProfile,
skipCostPreview: skipPreview,
+ ideaSlug: shouldSave ? freshSlug : undefined,
// v0.39.0.0 T10 cost-cap surface — wired in master, preserved here.
maxCostUsd: parsed.maxCost,
maxFarSet: parsed.maxFarSet,
@@ -305,16 +314,13 @@ async function runBrainstormCli(
const md = formatBrainstormMarkdown(result, { onlyPassed: true, includeMeta: true });
console.log(md);
- // Save policy: brainstorm defaults to save-on; lsd defaults to save-off.
- // CLI --save / --no-save overrides the default.
- const shouldSave = parsed.save ?? profile.default_save;
if (shouldSave) {
- const slug = buildIdeaSlug(parsed.question, profile.label);
+ const slug = result.idea_slug ?? freshSlug;
const title = `${profile.label === 'lsd' ? 'LSD' : 'Brainstorm'}: ${parsed.question.slice(0, 100)}`;
// Build ONE frontmatter object and render via the canonical serializer so
// the saved file round-trips through `gbrain sync` byte-for-byte. Include
- // filtered ideas (onlyPassed:false) so a future --retry-judge has the full
- // set to re-score.
+ // filtered ideas (onlyPassed:false) so a judge-failed run still shows every
+ // idea; `--resume <run_id>` re-scores and overwrites this same page.
const fmObj = buildBrainstormFrontmatterObject(result);
const body = formatBrainstormMarkdown(result, { onlyPassed: false, includeMeta: true });
const content = serializeMarkdown(fmObj, body, '', { type: 'note', title, tags: [] });
diff --git a/src/commands/code-callees.ts b/src/commands/code-callees.ts
index c7e87da445..857844fed3 100644
--- a/src/commands/code-callees.ts
+++ b/src/commands/code-callees.ts
@@ -55,6 +55,7 @@ export async function runCodeCallees(engine: BrainEngine, args: string[]): Promi
limit,
allSources,
sourceId: sourceId ?? undefined,
+ bareFallback: true, // #4670: bare method names resolve via content_chunks.symbol_name
});
// Call-graph readiness ('edge' grain): distinguishes "graph not built / still
diff --git a/src/commands/conversation-parser.ts b/src/commands/conversation-parser.ts
index efe988b6da..8fc8b97f64 100644
--- a/src/commands/conversation-parser.ts
+++ b/src/commands/conversation-parser.ts
@@ -187,6 +187,8 @@ async function runScan(
message_count: result.messages.length,
unmatched_line_count: result.unmatched_line_count,
timezone_warning: result.timezone_warning,
+ // undefined on healthy pages → JSON.stringify drops the key (byte-identical).
+ date_fallback_count: result.date_fallback_count,
unrecognized_headings: result.unrecognized_headings,
first_3_messages: result.messages.slice(0, 3).map((m) => ({
speaker: m.speaker,
@@ -213,6 +215,9 @@ async function runScan(
(result.timezone_warning
? ` timezone_warning: ${result.timezone_warning}\n`
: '') +
+ (result.date_fallback_count
+ ? ` date_fallbacks: ${result.date_fallback_count} — anchor date(s) could not be rebuilt (e.g. a localized month); those messages inherit the previous timestamp\n`
+ : '') +
(result.unrecognized_headings
? ` unrecognized_headings: [${result.unrecognized_headings.join(', ')}] — folded into the previous turn; speaker attribution may be wrong (#4136)\n`
: ''),
diff --git a/src/commands/doctor-asset-paths.ts b/src/commands/doctor-asset-paths.ts
index 80f44b037a..8d86d218f7 100644
--- a/src/commands/doctor-asset-paths.ts
+++ b/src/commands/doctor-asset-paths.ts
@@ -76,3 +76,21 @@ export function resolveImageAssetPath(
): AssetPathResolution {
return resolveAssetPath(storagePath, sourceLocalPath ?? fallbackRepoRoot);
}
+
+/**
+ * Which lane a files row's bytes live in, from its `metadata.storage` stamp
+ * (#4910). `'backend'` = an explicit non-git lane (supabase / s3 / the local
+ * backend root): storage_path is a bucket key, never a source-relative file,
+ * so only `gbrain files verify` can check it. `'local'` = explicit `git` OR
+ * no stamp at all — unmarked rows (sync-ingested, pre-fix writers) keep the
+ * on-disk stat so genuinely vanished repo assets are still caught. Accepts
+ * the #2339-era string-scalar shape like files verify does.
+ */
+export function imageAssetStorageLane(metadata: unknown): 'backend' | 'local' {
+ let meta = metadata;
+ if (typeof meta === 'string') {
+ try { meta = JSON.parse(meta); } catch { return 'local'; }
+ }
+ const lane = meta && typeof meta === 'object' ? (meta as Record<string, unknown>).storage : undefined;
+ return lane !== undefined && lane !== null && lane !== 'git' ? 'backend' : 'local';
+}
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index 6a6517dc36..5f5e4556ed 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -66,6 +66,7 @@ export {
whoknowsHealthCheck,
pgvectorCheck,
pagesUpsertArbiterCheck,
+ linkSourceCheckConstraintCheck,
jsonbIntegrityCheck,
checkVolunteerChannels,
takesWeightGridCheck,
@@ -163,6 +164,7 @@ import {
whoknowsHealthCheck,
pgvectorCheck,
pagesUpsertArbiterCheck,
+ linkSourceCheckConstraintCheck,
jsonbIntegrityCheck,
checkVolunteerChannels,
takesWeightGridCheck,
@@ -1671,6 +1673,18 @@ export async function buildChecks(
// Best-effort. A broken sources table should not stop doctor.
}
+ // 3a-ter. fts_reindex_incomplete (#4795). An interrupted
+ // `reindex-search-vector` leaves the trigger language flipped with rows
+ // still un-backfilled; the command's marker row stays set until it
+ // completes. Logic lives in doctor/checks/fts-reindex.ts (module-dir rule).
+ if (engine !== null) try {
+ const { ftsReindexIncompleteCheck } = await import('./doctor/checks/fts-reindex.ts');
+ const ftsCheck = await ftsReindexIncompleteCheck(engine!);
+ if (ftsCheck) checks.push(ftsCheck);
+ } catch {
+ // Best-effort. A missing config table should not stop doctor.
+ }
+
// 3b-multi-source. Multi-source drift (v0.31.8 — D8 + D17 + OV12 + OV13).
// Pre-v0.30.3 putPage misrouted multi-source writes to (default, slug).
// For each non-default source with local_path set, walk the FS and surface
@@ -1921,6 +1935,12 @@ export async function buildChecks(
progress.heartbeat('pages_upsert_arbiter');
checks.push(await pagesUpsertArbiterCheck(engine));
+ // 4a-ter. #4613: links_link_source_check shape — a ledger-current brain
+ // whose CHECK reverted to the pre-v114 allowlist rejects every kebab
+ // provenance write; the version counter can't see it.
+ progress.heartbeat('links_link_source_check');
+ checks.push(await linkSourceCheckConstraintCheck(engine));
+
// 4b. pglite_scale — engine-fit signal: makes the init-time 1000-file
// Supabase suggestion re-evaluable for the life of the brain.
progress.heartbeat('pglite_scale');
@@ -2955,7 +2975,7 @@ export async function buildChecks(
checks.push({
name: 'markdown_body_completeness',
status: 'warn',
- message: `${rows.length} page(s) appear truncated (sample: ${sample}). Re-import with: gbrain sync --force`,
+ message: `${rows.length} page(s) appear truncated (sample: ${sample}). Re-import: edit each page body, then run gbrain sync (see docs/integrations/reliability-repair.md)`,
});
}
} catch {
@@ -3869,18 +3889,23 @@ export async function buildChecks(
if (engine) {
progress.heartbeat('image_assets');
try {
- const rows = await engine.executeRaw<{ storage_path: string; source_local_path: string | null }>(
- `SELECT f.storage_path, s.local_path AS source_local_path FROM files f LEFT JOIN sources s ON s.id = COALESCE(f.source_id, 'default') WHERE f.mime_type LIKE 'image/%' LIMIT 1000`
+ const rows = await engine.executeRaw<{ storage_path: string; source_local_path: string | null; metadata: unknown }>(
+ `SELECT f.storage_path, f.metadata, s.local_path AS source_local_path FROM files f LEFT JOIN sources s ON s.id = COALESCE(f.source_id, 'default') WHERE f.mime_type LIKE 'image/%' LIMIT 1000`
);
let vanished = 0;
let foreign = 0;
+ let remote = 0;
const vanishedPaths: string[] = [];
const fs = await import('node:fs');
- const { resolveImageAssetPath } = await import('./doctor-asset-paths.ts');
+ const { resolveImageAssetPath, imageAssetStorageLane } = await import('./doctor-asset-paths.ts');
// storage_path is repo-relative for sync-ingested assets. Prefer the
// owning source's root; sync.repo_path is only a legacy fallback.
const repoRoot = (await engine.getConfig('sync.repo_path')) ?? process.cwd();
for (const r of rows) {
+ // #4910: an explicit non-git lane (supabase/s3/local backend) means
+ // storage_path is a bucket key, never a source-relative file. Only
+ // `gbrain files verify` can probe those; unmarked rows keep the stat.
+ if (imageAssetStorageLane(r.metadata) === 'backend') { remote++; continue; }
// #1835: Windows drive paths (D:/…) translate to the WSL automount
// (/mnt/d/…) under WSL, and are SKIPPED (not "missing") on hosts
// where they cannot exist (macOS / plain Linux) — never joined onto
@@ -3897,12 +3922,16 @@ export async function buildChecks(
if (vanishedPaths.length < 5) vanishedPaths.push(r.storage_path);
}
}
- const checked = rows.length - foreign;
- const foreignNote = foreign > 0
+ const checked = rows.length - foreign - remote;
+ const foreignNote = (foreign > 0
? ` (${foreign} Windows-drive path(s) skipped — not resolvable on this platform)`
- : '';
+ : '') + (remote > 0
+ ? ` (${remote} storage-backend object(s) not checked locally — run \`gbrain files verify\`)`
+ : '');
if (rows.length === 0) {
checks.push({ name: 'image_assets', status: 'ok', message: 'No image assets indexed yet' });
+ } else if (checked === 0) {
+ checks.push({ name: 'image_assets', status: 'ok', message: `No local image assets to check${foreignNote}` });
} else if (vanished === 0) {
checks.push({ name: 'image_assets', status: 'ok', message: `${checked} image(s) all present on disk${foreignNote}` });
} else {
diff --git a/src/commands/doctor/checks/calibration.ts b/src/commands/doctor/checks/calibration.ts
index cd844e5fc2..e1fa2955c5 100644
--- a/src/commands/doctor/checks/calibration.ts
+++ b/src/commands/doctor/checks/calibration.ts
@@ -19,6 +19,7 @@ import {
// drift from what search actually filters.
import { resolveHardExcludes, DEFAULT_HARD_EXCLUDES } from '../../../core/search/source-boost.ts';
import { escapeLikePattern, buildVisibilityClause } from '../../../core/search/sql-ranking.ts';
+import { safeChunksFilter } from '../../../core/search/safe-chunks.ts';
import type { Check } from '../../doctor.ts';
// --- v0.36.1.0 calibration doctor checks (T12) ---
@@ -49,22 +50,34 @@ import type { Check } from '../../doctor.ts';
* `src/core/audit-synopsis.ts`. Failure-only audit means low write
* volume on healthy brains.
*/
-export async function checkContextualRetrievalCoverage(engine: BrainEngine): Promise<Check> {
+export async function checkContextualRetrievalCoverage(
+ engine: BrainEngine,
+ // Source isolation (#4592 class): the remote report threads the caller's
+ // resolved grant here so a source-bound token never reads brain-wide
+ // page counts. Unset = brain-wide (trusted/unrestricted).
+ opts: { sourceIds?: string[] } = {},
+): Promise<Check> {
try {
const { MARKDOWN_CHUNKER_VERSION } = await import('../../../core/chunkers/recursive.ts');
- const rows = await engine.executeRaw<{ chunker_drift: number; mode_null: number }>(
+ const rows = await engine.executeRaw<{ chunker_drift: number; unsealed: number; mode_null: number }>(
`SELECT
COUNT(*) FILTER (WHERE chunker_version < $1)::int AS chunker_drift,
+ -- #5004: pages the safe-chunk fence withholds from every remote read.
+ -- Counted separately from drift: the chunker version may move past
+ -- the fence floor, and only the fence has this consequence.
+ COUNT(*) FILTER (WHERE NOT (${safeChunksFilter('pages')}))::int AS unsealed,
-- #4009 belt+braces: extract receipts are audit artifacts stamped
-- mode 'none' at write time, but a reindex DB fallback can clear
-- the stamp — never count them as "never evaluated".
COUNT(*) FILTER (WHERE contextual_retrieval_mode IS NULL AND type <> 'extract_receipt')::int AS mode_null
FROM pages
WHERE page_kind = 'markdown'
- AND deleted_at IS NULL`,
- [MARKDOWN_CHUNKER_VERSION],
+ AND deleted_at IS NULL
+ ${opts.sourceIds ? 'AND source_id = ANY($2::text[])' : ''}`,
+ opts.sourceIds ? [MARKDOWN_CHUNKER_VERSION, opts.sourceIds] : [MARKDOWN_CHUNKER_VERSION],
);
const chunkerDrift = rows[0]?.chunker_drift ?? 0;
+ const unsealed = rows[0]?.unsealed ?? 0;
const modeNull = rows[0]?.mode_null ?? 0;
// Synopsis-failures audit summary (best-effort; missing audit file = 0).
@@ -83,7 +96,8 @@ export async function checkContextualRetrievalCoverage(engine: BrainEngine): Pro
// Audit module unavailable — skip the summary line.
}
- if (chunkerDrift === 0 && modeNull === 0 && failureSummaryLine === '') {
+ const needsReindex = chunkerDrift > 0 || unsealed > 0 || modeNull > 0;
+ if (!needsReindex && failureSummaryLine === '') {
return {
name: 'contextual_retrieval_coverage',
status: 'ok',
@@ -95,16 +109,16 @@ export async function checkContextualRetrievalCoverage(engine: BrainEngine): Pro
if (chunkerDrift > 0) {
parts.push(`${chunkerDrift} page(s) at older chunker_version`);
}
+ if (unsealed > 0) {
+ parts.push(`${unsealed} page(s) below the safe-chunk index version — withheld from remote/MCP chunk retrieval until reindexed`);
+ }
if (modeNull > 0) {
parts.push(`${modeNull} page(s) never evaluated against CR ladder`);
}
- const fixHint =
- chunkerDrift > 0 || modeNull > 0
- ? ` Run \`gbrain reindex --markdown\` to align.`
- : '';
+ const fixHint = needsReindex ? ` Run \`gbrain reindex --markdown\` to align.` : '';
return {
name: 'contextual_retrieval_coverage',
- status: chunkerDrift > 0 || modeNull > 0 ? 'warn' : 'ok',
+ status: needsReindex ? 'warn' : 'ok',
message: `${parts.join('; ')}.${fixHint}${failureSummaryLine}`,
};
} catch (e) {
diff --git a/src/commands/doctor/checks/core-health.ts b/src/commands/doctor/checks/core-health.ts
index 96b1794690..85373e1e7d 100644
--- a/src/commands/doctor/checks/core-health.ts
+++ b/src/commands/doctor/checks/core-health.ts
@@ -9,6 +9,7 @@ import { fileURLToPath } from 'url';
import { existsSync, readFileSync, statSync } from 'fs';
import type { BrainEngine } from '../../../core/engine.ts';
import { REPAIR_SOURCE_CONFIG_SQL } from '../../../core/source-config-sql.ts';
+import { checkLinkSourceCheck } from '../../../core/link-source-check-repair.ts';
import { loadConfig } from '../../../core/config.ts';
import type { ProgressReporter } from '../../../core/progress.ts';
import type { Check } from '../../doctor.ts';
@@ -189,6 +190,49 @@ export async function pagesUpsertArbiterCheck(engine: BrainEngine): Promise<Chec
}
}
+/**
+ * Doctor check: links_link_source_check constraint shape (#4613).
+ *
+ * The version ledger can read current (>= v114) while the live CHECK still
+ * carries the pre-v114 closed allowlist — then every kebab provenance write
+ * (atom-provenance, concept-provenance) is rejected and the version counter
+ * can't see it. Keyed off pg_constraint via checkLinkSourceCheck. Severity
+ * follows what writes do: only a wrong definition rejects them (fail); an
+ * absent gate or a NOT VALID one still accepts them (warn).
+ */
+export async function linkSourceCheckConstraintCheck(engine: BrainEngine): Promise<Check> {
+ const name = 'links_link_source_check';
+ try {
+ const s = await checkLinkSourceCheck(engine);
+ if (!s.tablePresent || !s.needsRepair) {
+ return {
+ name,
+ status: 'ok',
+ message: s.tablePresent ? 'links_link_source_check has the v114 kebab-case gate' : 'no links table yet',
+ };
+ }
+ const heal = 'Run `gbrain apply-migrations --yes` to heal it (#4613).';
+ if (s.drift === 'wrong_def') {
+ return {
+ name,
+ status: 'fail',
+ message:
+ `links_link_source_check is not the v114 kebab-case gate (${s.def}) — kebab provenance ` +
+ `link writes (atom-provenance, concept-provenance) are being rejected. ${heal}`,
+ };
+ }
+ return {
+ name,
+ status: 'warn',
+ message: s.drift === 'absent'
+ ? `links_link_source_check is absent — link_source has no format gate (writes succeed unchecked). ${heal}`
+ : `links_link_source_check is NOT VALID — existing rows were never validated. ${heal}`,
+ };
+ } catch {
+ return { name, status: 'warn', message: 'Could not check the links_link_source_check constraint' };
+ }
+}
+
/**
* Doctor check: JSONB columns are not double-encoded as strings.
*
@@ -562,9 +606,11 @@ export async function rawProvenanceCheck(engine: BrainEngine): Promise<Check> {
* that grows a layer on every read→write cycle. Any row where
* `jsonb_typeof(config) <> 'object'` is corrupted — federation and ACL settings
* on that source are read off a string instead of the settings object. Surface
- * the affected sources with the repair path. The `gbrain sources` config writers
- * now normalize before write, so any config-writing command self-heals the row
- * (the app unwraps up to 10 nested layers); the SQL below repairs one layer
+ * the affected sources with the repair path. The `gbrain sources` writers that
+ * rewrite the `config` COLUMN (federate/unfederate, webhook set/rotate/clear,
+ * tracked-branch) normalize before write and so self-heal the row (the app
+ * unwraps up to 10 nested layers); writers of other columns (set-cr-mode,
+ * rename, set-path) do not touch it (#5002). The SQL below repairs one layer
* directly for the common case.
*/
export async function checkSourceConfigShape(engine: BrainEngine): Promise<Check> {
@@ -587,8 +633,12 @@ export async function checkSourceConfigShape(engine: BrainEngine): Promise<Check
`${rows.length} source(s) have a non-object config — a JSON string/scalar ` +
`instead of an object (the #2829 re-wrapping bug): ${affected}. ` +
`Federation and ACL settings on these sources won't be read correctly. ` +
- `Repair by running any 'gbrain sources' config write (self-heals nested ` +
- `strings and recoverable arrays), or in SQL: ${REPAIR_SOURCE_CONFIG_SQL}`,
+ `Repair with this SQL: ${REPAIR_SOURCE_CONFIG_SQL} — or re-assert the source's ` +
+ `current federation state with 'gbrain sources federate <id>' / 'unfederate <id>' ` +
+ `(see 'gbrain sources list'; federate on an isolated source also flips it into ` +
+ `default search), which rewrites the config column and self-heals nested strings / ` +
+ `recoverable arrays. Commands that write other columns ('set-cr-mode', 'rename', ` +
+ `'set-path') do not repair it.`,
};
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
diff --git a/src/commands/doctor/checks/fts-reindex.ts b/src/commands/doctor/checks/fts-reindex.ts
new file mode 100644
index 0000000000..0841e5c0fe
--- /dev/null
+++ b/src/commands/doctor/checks/fts-reindex.ts
@@ -0,0 +1,29 @@
+/**
+ * fts_reindex_incomplete doctor check (#4795).
+ *
+ * `gbrain reindex-search-vector` stamps `fts.reindex_in_progress` (= target
+ * language) in the config table before it flips the trigger functions and
+ * clears it only after both backfills return. While the marker is set, rows
+ * written after the flip and rows not yet backfilled are tokenized under
+ * different text-search configurations, so keyword search silently matches
+ * only part of the corpus — a data-correctness fault, hence `fail`. Healthy
+ * brains return null (the caller pushes nothing).
+ *
+ * Lives in the doctor module dir per the peeled-façade rule.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+import { FTS_REINDEX_MARKER_KEY } from '../../../core/fts-language.ts';
+
+export async function ftsReindexIncompleteCheck(engine: BrainEngine): Promise<Check | null> {
+ const lang = await engine.getConfig(FTS_REINDEX_MARKER_KEY);
+ if (!lang) return null;
+ return {
+ name: 'fts_reindex_incomplete',
+ status: 'fail',
+ message:
+ `FTS reindex to language='${lang}' started but did not finish; keyword search is split ` +
+ `across two tokenizers. Fix: GBRAIN_FTS_LANGUAGE=${lang} gbrain reindex-search-vector --yes ` +
+ `(resumes from the saved checkpoint).`,
+ };
+}
diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.ts
index 9581275258..b792bb5844 100644
--- a/src/commands/doctor/report-remote.ts
+++ b/src/commands/doctor/report-remote.ts
@@ -155,8 +155,10 @@ export async function doctorReportRemote(
// When the arbiter is missing, EVERY putPage fails with "no unique or
// exclusion constraint" and the version counter can't see it.
{
- const { pagesUpsertArbiterCheck } = await import('./checks/core-health.ts');
+ const { pagesUpsertArbiterCheck, linkSourceCheckConstraintCheck } = await import('./checks/core-health.ts');
checks.push(await pagesUpsertArbiterCheck(engine));
+ // 2d. #4613: links_link_source_check shape — same drift class as 2b/2c.
+ checks.push(await linkSourceCheckConstraintCheck(engine));
}
// v0.42.x — Life Chronicle (#2390): orphaned event projections. Reads already
@@ -450,7 +452,7 @@ export async function doctorReportRemote(
// - chunker_version drift (pre-v40 pages not yet re-embedded)
// - contextual_retrieval_mode IS NULL (mode never evaluated)
// - synopsis-failures audit JSONL entries from the last 7 days
- checks.push(await checkContextualRetrievalCoverage(engine));
+ checks.push(await checkContextualRetrievalCoverage(engine, { sourceIds: opts.sourceIds }));
// issue #1777 — hidden_by_search_policy: chunked pages withheld from default
// search by the hard-exclude prefix policy. Pure SQL COUNT, safe on the
diff --git a/src/commands/dream.ts b/src/commands/dream.ts
index 224069dbfc..3bbe53ef3f 100644
--- a/src/commands/dream.ts
+++ b/src/commands/dream.ts
@@ -87,9 +87,11 @@ interface DreamArgs {
/**
* issue #2860 — `--once`. One-shot bypass of the named `--phase`'s own
* `dream.<phase>.enabled` / `cycle.<phase>.enabled` config gate, for this
- * invocation only. Never reads or writes config — unlike the old
- * "toggle enabled true, run, toggle back to false" workaround, a crash
- * mid-run can't leave any global state stuck. Requires an explicit
+ * invocation only. Never reads or writes the `.enabled` key — unlike the
+ * old "toggle enabled true, run, toggle back to false" workaround, a crash
+ * mid-run can't leave any global state stuck. (Phases may still write
+ * their own completion stamps, e.g. patterns' `last_evidence_ts` per
+ * #4879, so a forced run isn't re-paid by the next tick.) Requires an explicit
* `--phase <name>`; bare `--once` is a usage error (there'd be no single
* phase to target). Applies only to phases with a config `.enabled` gate
* (patterns, synthesize, conversation_facts_backfill, enrich_thin,
@@ -391,7 +393,8 @@ re-scores the corpus and reconciles the queued synthesis backlog.
Options:
--dry-run Preview all fixes without writing. Note: synthesize
runs the cheap scored triage pass (caches verdicts),
- but skips the synthesis subagents.
+ but skips the synthesis subagents; propose_takes,
+ grade_takes and calibration_profile are skipped.
"--dry-run" does NOT mean "zero LLM calls."
--json Emit the CycleReport as JSON (agent-readable)
--phase <name> Run only the named phase(s). Repeatable — every named
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index f4ba7b217f..e507c7b2ca 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -54,6 +54,7 @@ import {
} from '../core/link-extraction.ts';
// #3190: pack-aware link typing on every extract surface (db/stale/fs).
import { loadActivePackForLocalEngine } from '../core/schema-pack/best-effort.ts';
+import { resolveIncludeFrontmatter } from '../core/extract-frontmatter.ts';
import { inferLinkTypeFromPack } from '../core/schema-pack/link-inference.ts';
export { extractTimelineFromContent, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';
import { extractTimelineFromContent, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';
@@ -69,14 +70,13 @@ import { pathToSlug, slugifyPath, slugifySegment, pruneDir, isSyncable } from '.
import { withRetry, isRetryableConnError } from '../core/retry.ts';
export { withRetry };
export type { WithRetryOpts } from '../core/retry.ts';
-import { buildGazetteer, findMentionedEntities } from '../core/by-mention.ts';
+import { buildGazetteer, findMentionedEntities, hashGazetteer } from '../core/by-mention.ts';
// #4611: the cross-source link fallback follows the configured
// `sources.default` (validated shape) instead of the literal 'default'.
import { isValidSourceId } from '../core/source-id.ts';
import {
loadOpCheckpoint, recordCompleted, clearOpCheckpoint, mentionsFingerprint,
} from '../core/op-checkpoint.ts';
-import { createHash } from 'crypto';
// v0.41.15.0 (T7, D9): --workers N for the fs-walk inner loops via the
// shared sliding-pool helper + PGLite-clamp wrapper.
import { runSlidingPool } from '../core/worker-pool.ts';
@@ -381,6 +381,54 @@ export function walkMarkdownFiles(dir: string): { path: string; relPath: string
return files;
}
+/**
+ * Slug → real on-disk relPath, for every markdown file under a brain dir.
+ *
+ * A slug is NOT a path. `pathToSlug` lowercases each segment and slugifies
+ * it, so rebuilding a file's path as `join(dir, slug + '.md')` only finds
+ * files whose names already happen to be slugs — `Meeting Notes.md` slugs to
+ * `meeting-notes`, and `Report.md` only appears to round-trip on a
+ * case-insensitive filesystem. Every per-slug extractor resolves through this
+ * index instead, so a legitimately-named file is never mistaken for a
+ * deleted one.
+ *
+ * Collisions are possible (two files can slug to one slug). The file whose
+ * name IS the slug wins, which is exactly what the old reconstructed path
+ * found; otherwise the first walked entry wins, so the choice never depends
+ * on directory-read order.
+ */
+export function buildSlugPathIndex(
+ files: ReadonlyArray<{ relPath: string }>,
+): Map<string, string> {
+ const index = new Map<string, string>();
+ for (const file of files) {
+ const slug = pathToSlug(file.relPath);
+ if (!index.has(slug) || file.relPath === `${slug}.md`) index.set(slug, file.relPath);
+ }
+ return index;
+}
+
+/**
+ * Resolve one requested slug to its on-disk relPath: the index first, then
+ * the legacy `slug + '.md'` reconstruction. The index only covers what
+ * `walkMarkdownFiles` emits, but sync ADMITS files the walker never emits —
+ * `_`-prefixed names, and dot-dirs waived via `sync.include_hidden` — and
+ * those slugs still round-trip to their real path. Without the fallback the
+ * per-slug extractors treated every such page as deleted and it imported
+ * with no edges. Only a miss on BOTH means "no file behind this slug".
+ */
+export function resolveSlugRelPath(
+ slugToPath: ReadonlyMap<string, string>,
+ repoPath: string,
+ slug: string,
+): string | undefined {
+ const indexed = slugToPath.get(slug);
+ if (indexed !== undefined) return indexed;
+ const legacy = `${slug}.md`;
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- legacy is `slug + '.md'` for a slug read from the pages table; every stored slug passed validateSlug (no `..` segments, no leading `/`), and repoPath is the registered source root
+ return existsSync(join(repoPath, legacy)) ? legacy : undefined;
+}
+
// --- Link extraction ---
/**
@@ -391,13 +439,13 @@ export function walkMarkdownFiles(dir: string): { path: string; relPath: string
* 2. Wikilinks: [[relative/path]] or [[relative/path|Display Text]]
*
* Both are resolved relative to the file that contains them. External URLs
- * (containing ://) are always skipped. For wikilinks, the .md suffix is added
- * if absent and section anchors (#heading) are stripped.
+ * (containing ://) are always skipped. Section anchors (#heading) are stripped
+ * from both (#4995); for wikilinks, the .md suffix is added if absent.
*/
export function extractMarkdownLinks(content: string): { name: string; relTarget: string }[] {
const results: { name: string; relTarget: string }[] = [];
- const mdPattern = /\[([^\]]+)\]\(([^)]+\.md)\)/g;
+ const mdPattern = /\[([^\]]+)\]\(([^)#]+\.md)(?:#[^)]*)?\)/g;
let match;
while ((match = mdPattern.exec(content)) !== null) {
let target = match[2];
@@ -928,7 +976,9 @@ export async function runExtract(engine: BrainEngine, args: string[]) {
await extractStaleFromDB(engine, {
dryRun: args.includes('--dry-run'),
jsonMode: args.includes('--json'),
- includeFrontmatter: args.includes('--include-frontmatter'),
+ // Flag present → true; absent → the configured knob, so the stale sweep
+ // sync hints at never stamps pages fresh without their frontmatter edges.
+ includeFrontmatter: args.includes('--include-frontmatter') || undefined,
sourceIdFilter: staleSourceId,
catchUp: args.includes('--catch-up'),
});
@@ -1284,7 +1334,11 @@ async function extractForSlugs(
const stdoutQuiet = jsonMode || quiet;
// Build the full slug set for link resolution (fast: just readdir, no file reads)
const allFiles = walkMarkdownFiles(brainDir);
- const allSlugs = new Set(allFiles.map(f => pathToSlug(f.relPath)));
+ // Same real-path resolution the sync hooks use (see buildSlugPathIndex).
+ // Rebuilding `slug + '.md'` here made the cycle's incremental extract treat
+ // every non-slug filename as a deleted file and skip it without a word.
+ const slugToPath = buildSlugPathIndex(allFiles);
+ const allSlugs = new Set(slugToPath.keys());
const doLinks = mode === 'links' || mode === 'all';
const doTimeline = mode === 'timeline' || mode === 'all';
@@ -1375,10 +1429,10 @@ async function extractForSlugs(
// #1972: bail before doing any work for this slug on abort. Trailing
// flushLinks/flushTimeline still commit accumulated rows — no torn write.
if (isAborted(signal)) return;
- const relPath = slug + '.md';
+ const relPath = resolveSlugRelPath(slugToPath, brainDir, slug);
+ if (relPath === undefined) return; // deleted file — sync already handled removal
const fullPath = join(brainDir, relPath);
try {
- if (!existsSync(fullPath)) return; // deleted file — sync already handled removal
const content = readFileSync(fullPath, 'utf-8');
if (doLinks) {
@@ -1603,14 +1657,48 @@ async function extractTimelineFromDir(
// --- Sync integration hooks ---
+/**
+ * What a per-slug sync hook actually got done. `created` is the row count
+ * (unchanged reporting); `processed` is the subset of the requested slugs
+ * whose file was found on disk and read successfully.
+ *
+ * The split exists because the watermark stamp lives at the CALL SITE: the
+ * caller may only stamp `links_extracted_at` for slugs the extractor really
+ * read. Stamping the whole requested set marks silently-skipped pages fresh
+ * and hides them from `extract --stale` forever.
+ */
+export interface ExtractForSlugsResult {
+ created: number;
+ processed: string[];
+}
+
+/**
+ * The slugs both sync hooks read, in the order the caller asked for them.
+ * One `links_extracted_at` watermark covers link AND timeline extraction, so
+ * a slug is only fresh when both halves read it.
+ */
+export function slugsSafeToStamp(
+ links: ExtractForSlugsResult,
+ timeline: ExtractForSlugsResult,
+): string[] {
+ const timelineRead = new Set(timeline.processed);
+ return links.processed.filter((slug) => timelineRead.has(slug));
+}
+
export async function extractLinksForSlugs(
engine: BrainEngine,
repoPath: string,
slugs: string[],
- opts?: { sourceId?: string },
-): Promise<number> {
+ opts?: { sourceId?: string; includeFrontmatter?: boolean },
+): Promise<ExtractForSlugsResult> {
const allFiles = walkMarkdownFiles(repoPath);
- const allSlugs = new Set(allFiles.map(f => pathToSlug(f.relPath)));
+ // Resolve each requested slug to its REAL path (see buildSlugPathIndex).
+ // The old reconstructed path missed any file whose name is not already a
+ // slug: `existsSync` was false, the page was skipped in silence, and the
+ // caller stamped it extracted anyway — so `extract --stale` never came
+ // back for it and the edges were lost for good.
+ const slugToPath = buildSlugPathIndex(allFiles);
+ const allSlugs = new Set(slugToPath.keys());
// v0.18.0+ multi-source: post-sync extract reconciles same-source edges.
// Markdown→markdown links within one repo always live in the caller's
// sourceId. Cross-source extraction (rare) would need a per-repo source
@@ -1622,18 +1710,30 @@ export async function extractLinksForSlugs(
const globalBasename = await isGlobalBasenameEnabled(engine);
// #3190: pack-aware typing on the sync inline hook too.
const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
+ // #4999: resolved HERE, like isGlobalBasenameEnabled above, so every caller
+ // (sync, GitHub/Google source inline extracts) honours the configured
+ // frontmatter knob without per-caller threading — an unattended sync used to
+ // skip `related:` edges and then stamp the page fresh, defeating the knob.
+ const includeFrontmatter = opts?.includeFrontmatter ?? await resolveIncludeFrontmatter(engine);
let created = 0;
+ // Only a slug whose file was found AND read counts as processed. The
+ // caller stamps the watermark for these and no others, so a silent skip
+ // leaves the page stale and `extract --stale` picks it up next run.
+ const processed: string[] = [];
for (const slug of slugs) {
- const filePath = join(repoPath, slug + '.md');
- if (!existsSync(filePath)) continue;
+ const relPath = resolveSlugRelPath(slugToPath, repoPath, slug);
+ if (relPath === undefined) continue;
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- relPath comes from the slug→path index built by walkMarkdownFiles(repoPath) (repo-relative entries of that walk) or the validated-slug legacy fallback, never from a caller
+ const filePath = join(repoPath, relPath);
try {
const content = readFileSync(filePath, 'utf-8');
- for (const link of await extractLinksFromFile(content, slug + '.md', allSlugs, { globalBasename, pack })) {
+ processed.push(slug);
+ for (const link of await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter, pack })) {
try { await engine.addLink(link.from_slug, link.to_slug, link.context, link.link_type, link.link_source, undefined, undefined, linkOpts); created++; } catch { /* skip */ } // gbrain-allow-direct-insert: gbrain extract single-row fallback when batch path declines a row
}
- } catch { /* skip */ }
+ } catch { /* skip: unreadable — not processed, stays stale */ }
}
- return created;
+ return { created, processed };
}
export async function extractTimelineForSlugs(
@@ -1641,23 +1741,30 @@ export async function extractTimelineForSlugs(
repoPath: string,
slugs: string[],
opts?: { sourceId?: string },
-): Promise<number> {
+): Promise<ExtractForSlugsResult> {
+ // Real-path resolution, same as extractLinksForSlugs. Both halves come off
+ // one `links_extracted_at` stamp, so both must agree on what was read.
+ const slugToPath = buildSlugPathIndex(walkMarkdownFiles(repoPath));
// v0.18.0+ multi-source: source-qualify so timeline rows don't fan out
// across every source containing the slug (the addTimelineEntry's
// INSERT...SELECT-from-pages fan-out was Data R1's HIGH 2).
const entryOpts = opts?.sourceId ? { sourceId: opts.sourceId } : undefined;
let created = 0;
+ const processed: string[] = [];
for (const slug of slugs) {
- const filePath = join(repoPath, slug + '.md');
- if (!existsSync(filePath)) continue;
+ const relPath = resolveSlugRelPath(slugToPath, repoPath, slug);
+ if (relPath === undefined) continue;
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- relPath comes from the walkMarkdownFiles(repoPath) index or the validated-slug legacy fallback, never from a caller
+ const filePath = join(repoPath, relPath);
try {
const content = readFileSync(filePath, 'utf-8');
+ processed.push(slug);
for (const entry of extractTimelineFromContent(content, slug)) {
try { await engine.addTimelineEntry(entry.slug, { date: entry.date, source: entry.source, summary: entry.summary, detail: entry.detail }, entryOpts); created++; } catch { /* skip */ } // gbrain-allow-direct-insert: gbrain extract single-row fallback for timeline entries
}
- } catch { /* skip */ }
+ } catch { /* skip: unreadable — not processed, stays stale */ }
}
- return created;
+ return { created, processed };
}
// ─── DB-source extractors (v0.10.3 graph layer) ────────────────────────────
@@ -2045,7 +2152,8 @@ export async function extractStaleFromDB(
jsonMode: boolean;
/** Embedded callers (the cycle) own the report: emit nothing on stdout. */
quiet?: boolean;
- includeFrontmatter: boolean;
+ /** Unset → the configured knob (resolveIncludeFrontmatter); explicit wins. */
+ includeFrontmatter?: boolean;
sourceIdFilter?: string;
catchUp: boolean;
/**
@@ -2058,7 +2166,8 @@ export async function extractStaleFromDB(
timeBudgetMs?: number;
},
): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number }> {
- const { dryRun, jsonMode, includeFrontmatter, sourceIdFilter, catchUp } = opts;
+ const { dryRun, jsonMode, sourceIdFilter, catchUp } = opts;
+ const includeFrontmatter = opts.includeFrontmatter ?? await resolveIncludeFrontmatter(engine);
const log = opts.quiet ? (..._args: unknown[]) => {} : console.log;
const timeBudgetMs = opts.timeBudgetMs ?? STALE_TIME_BUDGET_MS;
const versionTs = LINK_EXTRACTOR_VERSION_TS;
@@ -2292,10 +2401,7 @@ async function extractMentionsFromDb(
// checkpoint cleanly. Without it, resumed pages would skip new
// entities silently (codex flag).
const allowCrossSource = await isCrossSourceLinksEnabled(engine);
- const gazetteerHash = createHash('sha256')
- .update([...gazetteer.keys()].sort().join('|'))
- .digest('hex')
- .slice(0, 8) + (allowCrossSource ? ':xs' : '');
+ const gazetteerHash = hashGazetteer(gazetteer) + (allowCrossSource ? ':xs' : '');
// #4304: --since prunes at the ref level BEFORE the checkpoint diff and
// the per-page getPage loop. Refs outside the window never enter the
diff --git a/src/commands/files.ts b/src/commands/files.ts
index 61d5d986bd..30c6a2e6ad 100644
--- a/src/commands/files.ts
+++ b/src/commands/files.ts
@@ -3,7 +3,7 @@ import { join, relative, extname, basename, dirname, resolve } from 'path';
import { createHash } from 'crypto';
import type { BrainEngine } from '../core/engine.ts';
import type { StorageBackend, StorageConfig } from '../core/storage.ts';
-import { sqlQueryForEngine, executeRawJsonb } from '../core/sql-query.ts';
+import { sqlQueryForEngine, executeRawJsonb, FILES_METADATA_MERGE_SQL } from '../core/sql-query.ts';
import { humanSize } from '../core/file-resolver.ts';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
@@ -182,7 +182,7 @@ async function uploadFile(engine: BrainEngine, args: string[]) {
// Precondition first: a backend-less upload can only produce a phantom row
// (metadata for bytes that were never stored), so refuse before touching the
// DB or reporting anything as uploaded.
- const { storage } = await requireStorageBackend('upload');
+ const { storage, storageConfig } = await requireStorageBackend('upload');
const stat = statSync(filePath);
const hash = fileHash(filePath);
@@ -207,6 +207,9 @@ async function uploadFile(engine: BrainEngine, args: string[]) {
// files.metadata is JSONB — bind a real object via executeRawJsonb instead
// of casting a string into ::jsonb (the #2339 double-encode class).
+ // #4910: stamp the lane so readers (doctor image_assets, files verify)
+ // know storage_path is a bucket key; the upsert merges metadata so a
+ // legacy `{}` row heals on its next content change.
await executeRawJsonb(
engine,
`INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)
@@ -214,9 +217,10 @@ async function uploadFile(engine: BrainEngine, args: string[]) {
ON CONFLICT (storage_path) DO UPDATE SET
content_hash = EXCLUDED.content_hash,
size_bytes = EXCLUDED.size_bytes,
- mime_type = EXCLUDED.mime_type`,
+ mime_type = EXCLUDED.mime_type,
+ ${FILES_METADATA_MERGE_SQL}`,
[pageSlug, filename, storagePath, mimeType, stat.size, hash],
- [{}],
+ [{ storage: storageConfig.backend }],
);
console.log(`Uploaded: ${storagePath} (${humanSize(stat.size)})`);
@@ -306,9 +310,10 @@ async function uploadRaw(engine: BrainEngine, args: string[]) {
ON CONFLICT (storage_path) DO UPDATE SET
content_hash = EXCLUDED.content_hash,
size_bytes = EXCLUDED.size_bytes,
- mime_type = EXCLUDED.mime_type`,
+ mime_type = EXCLUDED.mime_type,
+ ${FILES_METADATA_MERGE_SQL}`,
[sourceId, pageSlug, filename, storagePath, mimeType, stat.size, 'sha256:' + hash],
- [{ storage: 'git', type: fileType }],
+ [{ storage: 'git', ...(fileType ? { type: fileType } : {}) }],
);
console.log(JSON.stringify({
success: true,
@@ -373,9 +378,10 @@ async function uploadRaw(engine: BrainEngine, args: string[]) {
ON CONFLICT (storage_path) DO UPDATE SET
content_hash = EXCLUDED.content_hash,
size_bytes = EXCLUDED.size_bytes,
- mime_type = EXCLUDED.mime_type`,
+ mime_type = EXCLUDED.mime_type,
+ ${FILES_METADATA_MERGE_SQL}`,
[pageSlug, filename, storagePath, mimeType, stat.size, 'sha256:' + hash],
- [{ type: fileType, upload_method: method }],
+ [{ storage: (config.storage as StorageConfig).backend, ...(fileType ? { type: fileType } : {}), upload_method: method }],
);
// Output JSON for scripting
@@ -423,7 +429,7 @@ async function syncFiles(engine: BrainEngine, dir?: string) {
// Pre-fix this command inserted a `files` row per file and reported them as
// "uploaded" without ever calling the storage backend — every row it produced
// was a phantom, even on a brain WITH storage configured.
- const { storage } = await requireStorageBackend('sync');
+ const { storage, storageConfig } = await requireStorageBackend('sync');
const files = collectFiles(dir);
console.log(`Found ${files.length} files to sync`);
@@ -469,9 +475,10 @@ async function syncFiles(engine: BrainEngine, dir?: string) {
ON CONFLICT (storage_path) DO UPDATE SET
content_hash = EXCLUDED.content_hash,
size_bytes = EXCLUDED.size_bytes,
- mime_type = EXCLUDED.mime_type`,
+ mime_type = EXCLUDED.mime_type,
+ ${FILES_METADATA_MERGE_SQL}`,
[pageSlug, filename, storagePath, mimeType, stat.size, hash],
- [{}],
+ [{ storage: storageConfig.backend }],
);
uploaded++;
diff --git a/src/commands/frontmatter-install-hook.ts b/src/commands/frontmatter-install-hook.ts
index 0bc1e6b281..9801039aaa 100644
--- a/src/commands/frontmatter-install-hook.ts
+++ b/src/commands/frontmatter-install-hook.ts
@@ -1,7 +1,7 @@
/**
* gbrain frontmatter install-hook — Install a pre-commit hook in a brain
* source's git repo that runs `gbrain frontmatter validate` against staged
- * .md/.mdx files. Skips non-git sources with a one-line note.
+ * .md/.mdx files. Skips sources outside any git repo with a one-line note.
*
* Usage:
* gbrain frontmatter install-hook [--source <id>] [--force] [--uninstall]
@@ -11,25 +11,71 @@
* --uninstall Remove the hook; restore <hook>.bak if present.
*
* Hook contract:
- * - Located at <source>/.githooks/pre-commit. We `git config core.hooksPath
- * .githooks` if no other hooksPath is set.
+ * - Located at <git root>/.githooks/pre-commit. The root is discovered the
+ * way `gbrain sync` does (#4600): a source registered as a SUBDIRECTORY of
+ * a host repo (the `<workspace>/brain` layout bootstrap creates) gets ONE
+ * hook at the host root, pathspec-scoped to that subdirectory; several
+ * nested sources union their scopes; a source registered at the root
+ * renders the unscoped whole-repo script. We `git config core.hooksPath
+ * .githooks` only when `hooksPathBlocker` finds nothing: core.hooksPath
+ * unset (one already resolving to `.githooks` is left alone; one pointing
+ * elsewhere — global/corporate templates — is theirs to keep and reported
+ * as unwired, since git never reads `.githooks/` then), no foreign
+ * executable under `.githooks/` (wiring would start running it) and no
+ * active hook in the repo's own hooks dir (`.git/hooks` — wiring makes git
+ * ignore it for EVERY hook type). Either way the hook is written and the
+ * reason + manual wiring step printed.
* - When the gbrain binary is missing, the hook prints a one-line warning
* and exits 0 (don't break commits if a developer uninstalls gbrain).
* - Bypass via `git commit --no-verify`.
*/
-import { existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync, rmSync, copyFileSync } from 'fs';
-import { join } from 'path';
+import { existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync, rmSync, copyFileSync, realpathSync, readdirSync, statSync, lstatSync } from 'fs';
+import { isAbsolute, join, relative, resolve } from 'path';
import { execFileSync } from 'child_process';
import type { BrainEngine } from '../core/engine.ts';
import { loadConfig, toEngineConfig } from '../core/config.ts';
import { createEngine } from '../core/engine-factory.ts';
+import { discoverGitRoot } from '../core/sync-git.ts';
const HOOK_BANNER = '# gbrain frontmatter pre-commit hook (v0.22.4+)';
+/** One line per guarded subdirectory (root-relative, trailing slash). No lines = whole repo. */
+const SCOPE_MARKER = '# gbrain-scope: ';
-const HOOK_SCRIPT = `#!/bin/sh
+const shellQuote = (s: string): string => `'${s.replace(/'/g, "'\\''")}'`;
+
+/**
+ * A scope is rendered into a `#` comment line and a `'…'` pathspec: a line
+ * terminator inside it would end the comment early and run the rest of the
+ * path as hook code. Refused at the seam (path → scope) and again at render.
+ */
+function assertNoLineTerminator(scope: string): void {
+ if (/[\n\r\0]/.test(scope)) {
+ throw new Error(`source path contains a line terminator; refusing to install hook: ${JSON.stringify(scope)}`);
+ }
+}
+
+/**
+ * Run git in `root`; trimmed stdout, throws on non-zero. `env: process.env`
+ * keeps the child on the LIVE environment (Bun's default is a startup
+ * snapshot, Node's is live) so a caller's `GIT_CONFIG_*` overrides are honored.
+ */
+const git = (root: string, args: string[]): string =>
+ execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', env: process.env }).trim();
+
+/**
+ * Render the hook script. Empty `scopes` = the whole repo (byte-identical to
+ * the pre-#4600 script); otherwise `git diff --cached` is limited to the
+ * listed pathspecs. Git runs hooks from the worktree root, so the
+ * root-relative paths it lists resolve as-is for `gbrain frontmatter validate`.
+ */
+function renderHookScript(scopes: string[]): string {
+ scopes.forEach(assertNoLineTerminator);
+ const marker = scopes.map((s) => `${SCOPE_MARKER}${s}\n`).join('');
+ const pathspec = scopes.length > 0 ? ` -- ${scopes.map(shellQuote).join(' ')}` : '';
+ return `#!/bin/sh
${HOOK_BANNER}
-# Validates YAML frontmatter on staged .md / .mdx files. Bypass with
+${marker}# Validates YAML frontmatter on staged .md / .mdx files. Bypass with
# 'git commit --no-verify'. Uninstall with 'gbrain frontmatter install-hook --uninstall'.
set -e
@@ -39,17 +85,23 @@ if ! command -v gbrain >/dev/null 2>&1; then
exit 0
fi
-staged=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\\.mdx?$' || true)
+# One path per line: -z disables git's quoting (a non-ASCII name would print
+# as "caf\\303\\251.md"), tr turns the NUL terminators into newlines, and the
+# read loop keeps spaces intact (a newline INSIDE a name is the one unsupported
+# shape). The heredoc keeps the loop in this shell so 'failed' survives it.
+staged=$(git diff --cached --name-only -z --diff-filter=ACM${pathspec} | tr '\\0' '\\n' | grep -E '\\.mdx?$' || true)
[ -z "$staged" ] && exit 0
failed=0
-for f in $staged; do
+while IFS= read -r f; do
[ -f "$f" ] || continue
if ! gbrain frontmatter validate "$f" >/dev/null 2>&1; then
gbrain frontmatter validate "$f" >&2
failed=1
fi
-done
+done <<EOF
+$staged
+EOF
if [ $failed -ne 0 ]; then
echo "" >&2
@@ -57,6 +109,14 @@ if [ $failed -ne 0 ]; then
exit 1
fi
`;
+}
+
+function parseScopes(hook: string): string[] {
+ return hook
+ .split('\n')
+ .filter((l) => l.startsWith(SCOPE_MARKER))
+ .map((l) => l.slice(SCOPE_MARKER.length));
+}
interface SourceRow {
id: string;
@@ -106,13 +166,27 @@ export async function runFrontmatterInstallHook(args: string[]): Promise<void> {
skipped++;
continue;
}
- if (!isGitRepo(src.local_path)) {
- console.log(`[${src.id}] ${src.local_path} — skipped, not a git repo`);
+ let target: HookTarget;
+ try {
+ target = resolveHookTarget(src.local_path);
+ } catch (err) {
+ // Outside any git repo, or a path the hook script cannot carry safely.
+ console.log(`[${src.id}] ${src.local_path} — skipped, ${err instanceof Error ? err.message : String(err)}`);
skipped++;
continue;
}
if (uninstall) {
- if (uninstallHook(src.local_path)) {
+ let removed: boolean;
+ try {
+ removed = uninstallHook(src.local_path);
+ } catch (err) {
+ // Same refusal class as install (symlinked .githooks/ or hook): this
+ // source is reported and skipped, the remaining sources still run.
+ console.log(`[${src.id}] skipped — ${err instanceof Error ? err.message : String(err)}`);
+ skipped++;
+ continue;
+ }
+ if (removed) {
console.log(`[${src.id}] hook removed`);
installed++;
} else {
@@ -120,9 +194,24 @@ export async function runFrontmatterInstallHook(args: string[]): Promise<void> {
}
continue;
}
- const result = installHook(src.local_path, force);
+ let result: InstallResult;
+ try {
+ result = installHook(src.local_path, force);
+ } catch (err) {
+ // e.g. a symlinked .githooks/ — refused, the other sources still run.
+ console.log(`[${src.id}] skipped — ${err instanceof Error ? err.message : String(err)}`);
+ skipped++;
+ continue;
+ }
if (result === 'installed') {
- console.log(`[${src.id}] hook installed at .githooks/pre-commit`);
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- target.root is the git root discovered with `git rev-parse` for a registered source path; the tail is a fixed literal
+ const where = join(target.root, '.githooks', 'pre-commit');
+ console.log(`[${src.id}] hook installed at ${where}${target.scope ? ` (scoped to ${target.scope})` : ''}`);
+ installed++;
+ } else if (result === 'installed_unwired') {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- target.root is the discovered git root of a registered source; fixed literal tail
+ const where = join(target.root, '.githooks', 'pre-commit');
+ console.log(`[${src.id}] hook written at ${where}; core.hooksPath left unset — ${hooksPathBlocker(target.root)}`);
installed++;
} else if (result === 'skipped_existing') {
console.log(`[${src.id}] existing pre-commit hook found; pass --force to overwrite (.bak created)`);
@@ -146,6 +235,8 @@ Usage:
The hook runs \`gbrain frontmatter validate\` against staged .md/.mdx files,
blocking commits with malformed frontmatter. Bypass with 'git commit --no-verify'.
+A source registered as a subdirectory of a host repo gets the hook at the host
+root, scoped to that subdirectory.
Options:
--source <id> Limit to one registered source. Default: all sources.
@@ -170,52 +261,184 @@ async function listSources(engine: BrainEngine, sourceId?: string): Promise<Sour
}
}
-function isGitRepo(dir: string): boolean {
- return existsSync(join(dir, '.git'));
+interface HookTarget {
+ /** Realpath of the enclosing git worktree root. */
+ root: string;
+ /** Root-relative subdirectory the hook guards, trailing slash ('' when local_path IS the root). */
+ scope: string;
+}
+
+/**
+ * Discover the git root enclosing `localPath` (the same helper `gbrain sync`
+ * uses, so both commands accept the same shapes) and the root-relative scope.
+ * Both sides are realpath'd: `git rev-parse --show-toplevel` returns the
+ * resolved path, and an unresolved /tmp on macOS (/private/tmp) would
+ * otherwise yield a `..` scope. Throws when `localPath` is outside any repo.
+ */
+function resolveHookTarget(localPath: string): HookTarget {
+ const root = realpathSync(discoverGitRoot(localPath));
+ const rel = relative(root, realpathSync(localPath));
+ if (rel === '..' || rel.startsWith('../') || isAbsolute(rel)) {
+ throw new Error(`Not inside a git repository: ${localPath} resolves outside its git root ${root}`);
+ }
+ assertNoLineTerminator(rel);
+ return { root, scope: rel ? `${rel}/` : '' };
}
-type InstallResult = 'installed' | 'skipped_existing' | 'unchanged';
+type InstallResult = 'installed' | 'installed_unwired' | 'skipped_existing' | 'unchanged';
-export function installHook(repoPath: string, force: boolean): InstallResult {
- const hooksDir = join(repoPath, '.githooks');
+/**
+ * `.githooks/` and its `pre-commit` under `root`. Refuses a symlink at either
+ * level: a committed link in a host repo would redirect our write/chmod/rm to
+ * wherever it points (lstat, so a dangling link is refused too).
+ */
+function hookPaths(root: string): { hooksDir: string; hookPath: string } {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- root is the discovered git root of a registered source; fixed literal tail
+ const hooksDir = join(root, '.githooks');
const hookPath = join(hooksDir, 'pre-commit');
+ for (const p of [hooksDir, hookPath]) {
+ let link = false;
+ try { link = lstatSync(p).isSymbolicLink(); } catch { /* absent — fine */ }
+ if (link) throw new Error(`Refusing to write through a symlink: ${p}`);
+ }
+ return { hooksDir, hookPath };
+}
+
+/**
+ * Hooks git would run from the repo's own hooks dir today: executable,
+ * non-`*.sample` files (git skips both non-executable files and samples).
+ * The dir is `<git common dir>/hooks` (worktree-safe — `.git` is a FILE in
+ * linked worktrees, and hooks live in the shared common dir). NOT
+ * `rev-parse --git-path hooks`: that honors core.hooksPath, so under a global
+ * hooksPath it would list the FOREIGN dir instead of the one wiring sidelines.
+ */
+export function activeGitHooks(root: string): string[] {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- root is the discovered git root; fixed literal tail
+ let dir = join(root, '.git', 'hooks');
+ try {
+ const p = git(root, ['rev-parse', '--git-common-dir']);
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- p is `git rev-parse --git-path hooks` output for that same root (the operator's own repo layout), not caller input
+ if (p) dir = join(isAbsolute(p) ? p : join(root, p), 'hooks');
+ } catch { /* classic layout fallback */ }
+ return executableHooks(dir);
+}
+
+/** Executable, non-`*.sample` files in `dir` — what git runs from a hooks dir. */
+function executableHooks(dir: string): string[] {
+ if (!existsSync(dir)) return [];
+ return readdirSync(dir).filter((f) => {
+ if (f.endsWith('.sample')) return false;
+ try {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- dir is the resolved hooks directory above and f is a directory entry read from it
+ const st = statSync(join(dir, f));
+ return st.isFile() && (st.mode & 0o111) !== 0;
+ } catch { return false; }
+ }).sort();
+}
+
+/**
+ * Where `core.hooksPath` points today (any scope — a global/corporate value
+ * counts, git reads it), resolved against the worktree root the way git does a
+ * relative value, `~` expanded via `--type=path`; '' when unset.
+ */
+function currentHooksPath(root: string): string {
+ try {
+ const p = git(root, ['config', '--type=path', '--get', 'core.hooksPath']);
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- p is the repo's own core.hooksPath config value, resolved against its git root to compare with `.githooks`
+ return p ? resolve(root, p) : '';
+ } catch {
+ return ''; // git config exits non-zero when the key is unset — the normal case.
+ }
+}
+
+const samePath = (a: string, b: string): boolean => {
+ try { return realpathSync(a) === realpathSync(b); } catch { return a === b; }
+};
+
+/**
+ * Why `.githooks` is not wired as `core.hooksPath` (an operator-facing sentence
+ * with the manual step), or null when it already is / safely can be. A
+ * hooksPath already pointing ELSEWHERE is theirs to keep — git never reads
+ * `.githooks/` then, so "installed" would lie. Wiring makes git run EVERY
+ * executable script in `.githooks/` — third-party clones commit hooks there as
+ * a convention — and ignore `.git/hooks/*` for every hook type, so a foreign
+ * `.githooks/<hook>` or a live `.git/hooks/<hook>` both block it too.
+ */
+export function hooksPathBlocker(root: string): string | null {
+ const current = currentHooksPath(root);
+ if (current) {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- fixed literal tail under the discovered git root
+ if (samePath(current, join(root, '.githooks'))) return null;
+ return `core.hooksPath already points at ${current} (git reads hooks only from there); copy .githooks/pre-commit into it, or run: git -C ${root} config core.hooksPath .githooks`;
+ }
+ const wire = `then run: git -C ${root} config core.hooksPath .githooks`;
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- fixed literal tail under the discovered git root
+ const foreign = executableHooks(join(root, '.githooks')).filter((f) => f !== 'pre-commit');
+ if (foreign.length > 0) return `.githooks/ holds other hook scripts git would start running (${foreign.join(', ')}); review them, ${wire}`;
+ const live = activeGitHooks(root);
+ if (live.length > 0) return `active hooks in .git/hooks (${live.join(', ')}) would stop running; move them into .githooks/, ${wire}`;
+ return null;
+}
+
+export function installHook(localPath: string, force: boolean): InstallResult {
+ const { root, scope } = resolveHookTarget(localPath);
+ const { hooksDir, hookPath } = hookPaths(root);
mkdirSync(hooksDir, { recursive: true });
+ let next = renderHookScript(scope ? [scope] : []);
+ let changed = true;
if (existsSync(hookPath)) {
const existing = readFileSync(hookPath, 'utf8');
if (existing.includes(HOOK_BANNER)) {
- // Already a gbrain hook — refresh the script content silently.
- writeFileSync(hookPath, HOOK_SCRIPT);
- chmodSync(hookPath, 0o755);
- return 'unchanged';
+ // Already a gbrain hook — refresh it, keeping every scope it guards.
+ // One hook per root: a nested source joins the pathspec union; a
+ // whole-repo hook (root source, or no marker) already covers everything.
+ const prior = parseScopes(existing);
+ const wholeRepo = !scope || prior.length === 0;
+ next = renderHookScript(wholeRepo ? [] : [...new Set([...prior, scope])].sort());
+ changed = next !== existing;
+ } else if (!force) {
+ return 'skipped_existing';
+ } else {
+ copyFileSync(hookPath, hookPath + '.bak');
}
- if (!force) return 'skipped_existing';
- copyFileSync(hookPath, hookPath + '.bak');
}
-
- writeFileSync(hookPath, HOOK_SCRIPT);
+ writeFileSync(hookPath, next);
chmodSync(hookPath, 0o755);
- // Set core.hooksPath unless the user has set it to something else already.
- try {
- const current = execFileSync('git', ['-C', repoPath, 'config', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim();
- if (current && current !== '.githooks') return 'installed';
- } catch {
- // git config returns non-zero when the key is unset; that's the normal case.
- }
+ // Every branch that leaves a hook on disk reaches the wiring step: the hook
+ // FILE travels with the repo, core.hooksPath is per-clone config, so a fresh
+ // clone of a repo that committed the hook has the script but git never runs
+ // it. A blocker (hooksPath set elsewhere — theirs to keep — or hooks that
+ // wiring would activate/sideline) leaves it unset; the CLI prints the reason.
+ if (hooksPathBlocker(root)) return 'installed_unwired';
+ if (currentHooksPath(root)) return changed ? 'installed' : 'unchanged'; // already resolves to .githooks
try {
- execFileSync('git', ['-C', repoPath, 'config', 'core.hooksPath', '.githooks']);
+ git(root, ['config', 'core.hooksPath', '.githooks']);
} catch {
// Best-effort. Hook still exists; user can configure manually.
}
return 'installed';
}
-export function uninstallHook(repoPath: string): boolean {
- const hookPath = join(repoPath, '.githooks', 'pre-commit');
+export function uninstallHook(localPath: string): boolean {
+ const { root, scope } = resolveHookTarget(localPath);
+ const { hookPath } = hookPaths(root);
if (!existsSync(hookPath)) return false;
const content = readFileSync(hookPath, 'utf8');
if (!content.includes(HOOK_BANNER)) return false;
+ if (scope) {
+ // Nested source: only its own pathspec is ours to drop — a whole-repo hook
+ // (root-registered source) or other nested sources' scopes stay.
+ const prior = parseScopes(content);
+ if (!prior.includes(scope)) return false;
+ const remaining = prior.filter((s) => s !== scope);
+ if (remaining.length > 0) {
+ writeFileSync(hookPath, renderHookScript(remaining));
+ chmodSync(hookPath, 0o755);
+ return true;
+ }
+ }
rmSync(hookPath);
if (existsSync(hookPath + '.bak')) {
copyFileSync(hookPath + '.bak', hookPath);
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index 74bb8a0db3..0dcc64a62f 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -1471,11 +1471,9 @@ async function hookStop(io: HookIo): Promise<number> {
...(io.transcriptRoot ? { root: io.transcriptRoot } : {}),
});
if (!conf.ok) return `transcript_${conf.reason}`;
- const findLastUser = (ts: WindowTurn[]): WindowTurn | undefined => {
- for (let i = ts.length - 1; i >= 0; i--) {
- if (ts[i].role === 'user' && ts[i].text) return ts[i];
- }
- return undefined;
+ const findLastUser = (parsed: ReturnType<typeof parseTranscript>): WindowTurn | undefined => {
+ const index = parsed.genuineUserTurnIndexes.at(-1);
+ return index === undefined ? undefined : parsed.turns[index];
};
let lastUser: WindowTurn | undefined;
try {
@@ -1488,11 +1486,11 @@ async function hookStop(io: HookIo): Promise<number> {
// wide parse only ever runs when the cheap one failed, so the common
// path keeps the 128KB cost inside this lane's 2s budget.
lastUser = findLastUser(
- parseTranscript(conf.path, { maxBytes: WRITEBACK_TRANSCRIPT_TAIL_BYTES }).turns,
+ parseTranscript(conf.path, { maxBytes: WRITEBACK_TRANSCRIPT_TAIL_BYTES }),
);
if (!lastUser) {
lastUser = findLastUser(
- parseTranscript(conf.path, { maxBytes: USER_PROMPT_TRANSCRIPT_MAX_BYTES }).turns,
+ parseTranscript(conf.path, { maxBytes: USER_PROMPT_TRANSCRIPT_MAX_BYTES }),
);
}
} catch {
diff --git a/src/commands/import.ts b/src/commands/import.ts
index 68419ca84f..0a03ff8292 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -1068,6 +1068,8 @@ export async function runImport(
unchanged: skipped - failures.length - malformedFileSkips,
malformed_skipped: malformedFileSkips,
failures,
+ // Effective destination — same expression as the import-file write (import-file.ts) and the ingest_log row below.
+ source_id: sourceId ?? 'default',
}));
} else {
slog(`\nImport complete (${totalTime}s):`);
diff --git a/src/commands/init-mode-picker.ts b/src/commands/init-mode-picker.ts
index 6c3f7cd939..8c8ceb3740 100644
--- a/src/commands/init-mode-picker.ts
+++ b/src/commands/init-mode-picker.ts
@@ -132,8 +132,10 @@ Three named modes. Cost depends on BOTH the mode AND your downstream model
The "cost" isn't gbrain itself — it's the downstream agent's input cost
reading the retrieved chunks back into its context window. gbrain's own
-overhead is rounding-error (semantic cache is free; tokenmax adds ~$1.50
-per 1K queries for the Haiku expansion call).
+overhead is rounding-error (semantic result caching is temporarily disabled,
+so budget for fresh retrieval on every query; gbrain query adds ~$1.50 per 1K
+queries for the Haiku expansion call in every mode — --no-expand skips it;
+gbrain search never expands).
Per-query cost @ 10K queries/mo (full search payload, no cache savings):
@@ -162,6 +164,9 @@ discount on top of these numbers (cache hits skip downstream entirely).
Best for: Opus/frontier models, max retrieval quality,
low-volume high-stakes work.
+("no LLM expansion" governs gbrain search + callers that leave expansion
+unset; gbrain query expands in every mode unless you pass --no-expand.)
+
You can change this any time with: gbrain config set search.mode <mode>
Per-knob tuning + recommendation engine ships at: gbrain search tune
`;
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index 046731ae03..3094cde477 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -2196,7 +2196,8 @@ export async function registerBuiltinHandlers(
const autoEmbed = job.data.auto_embed_backfill !== false;
let embedJobId: number | null = null;
let embedSkipReason: string | null = null;
- if (autoEmbed && sourceId && result.status !== 'up_to_date' && result.status !== 'dry_run') {
+ const { syncProducedEmbeddableContent } = await import('../core/sync-embed-backfill.ts');
+ if (autoEmbed && sourceId && result.status !== 'up_to_date' && result.status !== 'dry_run' && syncProducedEmbeddableContent(result)) {
try {
const { isFederatedV2Enabled } = await import('../core/feature-flags.ts');
if (await isFederatedV2Enabled(engine)) {
@@ -2224,6 +2225,9 @@ export async function registerBuiltinHandlers(
embedSkipReason = 'no_source_id';
} else if (!autoEmbed) {
embedSkipReason = 'auto_embed_disabled';
+ } else if (result.status !== 'up_to_date' && result.status !== 'dry_run') {
+ // #4786 x #2139: a sweep-only `synced` run wrote nothing to embed — a backfill here would only arm the cooldown.
+ embedSkipReason = 'no_new_content';
}
return { ...result, embed_job_id: embedJobId, embed_skip_reason: embedSkipReason };
@@ -2460,7 +2464,6 @@ export async function registerBuiltinHandlers(
const r = await extractStaleFromDB(engine, {
dryRun: !!job.data.dryRun,
jsonMode: false,
- includeFrontmatter: false,
sourceIdFilter,
catchUp: false,
});
diff --git a/src/commands/maintain.ts b/src/commands/maintain.ts
index 2442b48443..96b8b84fb5 100644
--- a/src/commands/maintain.ts
+++ b/src/commands/maintain.ts
@@ -78,6 +78,7 @@ async function runStaleExtraction(
engine: BrainEngine,
beforeHealth: BrainHealth,
dryRun: boolean,
+ json: boolean,
): Promise<MaintenanceAction> {
if (beforeHealth.stale_pages <= 0) {
return { name: 'extract_stale', status: 'ok', message: 'No stale pages.' };
@@ -92,10 +93,12 @@ async function runStaleExtraction(
};
}
+ // maintain owns the report: in --json mode the helper's human summary must
+ // stay off stdout or the JSON document stops parsing.
const result = await extractStaleFromDB(engine, {
dryRun: false,
jsonMode: false,
- includeFrontmatter: false,
+ quiet: json,
catchUp: false,
});
@@ -183,7 +186,7 @@ Not auto-applied:
const beforeDoctor = await buildDoctorReport(engine);
const actions: MaintenanceAction[] = [];
- actions.push(await runStaleExtraction(engine, beforeHealth, opts.dryRun));
+ actions.push(await runStaleExtraction(engine, beforeHealth, opts.dryRun, opts.json));
actions.push(...await runCycleFreshnessMaintenance(engine, beforeDoctor, opts.dryRun));
const afterHealth = await engine.getHealth();
diff --git a/src/commands/onboard.ts b/src/commands/onboard.ts
index 8a93dbe0f8..58b2c5cdc8 100644
--- a/src/commands/onboard.ts
+++ b/src/commands/onboard.ts
@@ -251,7 +251,7 @@ async function renderPackUpgradeExplain(
` Page-to-link: ${result.per_phase.page_to_link.would_convert} edges across ${result.per_phase.page_to_link.rules} rules\n` +
` Page-to-alias: ${result.per_phase.page_to_alias.would_alias} aliases across ${result.per_phase.page_to_alias.rules} rules\n` +
`\nRun the migration with:\n` +
- ` gbrain jobs submit unify-types --allow-protected --params '${JSON.stringify({ target_pack: targetPack, apply: true })}'\n`,
+ ` gbrain jobs submit unify-types --params '${JSON.stringify({ target_pack: targetPack, apply: true })}'\n`,
);
if (result.warnings.length > 0) {
process.stdout.write(`\nWarnings:\n`);
diff --git a/src/commands/pages.ts b/src/commands/pages.ts
index c8642a79bb..ca2fe24ee9 100644
--- a/src/commands/pages.ts
+++ b/src/commands/pages.ts
@@ -67,7 +67,8 @@ Subcommands:
Mirror of the autopilot purge phase.
Notes:
- Soft-delete a page via the MCP \`delete_page\` op. Restore via \`restore_page\`.
+ Soft-delete a page via the MCP \`delete_page\` op (also removes its markdown file
+ from the source working tree). Restore via \`restore_page\` (re-creates the file).
This command is the manual operator escape hatch — the autopilot cycle's
purge phase already calls the same library function on every run.
`);
diff --git a/src/commands/reindex-code.ts b/src/commands/reindex-code.ts
index 46dd739817..74a1d5673e 100644
--- a/src/commands/reindex-code.ts
+++ b/src/commands/reindex-code.ts
@@ -481,7 +481,7 @@ export async function runReindexCodeCli(engine: BrainEngine, args: string[]): Pr
}
const n = v ? parseFloat(v) : NaN;
if (!Number.isFinite(n) || n <= 0) {
- console.error(`gbrain reindex --code: ${flag} requires a positive number in USD, or off/unlimited (got ${v ?? '(missing)'})`);
+ console.error(`gbrain reindex-code: ${flag} requires a positive number in USD, or off/unlimited (got ${v ?? '(missing)'})`);
process.exit(2);
}
maxCostUsd = n;
diff --git a/src/commands/reindex-search-vector.ts b/src/commands/reindex-search-vector.ts
index bd9e33c80e..bba4f1e2a6 100644
--- a/src/commands/reindex-search-vector.ts
+++ b/src/commands/reindex-search-vector.ts
@@ -25,12 +25,27 @@
* through the shared reporter (stderr; stdout stays clean for --json).
*
* Cost: trigger recreate is sub-millisecond. Backfill is one tsvector
- * rebuild per page + per chunk. On a 20K-page brain with 80K chunks,
- * expect ~5-15s depending on Postgres CPU and content size.
+ * rebuild per page + per chunk, ~1-5s per 5000-row batch depending on
+ * engine CPU and content size (PGLite is the slow end) — budget minutes,
+ * not seconds, for a brain with 100K+ chunks.
+ *
+ * Interrupted runs (#4795): the two CREATE OR REPLACE statements autocommit,
+ * so a kill/crash mid-backfill would otherwise leave new writes tokenized in
+ * the new language and un-backfilled rows in the old one, silently splitting
+ * keyword search. The command therefore stamps `fts.reindex_in_progress`
+ * (= target language) in the config table BEFORE the DDL and clears it only
+ * after both backfills return; `gbrain doctor` fails (`fts_reindex_incomplete`)
+ * while it is set. Each batch persists its keyset cursor under the shared
+ * `backfill.<name>.last_id` convention, so re-running with the same language
+ * resumes where the killed run stopped (a different language starts over).
+ * Deliberately NOT one engine.transaction(): on Postgres that would hold every
+ * page/chunk row lock for the whole run (the batching exists to avoid that),
+ * and a hang inside it would bank zero progress.
*/
import type { BrainEngine } from '../core/engine.ts';
-import { getFtsLanguage } from '../core/fts-language.ts';
+import { getFtsLanguage, FTS_REINDEX_MARKER_KEY } from '../core/fts-language.ts';
+import { checkpointKey } from '../core/backfill-base.ts';
import { createInterface } from 'readline';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
@@ -58,11 +73,15 @@ interface CountRow {
/** Rows per backfill UPDATE. Keyset-batched so one statement never locks the whole table. */
export const BACKFILL_BATCH_SIZE = 5000;
+/** Checkpoint names (→ `backfill.<name>.last_id`), one per backfilled table. */
+const CHECKPOINT_NAME = { pages: 'fts_pages', content_chunks: 'fts_content_chunks' } as const;
+
/**
* Keyset-batched UPDATE: applies `setClause` to `table` rows where
* search_vector IS NOT NULL, BACKFILL_BATCH_SIZE ids at a time, ticking
* the shared progress reporter after each batch. Terminates when a batch
- * returns fewer rows than the batch size (or none).
+ * returns fewer rows than the batch size (or none). The cursor is persisted
+ * after every batch so a killed run loses at most one batch on resume.
*/
async function batchedBackfill(
engine: BrainEngine,
@@ -70,7 +89,9 @@ async function batchedBackfill(
setClause: string,
tick: (n: number) => void
): Promise<void> {
- let cursor = 0;
+ const key = checkpointKey(CHECKPOINT_NAME[table]);
+ const saved = Number(await engine.getConfig(key));
+ let cursor = Number.isFinite(saved) && saved > 0 ? saved : 0;
for (;;) {
const rows = await engine.executeRaw<{ id: number }>(`
UPDATE ${table} SET ${setClause}
@@ -85,6 +106,7 @@ async function batchedBackfill(
if (rows.length === 0) break;
tick(rows.length);
cursor = rows.reduce((m, r) => Math.max(m, Number(r.id)), cursor);
+ await engine.setConfig(key, String(cursor));
if (rows.length < BACKFILL_BATCH_SIZE) break;
}
}
@@ -221,7 +243,32 @@ export async function runReindexSearchVector(
$fn$ LANGUAGE plpgsql;
`;
- await engine.executeRaw(recreatePagesFn);
+ // #4795: marker first (see the docblock). A prior run interrupted on the
+ // SAME language resumes from its checkpoints; any other state starts over.
+ const inProgress = await engine.getConfig(FTS_REINDEX_MARKER_KEY);
+ if (inProgress === lang) {
+ console.error(`Resuming interrupted reindex to language='${lang}' from the saved checkpoint.`);
+ } else {
+ await engine.unsetConfig(checkpointKey(CHECKPOINT_NAME.pages));
+ await engine.unsetConfig(checkpointKey(CHECKPOINT_NAME.content_chunks));
+ }
+ await engine.setConfig(FTS_REINDEX_MARKER_KEY, lang);
+
+ try {
+ await engine.executeRaw(recreatePagesFn);
+ } catch (err) {
+ // Nothing landed (e.g. no CREATE FUNCTION privilege): put the marker back
+ // the way THIS run found it. Absent before → clear it, so doctor doesn't
+ // report a permanent fts_reindex_incomplete whose suggested fix re-fails.
+ // Set before (a prior run was interrupted) → the index is still split, so
+ // restore the prior value; clearing it would hide a real incomplete
+ // reindex. Once the pages trigger has flipped, the marker MUST stay.
+ await (inProgress === null
+ ? engine.unsetConfig(FTS_REINDEX_MARKER_KEY)
+ : engine.setConfig(FTS_REINDEX_MARKER_KEY, inProgress)
+ ).catch(() => {});
+ throw err;
+ }
await engine.executeRaw(recreateChunksFn);
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
@@ -245,6 +292,11 @@ export async function runReindexSearchVector(
);
progress.finish();
+ // 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));
+ await engine.unsetConfig(FTS_REINDEX_MARKER_KEY);
+
const result: ReindexSearchVectorResult = {
status: 'ok',
language: lang,
diff --git a/src/commands/schema.ts b/src/commands/schema.ts
index 11ffd61e9e..84c7c74a4c 100644
--- a/src/commands/schema.ts
+++ b/src/commands/schema.ts
@@ -51,7 +51,8 @@ import {
import type { SchemaPackManifest, PackPrimitive } from '../core/schema-pack/manifest-v1.ts';
import { PACK_PRIMITIVES } from '../core/schema-pack/manifest-v1.ts';
import { bundledPackPath } from '../core/schema-pack/bundled-assets.ts';
-import { gbrainPath, loadConfig, configPath, toEngineConfig } from '../core/config.ts';
+import { gbrainPath, loadConfig, configPath, toEngineConfig, type GBrainConfig } from '../core/config.ts';
+import { readDbSchemaPack } from '../core/schema-pack/best-effort.ts';
export async function runSchema(args: string[]): Promise<void> {
const sub = args[0];
@@ -167,27 +168,28 @@ Resolution chain (7-tier, tier 1 trust-gated):
`);
}
+/**
+ * DB-plane `schema_pack` (tier 4) for the read-only inspection verbs
+ * (active / show / graph / lint / explain), so they all report the SAME pack
+ * the engine queries with on brains whose active pack was flipped via
+ * `gbrain config set schema_pack` / unify-types (#3792, #4653). Best-effort
+ * AND gated on an actually-configured brain (cfg non-null): an unconfigured
+ * home has no DB plane to consult, and connecting would cold-CREATE a PGLite
+ * data dir as a side effect of a read-only command. No connectable DB →
+ * undefined, so file/env resolution stands.
+ */
+async function readDbSchemaPackConfig(cfg: GBrainConfig | null): Promise<string | undefined> {
+ if (!cfg) return undefined;
+ try {
+ return await withConnectedEngine((engine) => readDbSchemaPack(engine));
+ } catch {
+ return undefined;
+ }
+}
+
async function runActive(_args: string[]): Promise<void> {
const cfg = loadConfig();
- // #3792: consult the DB-plane schema_pack (tier 4) so `gbrain schema
- // active` reports the SAME pack the engine queries with on brains whose
- // active pack was flipped via `gbrain config set schema_pack` /
- // unify-types. Best-effort AND gated on an actually-configured brain
- // (cfg non-null): an unconfigured home has no DB plane to consult, and
- // connecting would cold-CREATE a PGLite data dir as a side effect of a
- // read-only inspection command.
- let dbConfig: string | undefined;
- if (cfg) {
- try {
- dbConfig = await withConnectedEngine(async (engine) => {
- try {
- return (await engine.getConfig('schema_pack')) ?? undefined;
- } catch {
- return undefined;
- }
- });
- } catch { /* no connectable DB — file/env resolution stands */ }
- }
+ const dbConfig = await readDbSchemaPackConfig(cfg);
const resolution = resolveActivePackNameOnly({ cfg, remote: false, dbConfig });
const pack = await loadActivePack({ cfg, remote: false, dbConfig });
console.log(`Active pack: ${pack.manifest.name} v${pack.manifest.version}`);
@@ -248,7 +250,8 @@ async function runShow(args: string[]): Promise<void> {
}
manifest = loadPackFromFile(path);
} else {
- const pack = await loadActivePack({ cfg: loadConfig(), remote: false });
+ const cfg = loadConfig();
+ const pack = await loadActivePack({ cfg, remote: false, dbConfig: await readDbSchemaPackConfig(cfg) });
manifest = pack.manifest;
}
if (asFilingRules) {
@@ -704,7 +707,7 @@ async function runDiffCmd(args: string[]): Promise<void> {
async function runGraphCmd(args: string[]): Promise<void> {
const { json } = parseFlags(args);
const cfg = loadConfig();
- const pack = await loadActivePack({ cfg, remote: false });
+ const pack = await loadActivePack({ cfg, remote: false, dbConfig: await readDbSchemaPackConfig(cfg) });
if (json) {
console.log(JSON.stringify({
schema_version: 1,
@@ -727,42 +730,46 @@ async function runLintCmd(args: string[]): Promise<void> {
const withDb = args.includes('--with-db');
const name = positional[0];
const cfg = loadConfig();
- let pack: SchemaPackManifest | null;
- if (name) {
- const p = packPathByName(name);
- let raw: SchemaPackManifest | null;
- try { raw = p ? loadPackFromFile(p) : null; } catch { raw = null; }
- if (raw) {
- // #4501: lint the MERGED manifest (extends chain + borrow_from
- // resolved), matching the no-name branch's loadActivePack path —
- // a child pack referencing inherited parent types must not fail
- // raw-manifest lint. Fall back to the raw child (with a stderr
- // warning) when the chain can't be resolved, e.g. missing parent.
- try {
- pack = (await loadResolvedPackByName(name)).manifest;
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- console.error(`warn: could not resolve extends chain for pack \`${name}\` (${msg}); linting raw manifest only`);
- pack = raw;
- }
- } else {
- pack = null;
- }
- } else {
- pack = (await loadActivePack({ cfg, remote: false })).manifest;
- }
- if (!pack) {
- console.error(`Pack not found: ${name}`);
- process.exit(1);
- }
// v0.40.6.0 Phase 5: swap basic 2-rule check for the rich 11-rule lint
// suite from Phase 1.5. File-plane rules run by default; --with-db
// opts into extractable_empty_corpus + mutation_count_anomaly which
// need an engine connection.
const { runAllLintRules } = await import('../core/schema-pack/lint-rules.ts');
- const report = withDb
- ? await withConnectedEngine(async (engine) => runAllLintRules(pack!, { engine }))
- : await runAllLintRules(pack);
+ // Resolve + lint in one step so --with-db reads the tier-4 DB-plane
+ // schema_pack (#4653) on the SAME connection the DB-backed rules use.
+ const lint = async (engine?: import('../core/engine.ts').BrainEngine) => {
+ let pack: SchemaPackManifest | null;
+ if (name) {
+ const p = packPathByName(name);
+ let raw: SchemaPackManifest | null;
+ try { raw = p ? loadPackFromFile(p) : null; } catch { raw = null; }
+ if (raw) {
+ // #4501: lint the MERGED manifest (extends chain + borrow_from
+ // resolved), matching the no-name branch's loadActivePack path —
+ // a child pack referencing inherited parent types must not fail
+ // raw-manifest lint. Fall back to the raw child (with a stderr
+ // warning) when the chain can't be resolved, e.g. missing parent.
+ try {
+ pack = (await loadResolvedPackByName(name)).manifest;
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ console.error(`warn: could not resolve extends chain for pack \`${name}\` (${msg}); linting raw manifest only`);
+ pack = raw;
+ }
+ } else {
+ pack = null;
+ }
+ } else {
+ const dbConfig = engine ? await readDbSchemaPack(engine) : await readDbSchemaPackConfig(cfg);
+ pack = (await loadActivePack({ cfg, remote: false, dbConfig })).manifest;
+ }
+ if (!pack) {
+ console.error(`Pack not found: ${name}`);
+ process.exit(1);
+ }
+ return { pack, report: await runAllLintRules(pack, engine ? { engine } : undefined) };
+ };
+ const { pack, report } = withDb ? await withConnectedEngine(lint) : await lint();
if (json) {
console.log(JSON.stringify({ schema_version: 1, pack: pack.name, ...report }, null, 2));
if (!report.ok) process.exit(1);
@@ -792,7 +799,7 @@ async function runExplainCmd(args: string[]): Promise<void> {
process.exit(2);
}
const cfg = loadConfig();
- const pack = await loadActivePack({ cfg, remote: false });
+ const pack = await loadActivePack({ cfg, remote: false, dbConfig: await readDbSchemaPackConfig(cfg) });
const found = pack.manifest.page_types.find((t) => t.name === typeName);
if (!found) {
console.error(`Type \`${typeName}\` not in active pack \`${pack.manifest.name}\`.`);
diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.ts
index e86faeac15..2a02b43bcb 100644
--- a/src/commands/serve-http.ts
+++ b/src/commands/serve-http.ts
@@ -212,6 +212,57 @@ type HttpServerLifecycle = EventSubscriber & {
};
type SignalSource = EventSubscriber;
type CleanupRegistrar = typeof registerCleanup;
+/** How long `server.close()` may hold shutdown before the lifecycle gives up on it. */
+const CLOSE_TIMEOUT_MS = 5_000;
+
+/** Live-connection bookkeeping for `waitForHttpServerLifecycle`'s teardown. */
+export interface SocketTracker {
+ /** Sockets currently tracked (live or not yet observed as gone). */
+ size(): number;
+ /** Sever every tracked connection so `server.close()` cannot block on them. */
+ destroyAll(): void;
+}
+
+/**
+ * Track accepted connections so shutdown can sever them.
+ *
+ * `close()` stops the listener and then waits for every open connection to
+ * drain. One attached admin-SSE EventSource — or any keep-alive socket —
+ * holds it open forever, so shutdown has to sever them itself. Bun 1.3.x
+ * ships `closeAllConnections()`/`closeIdleConnections()` as no-op stubs, so
+ * tracking is the only portable teardown.
+ */
+export function trackServerSockets(server: Pick<HttpServerLifecycle, 'on'>): SocketTracker {
+ // Hold sockets WEAKLY. Bun's node:http never emits 'close' (nor 'end'/'error')
+ // on server-side sockets and keeps reporting them open after the peer is
+ // gone, so no event or state flag can evict a dead connection — a strong Set
+ // grew by one socket per request forever (each health probe is a fresh TCP
+ // connection). A dead socket does become unreachable once the runtime drops
+ // it, so a WeakRef lets it go; a live one stays reachable from the server
+ // and keeps being tracked. Node does emit 'close' — honor it so the
+ // bookkeeping stays exact there, and prune collected refs as we go so the
+ // ref set itself stays bounded by live connections.
+ const refs = new Set<WeakRef<TrackedSocket>>();
+ const live = (): TrackedSocket[] => {
+ const out: TrackedSocket[] = [];
+ for (const ref of refs) {
+ const socket = ref.deref();
+ if (socket === undefined) refs.delete(ref);
+ else out.push(socket);
+ }
+ return out;
+ };
+ server.on('connection', (socket: TrackedSocket) => {
+ live();
+ const ref = new WeakRef(socket);
+ refs.add(ref);
+ socket.once('close', () => refs.delete(ref));
+ });
+ return {
+ size: () => live().length,
+ destroyAll: () => { for (const socket of live()) socket.destroy(); },
+ };
+}
/**
* Keep the HTTP server strongly referenced and make the daemon lifetime
@@ -224,21 +275,17 @@ export function waitForHttpServerLifecycle(
options: {
signals?: SignalSource;
register?: CleanupRegistrar;
+ /** Upper bound on how long `close()` may keep shutdown waiting. */
+ closeTimeoutMs?: number;
+ log?: (msg: string) => void;
} = {},
): Promise<void> {
const signals = options.signals ?? process;
const register = options.register ?? registerCleanup;
+ const closeTimeoutMs = options.closeTimeoutMs ?? CLOSE_TIMEOUT_MS;
+ const log = options.log ?? ((msg: string) => console.error(msg));
- // `close()` stops the listener and then waits for every open connection to
- // drain. One attached admin-SSE EventSource — or any keep-alive socket —
- // holds it open forever, so shutdown has to sever them itself. Bun 1.3.x
- // ships `closeAllConnections()`/`closeIdleConnections()` as no-op stubs, so
- // tracking is the only portable teardown.
- const sockets = new Set<TrackedSocket>();
- server.on('connection', (socket: TrackedSocket) => {
- sockets.add(socket);
- socket.once('close', () => sockets.delete(socket));
- });
+ const sockets = trackServerSockets(server);
return new Promise<void>((resolve, reject) => {
let settled = false;
@@ -251,13 +298,33 @@ export function waitForHttpServerLifecycle(
closeResolve();
return;
}
+ // Backstop for what the tracker cannot reach: sockets are held weakly,
+ // so an idle keep-alive wrapper the runtime already collected leaves a
+ // native handle that close() still waits on. Bound the wait instead
+ // of hanging the daemon; process exit releases the handle.
+ // The process still exits: the serve lane's own finishHttpServe
+ // (serve.ts) disconnects the engine and calls process.exit once the
+ // lifecycle resolves, so a leaked handle cannot outlive teardown.
+ let timedOut = false;
+ const deadline = setTimeout(() => {
+ timedOut = true;
+ log(`GBrain HTTP server: close() still waiting after ${closeTimeoutMs}ms — shutting down anyway`);
+ closeResolve();
+ }, closeTimeoutMs);
+ deadline.unref?.();
server.close((error?: Error) => {
+ clearTimeout(deadline);
+ if (timedOut) {
+ // Settled already — a late failure must be seen, not swallowed.
+ if (error) log(`GBrain HTTP server: close() failed after the deadline: ${error.message}`);
+ return;
+ }
if (error) closeReject(error);
else closeResolve();
});
// After close() so the listener stops accepting first, then in-flight
// connections are severed rather than waited on.
- for (const socket of sockets) socket.destroy();
+ sockets.destroyAll();
});
return closePromise;
};
@@ -277,7 +344,9 @@ export function waitForHttpServerLifecycle(
const onClose = () => finish();
const onError = (error: Error) => finish(error);
const onSigint = () => {
- void closeServer().catch(onError);
+ // A close() that reports done — or that the deadline gave up on — ends
+ // the lifecycle even when the server never emits 'close'.
+ void closeServer().then(() => finish(), onError);
};
server.once('close', onClose);
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 2195e17c96..1b9a6eed95 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -1,7 +1,7 @@
import { spawnSync } from 'node:child_process';
import type { BrainEngine } from '../core/engine.ts';
import { isEngineDegraded as isEngineDegradedForServe } from '../core/degraded-marker.ts';
-import { startMcpServer, stdioRpcsInFlightCount } from '../mcp/server.ts';
+import { startMcpServer, stdioRpcsInFlightCount, resolveMcpStdioSourceScope } from '../mcp/server.ts';
import { VERB_NAMES } from '../core/verbs.ts';
import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';
import {
@@ -665,8 +665,15 @@ function installStdioLifecycle(
if (runner.isDelegatedSyncRunning()) return;
// Lazy import keeps the sweep core off the serve boot path.
const { runMaintenanceSweep } = await import('../core/sweep.ts');
+ // #4679: same source ladder as stdio dispatch and the startup sweep
+ // (GBRAIN_SOURCE > .gbrain-source dotfile > local_path > sources.default
+ // > …). Pre-fix `GBRAIN_SOURCE || 'default'` swept the wrong source on
+ // dotfile/local_path-scoped serves, so in-session MCP writes never got
+ // their links reconciled until a restart. Never throws (falls back to
+ // 'default'); degraded engines short-circuit without a DB touch.
+ const { sourceId } = await resolveMcpStdioSourceScope(e);
await runMaintenanceSweep(e, {
- sourceId: process.env.GBRAIN_SOURCE || 'default',
+ sourceId,
budgetMs: IDLE_SWEEP_BUDGET_MS,
});
// Deferred-embed drain: delegated syncs always run noEmbed (the #2139
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 0939d30470..a69253a440 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -99,6 +99,7 @@ import {
resolveSingleSyncEmbedPlan,
resolveSyncAllEmbedPlan,
resolveSyncEmbedBackfill,
+ syncProducedEmbeddableContent,
type SyncEmbedBackfillOutcome,
} from '../core/sync-embed-backfill.ts';
import {
@@ -125,6 +126,7 @@ import {
resolveSlugRootMode,
type SlugRootMode,
} from '../core/sync-anchor.ts';
+import { isSyncDisabledConfig } from '../core/sync-policy.ts';
import {
SyncLockBusyError,
formatLockBusyMessage,
@@ -396,6 +398,11 @@ export interface SyncOpts {
* fallback aren't covered). Unlike `exclude`, this has to reach the
* collection step itself — a pruned path is never collected in the first
* place, so there's nothing for a post-collection filter to add back.
+ *
+ * Unioned with the persisted `sync.include_hidden` config key (same dialect
+ * and trailing-`/` normalization as `sync.exclude`), so callers that never
+ * touch the CLI — `sync --all`, autopilot, the dream cycle — inherit the
+ * waiver. Union, not override; unset admits nothing.
*/
includeHidden?: string[];
/**
@@ -1794,6 +1801,23 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
}
} catch { /* config unreadable — never break a sync over the scope read */ }
+ // #4901: the WAIVER's persisted twin, read exactly like `sync.exclude` above
+ // (same dialect, trailing-slash normalization, union, best-effort, position).
+ // `--include-hidden` is refused under `--all` and unavailable to autopilot /
+ // the dream cycle, so this key is the only way the unattended paths get it.
+ // An unset key admits nothing — the dot-directory default does not move.
+ try {
+ const storedHidden = await engine.getConfig('sync.include_hidden');
+ const hiddenPatterns = (storedHidden ?? '')
+ .split(/[\n,]/)
+ .map(p => p.trim())
+ .filter(Boolean)
+ .map(p => (p.endsWith('/') ? `${p}**` : p));
+ if (hiddenPatterns.length > 0) {
+ opts = { ...opts, includeHidden: [...new Set([...(opts.includeHidden ?? []), ...hiddenPatterns])] };
+ }
+ } catch { /* config unreadable — never break a sync over the scope read */ }
+
// #1970: bookmark reachability. The ONLY thing that should force a full
// reconcile is a truly-absent object; a present-but-non-ancestor bookmark
// (history rewrite: force-push, master→main consolidation, squash) is still
@@ -2272,6 +2296,9 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
// unsyncable cleanup in source A doesn't accidentally sweep same-slug
// pages in sources B/C/D.
const pageOpts = opts.sourceId ? { sourceId: opts.sourceId } : undefined;
+ // #4786: pages this loop retires count as `deleted` in the result (only rows
+ // that actually transitioned), so a sweep-only run never reports up_to_date.
+ let swept = 0;
for (const path of unsyncableModified) {
// v0.41.13 #1433: never delete on metafile classification.
// #2404 hardening: same for 'pruned-dir' — a page under a pruned
@@ -2304,7 +2331,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
// Scope falls back to DEFAULT_SOURCE_ID to preserve deletePage's
// old 'default' fallback; softDeletePages requires an explicit
// sourceId. The purge phase owns the eventual hard delete.
- await engine.softDeletePages([slug], { sourceId: opts.sourceId ?? DEFAULT_SOURCE_ID });
+ swept += (await engine.softDeletePages([slug], { sourceId: opts.sourceId ?? DEFAULT_SOURCE_ID })).length;
slog(` Soft-deleted un-syncable page (recoverable 72h): ${slug}`);
}
}
@@ -2316,8 +2343,9 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
// plus zero imports must not produce a clean `up_to_date` (and must not
// advance the anchor past commits this run never looked at remotely).
// Reached when local-only commits landed with no syncable content while
- // the pull kept failing. Nothing is written; the next sync re-diffs the
- // same trivial range and retries the pull.
+ // the pull kept failing. Nothing is imported (the #4786 sweep above may
+ // have soft-deleted pages — report it); the next sync re-diffs the same
+ // trivial range and retries the pull.
if (pullFailed) {
serr(
`[sync] git pull failed and no syncable changes imported — reporting partial ` +
@@ -2329,7 +2357,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
filesImported: 0,
pagesAffected: [],
chunksCreated: 0,
- added: 0, modified: 0, deleted: 0, renamed: 0,
+ added: 0, modified: 0, deleted: swept, renamed: 0,
reason: 'pull_failed',
});
}
@@ -2356,10 +2384,10 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
// sweep orphaned `<rename:…>` sentinels here too.
await sweepOrphanedRenameSentinels(engine, opts.sourceId ?? DEFAULT_SOURCE_ID);
return {
- status: 'up_to_date',
+ status: swept > 0 ? 'synced' : 'up_to_date',
fromCommit: lastCommit,
toCommit: pin,
- added: 0, modified: 0, deleted: 0, renamed: 0,
+ added: 0, modified: 0, deleted: swept, renamed: 0,
chunksCreated: 0,
embedded: 0,
pagesAffected: [],
@@ -2510,7 +2538,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
chunksCreated,
added: filtered.added.length,
modified: filtered.modified.length,
- deleted: filtered.deleted.length,
+ deleted: filtered.deleted.length + swept,
renamed: filtered.renamed.length,
reason: checkpointDead ? 'checkpoint_unavailable' : reason,
bankedFiles,
@@ -3742,7 +3770,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
toCommit: pin,
added: filtered.added.length,
modified: filtered.modified.length,
- deleted: filtered.deleted.length,
+ deleted: filtered.deleted.length + swept,
renamed: filtered.renamed.length,
chunksCreated,
embedded: 0,
@@ -3873,13 +3901,13 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
}
if (!opts.noExtract && totalChanges <= 100 && pagesAffected.length > 0) {
try {
- const { extractLinksForSlugs, extractTimelineForSlugs, stampExtracted } = await import('./extract.ts');
+ const { extractLinksForSlugs, extractTimelineForSlugs, stampExtracted, slugsSafeToStamp } = await import('./extract.ts');
// #774: pages' source_path is git-root-relative, so extract resolves
// files from gitContextRoot (== repoPath realpath when unscoped).
- const linksCreated = await extractLinksForSlugs(engine, gitContextRoot, pagesAffected, extractOpts);
- const timelineCreated = await extractTimelineForSlugs(engine, gitContextRoot, pagesAffected, extractOpts);
- if (linksCreated > 0 || timelineCreated > 0) {
- slog(` Extracted: ${linksCreated} links, ${timelineCreated} timeline entries`);
+ const linksResult = await extractLinksForSlugs(engine, gitContextRoot, pagesAffected, extractOpts);
+ const timelineResult = await extractTimelineForSlugs(engine, gitContextRoot, pagesAffected, extractOpts);
+ if (linksResult.created > 0 || timelineResult.created > 0) {
+ slog(` Extracted: ${linksResult.created} links, ${timelineResult.created} timeline entries`);
}
// v0.42.7 (#1696, CDX-6): stamp the links_extracted_at watermark for the
// pages we just extracted, AFTER the import set their updated_at, so
@@ -3887,9 +3915,12 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
// Source-correct via opts.sourceId. Stamp at the CALL SITE (not inside
// extractLinksForSlugs) so we use the per-source sourceId the sync owns.
// Best-effort: a stamp miss just means extract --stale re-sweeps later.
+ // Only the slugs both hooks actually read — a page the extractor
+ // skipped must stay stale so the sweep still owes it.
await stampExtracted(
engine,
- pagesAffected.map((slug) => ({ slug, source_id: opts.sourceId ?? 'default' })),
+ slugsSafeToStamp(linksResult, timelineResult)
+ .map((slug) => ({ slug, source_id: opts.sourceId ?? 'default' })),
);
} catch { /* extraction is best-effort */ }
}
@@ -3991,7 +4022,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
toCommit: pin,
added: filtered.added.length,
modified: filtered.modified.length,
- deleted: filtered.deleted.length,
+ deleted: filtered.deleted.length + swept,
renamed: filtered.renamed.length,
chunksCreated,
embedded,
@@ -4470,10 +4501,11 @@ function manageGitignoreAtGitRoot(path: string, engineKind?: 'pglite' | 'postgre
}
export async function runSync(engine: BrainEngine, args: string[]) {
- // #4888: under --json, stdout is reserved for JSON lines (the envelope and
- // any JSON status lines); every slog() human line from performSync and its
- // callees routes to stderr instead. serr/progress are stderr already, and
- // the console.log(JSON.stringify(..)) sites are untouched by the wrap.
+ // #4888: under --json, stdout is reserved for the ONE JSON envelope (#4684:
+ // the cost-gate status object rides inside it as `cost_gate`); every slog()
+ // human line from performSync and its callees routes to stderr instead.
+ // serr/progress are stderr already, and the envelope's own
+ // console.log(JSON.stringify(..)) site is untouched by the wrap.
return args.includes('--json')
? withHumanLogsToStderr(() => runSyncInner(engine, args))
: runSyncInner(engine, args);
@@ -4525,7 +4557,10 @@ Options:
waivable) for paths matching this glob (repeatable).
Does not reach a non-git directory's FS-walk import
fallback; every git-tracked source (the normal case)
- is covered. Cannot combine with --all.
+ is covered. Cannot combine with --all; persist it as
+ the sync.include_hidden config key (gbrain config set
+ sync.include_hidden '<globs>') so --all, autopilot and
+ the dream cycle honor it.
--include-gitignored Include otherwise-syncable files matched by .gitignore.
Forces a full filesystem walk so periodic syncs see
ignored untracked content.
@@ -4755,7 +4790,9 @@ See also:
console.error(
`--src-subpath/--exclude/--include-hidden scope a single sync invocation; they cannot be combined with --all. ` +
`For --all runs, register the subdirectory as the source's local_path instead ` +
- `(gbrain sources add <id> --path <repo>/<subdir>).`,
+ `(gbrain sources add <id> --path <repo>/<subdir>), persist exclusions with ` +
+ `\`gbrain config set sync.exclude <globs>\`, and persist the dot-directory waiver with ` +
+ `\`gbrain config set sync.include_hidden <globs>\` so --all, autopilot and the dream cycle honor it.`,
);
process.exit(1);
}
@@ -4946,10 +4983,7 @@ See also:
// performSync get the [<source-id>] prefix under parallel mode (D6)
// - stable JSON envelope {schema_version:1, sources, ...} when --json
// v0.41.31: v2Enabled resolved once above (cost gate). Reused here.
- const activeSources = sources.filter((s) => {
- const cfg = (s.config || {}) as { syncEnabled?: boolean };
- return cfg.syncEnabled !== false;
- });
+ const activeSources = sources.filter((s) => !isSyncDisabledConfig(s.config));
const disabledCount = sources.length - activeSources.length;
const humanSink: NodeJS.WriteStream = jsonOut ? process.stderr : process.stdout;
const writeHuman = (line: string) => humanSink.write(line + '\n');
@@ -5112,7 +5146,7 @@ See also:
!dryRun &&
result.status !== 'dry_run' &&
result.status !== 'up_to_date' &&
- result.status !== 'partial'
+ result.status !== 'partial' && syncProducedEmbeddableContent(result)
) {
try {
const outcome = await resolveSyncEmbedBackfill(engine, src.id, {
@@ -5262,6 +5296,8 @@ See also:
ok_count: okCount,
error_count: errCount,
skipped_count: perSourceResults.filter((r) => r.status === 'skipped_missing_path').length,
+ // #4684: the cost-gate status object rides inside the ONE envelope.
+ ...(embedPlan.costGate ? { cost_gate: embedPlan.costGate } : {}),
}));
}
@@ -5316,6 +5352,7 @@ See also:
// inline spend into informed inline-or-deferred spend.
let singleSourceAutoDefer = false;
let singleSourceNoWorkerSurface = false;
+ let singleCostGate: Record<string, unknown> | undefined;
if (!noEmbed && !dryRun && !watch) {
const gateRows = await engine.executeRaw<{ local_path: string | null; config: Record<string, unknown>; last_commit: string | null; chunker_version: string | null }>(
`SELECT local_path, config, last_commit, chunker_version FROM sources WHERE id = $1`,
@@ -5333,6 +5370,7 @@ See also:
jsonOut, yesFlag, full, includeGitignored, noAutoEmbed,
});
singleSourceNoWorkerSurface = gate.workerSurface.status === 'no_worker_surface';
+ singleCostGate = gate.costGate;
if (gate.stop) return;
if (gate.autoDeferEmbeds) {
opts.noEmbed = true;
@@ -5416,7 +5454,7 @@ See also:
)) &&
result.status !== 'dry_run' &&
result.status !== 'up_to_date' &&
- result.status !== 'partial'
+ result.status !== 'partial' && syncProducedEmbeddableContent(result)
) {
try {
singleEmbedBackfill = await resolveSyncEmbedBackfill(engine, sourceId, {
@@ -5428,7 +5466,7 @@ See also:
}
}
if (jsonOut) {
- console.log(JSON.stringify(buildSingleSyncJsonEnvelope(sourceId, result, singleEmbedBackfill)));
+ console.log(JSON.stringify(buildSingleSyncJsonEnvelope(sourceId, result, singleEmbedBackfill, singleCostGate)));
}
return;
}
diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.ts
index 5aed86ff26..a73b2709c4 100644
--- a/src/commands/transcripts.ts
+++ b/src/commands/transcripts.ts
@@ -22,7 +22,10 @@ import type { TranscriptFormat } from '../core/transcripts/types.ts';
import { runTranscriptsIngest, type TranscriptsIngestResult } from '../core/transcripts/ingest.ts';
import { isOpenclawCheckpointFile } from '../core/transcripts/openclaw.ts';
import { isGrokSessionSidecarStrict } from '../core/transcripts/grok.ts';
-import { isClaudeCodeSubagentFile } from '../core/transcripts/claude-code.ts';
+import {
+ isClaudeCodeSubagentFile,
+ isClaudeCodeWorkflowArtifactFile,
+} from '../core/transcripts/claude-code.ts';
interface RecentOpts {
days?: number;
@@ -291,7 +294,11 @@ export async function expandPaths(specs: string[]): Promise<string[]> {
}
}
return [...new Set(out)].filter(
- (p) => !isOpenclawCheckpointFile(p) && !isGrokSessionSidecarStrict(p) && !isClaudeCodeSubagentFile(p),
+ (p) =>
+ !isOpenclawCheckpointFile(p) &&
+ !isGrokSessionSidecarStrict(p) &&
+ !isClaudeCodeSubagentFile(p) &&
+ !isClaudeCodeWorkflowArtifactFile(p),
);
}
diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.ts
index b659c875a1..c20d57ea2f 100644
--- a/src/core/ai/errors.ts
+++ b/src/core/ai/errors.ts
@@ -157,6 +157,33 @@ function numericStatusOf(e: unknown): number | undefined {
return undefined;
}
+/**
+ * Did the provider refuse the request BECAUSE of its `response_format:
+ * json_schema` (an Ollama build predating structured outputs, a strict proxy
+ * rejecting the schema shape) — as opposed to failing for any other reason?
+ * `chat()` retries such a call once without the schema and remembers the
+ * recipe; every other error (a 500, a context-length 400, a policy error)
+ * propagates untouched. Request-shaped only: a 5xx / 429 is never a
+ * capability rejection, even when its body echoes the request. Walks the
+ * SDK's wrapping chain (`cause`, RetryError's `lastError`) so the status and
+ * the phrase can sit on different layers.
+ */
+const STRUCTURED_OUTPUT_REJECTION_RE = /response_format|json_schema|structured[ _-]?outputs?/i;
+
+export function isStructuredOutputRejection(err: unknown): boolean {
+ let status: number | undefined;
+ let named = false;
+ let cur: unknown = err;
+ for (let depth = 0; cur && typeof cur === 'object' && depth < 5; depth++) {
+ const e = cur as { message?: unknown; responseBody?: unknown; cause?: unknown; lastError?: unknown };
+ status ??= numericStatusOf(e);
+ named ||= [e.message, e.responseBody].some(t => typeof t === 'string' && STRUCTURED_OUTPUT_REJECTION_RE.test(t));
+ cur = e.cause ?? e.lastError;
+ }
+ if (status !== undefined && (status < 400 || status >= 500 || status === 429)) return false;
+ return named;
+}
+
function statusToClass(status: number): GlobalLlmErrorClass | null {
if (status === 401 || status === 403) return 'auth';
if (status === 402) return 'billing';
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 7adf65aa13..9cf8fc44f2 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -21,7 +21,7 @@
* rotation (via configureGateway()) invalidates stale entries.
*/
-import { embed as aiEmbed, embedMany, generateObject, generateText, jsonSchema } from 'ai';
+import { embed as aiEmbed, embedMany, generateObject, generateText, jsonSchema, type JSONSchema7, type Output } from 'ai';
import { AsyncLocalStorage } from 'node:async_hooks';
import { createHash, randomUUID } from 'node:crypto';
import { listRecipes } from './recipes/index.ts';
@@ -58,7 +58,7 @@ import { parseLlmJson } from '../llm-json.ts';
import type { BrainEngine } from '../engine.ts';
import { dimsProviderOptions } from './dims.ts';
import { hasAnthropicKey, stashGatewayAnthropicKeyFromEnv } from './anthropic-key.ts';
-import { AIConfigError, AITransientError, normalizeAIError } from './errors.ts';
+import { AIConfigError, AITransientError, isStructuredOutputRejection, normalizeAIError } from './errors.ts';
import { getProviderCapabilities } from './capabilities.ts';
import { runGuardrails, hasGuardrails, type GuardrailHook } from '../guardrails.ts';
import { loadConfig } from '../config.ts';
@@ -3510,6 +3510,42 @@ export interface ChatOpts {
* request body — the AI SDK routes provider options by provider key.
*/
cacheSystem?: boolean;
+ /**
+ * JSON Schema the reply must conform to (#4863). Honored ONLY on
+ * openai-compatible recipes that declare `supports_structured_outputs` —
+ * backends that enforce `response_format: json_schema` server-side
+ * (Ollama's grammar-constrained decoding). Every other lane ignores the
+ * field, so native / claude-cli calls are byte-identical with or without
+ * it, and the reply still arrives as `text`: callers keep parsing and
+ * validating it themselves (see `jsonSchemaOutput`).
+ */
+ responseSchema?: { name: string; description?: string; schema: Record<string, unknown> };
+}
+
+/**
+ * Tolerant AI SDK `Output` spec for `ChatOpts.responseSchema` (#4863). NOT
+ * `Output.object`: generateText parses `output` eagerly when finishReason is
+ * 'stop', and Output.object throws NoObjectGeneratedError on unparseable
+ * text — that would turn a recoverable malformed reply into a thrown
+ * provider_error and skip the caller's own parse + retry lane. This spec only
+ * carries the responseFormat (what the openai-compatible provider turns into
+ * `response_format: json_schema`) and hands the raw text back, so
+ * result.text / stopReason / usage / the facts #2113 truncation retry all run
+ * unchanged. The streaming members are inert (chat() never streams).
+ */
+function jsonSchemaOutput(spec: NonNullable<ChatOpts['responseSchema']>): Output.Output<string, string, never> {
+ return {
+ name: 'json_schema',
+ responseFormat: Promise.resolve({
+ type: 'json' as const,
+ schema: spec.schema as JSONSchema7,
+ name: spec.name,
+ ...(spec.description ? { description: spec.description } : {}),
+ }),
+ parseCompleteOutput: async ({ text }) => text,
+ parsePartialOutput: async () => undefined,
+ createElementStreamTransform: () => undefined,
+ };
}
/**
@@ -4060,20 +4096,52 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {
}
: opts.system;
+ // #4863: schema-constrained decoding for openai-compatible backends that
+ // honor json_schema. Gated on the recipe declaration so a backend that
+ // would reject the schema is never sent one; a declared backend that
+ // ignores it just returns unconstrained text, which the caller's parse
+ // lane already handles. Native + claude-cli lanes never see the field.
+ // A declared backend that REJECTS it at call time (older Ollama build,
+ // strict proxy) gets one schemaless retry below and is remembered in
+ // `_structuredOutputRejectedRecipes` — the same process-lifetime memory
+ // expand() keeps — so the caller's own retry lanes don't re-pay the
+ // rejection and turn every call into a permanent provider_error.
+ const output = opts.responseSchema
+ && recipe.implementation === 'openai-compatible'
+ && recipeSupportsStructuredOutputs(recipe)
+ && !_structuredOutputRejectedRecipes.has(recipe.id)
+ ? jsonSchemaOutput(opts.responseSchema)
+ : undefined;
+
+ const generate = (out: typeof output) => guardedGeneration(modelStr, _generateTextTransport, {
+ model,
+ system: systemParam,
+ messages: toModelMessages(repairToolPairing(opts.messages)) as any,
+ tools: opts.tools && opts.tools.length > 0 ? tools : undefined,
+ maxOutputTokens: opts.maxTokens ?? defaultMaxOutputTokens(modelStr),
+ ...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),
+ output: out,
+ // v0.42.20.0 — default a chat timeout (composes with the caller's signal,
+ // shorter wins). Covers native-anthropic (the default provider + facts Haiku).
+ // Fresh signal per attempt so the schemaless retry gets its own timeout.
+ abortSignal: withDefaultTimeout(opts.abortSignal, AI_CHAT_TIMEOUT_MS),
+ providerOptions: Object.keys(providerOptions).length > 0 ? providerOptions : undefined,
+ ...(requestHeaders ? { headers: requestHeaders } : {}),
+ });
+
try {
- const result = await guardedGeneration(modelStr, _generateTextTransport, {
- model,
- system: systemParam,
- messages: toModelMessages(repairToolPairing(opts.messages)) as any,
- tools: opts.tools && opts.tools.length > 0 ? tools : undefined,
- maxOutputTokens: opts.maxTokens ?? defaultMaxOutputTokens(modelStr),
- ...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),
- // v0.42.20.0 — default a chat timeout (composes with the caller's signal,
- // shorter wins). Covers native-anthropic (the default provider + facts Haiku).
- abortSignal: withDefaultTimeout(opts.abortSignal, AI_CHAT_TIMEOUT_MS),
- providerOptions: Object.keys(providerOptions).length > 0 ? providerOptions : undefined,
- ...(requestHeaders ? { headers: requestHeaders } : {}),
- });
+ let result: Awaited<ReturnType<GenerateTextFn>>;
+ try {
+ result = await generate(output);
+ } catch (err) {
+ if (!output || isAIInvocationPolicyError(err) || !isStructuredOutputRejection(err)) throw err;
+ _structuredOutputRejectedRecipes.add(recipe.id);
+ console.warn(
+ `[ai.gateway] ${recipe.id} rejected response_format json_schema; retrying without a schema ` +
+ `and skipping it for the rest of this process: ${(err as Error)?.message ?? String(err)}`,
+ );
+ result = await generate(undefined);
+ }
// Normalize blocks. Vercel SDK gives us `result.content` (an array of typed
// parts) for v6+; fall back to text + toolCalls for older shapes.
diff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.ts
index 738e276d31..4510cf346e 100644
--- a/src/core/ai/providers/claude-cli-language-model.ts
+++ b/src/core/ai/providers/claude-cli-language-model.ts
@@ -81,11 +81,13 @@ let hermeticEnsured = false;
* (today's behavior). `1`/`true` → a per-process empty tmpdir; any other
* non-empty value is used verbatim as the config-dir path.
*
- * Opt-in, NOT default: on non-macOS installs the config dir also holds the
- * OAuth session credentials, so pointing the child at an empty dir logs it
- * out (macOS keeps credentials in the keychain and survives). SkillOpt runs
- * that need hermetic measurements (no user-level CLAUDE.md / settings.json /
- * hooks bleeding into rollouts) flip it deliberately — see
+ * Opt-in, NOT default: the config dir also holds the CLI's session
+ * credentials, so the empty-dir form logs the child out wherever the CLI
+ * reads its session from the config dir (observed on macOS with Claude Code
+ * 2.1.x too — #4741; nothing here seeds or looks up credential material).
+ * For hermetic-with-auth use the explicit-path form with a pre-seeded config.
+ * SkillOpt runs that need hermetic measurements (no user-level CLAUDE.md /
+ * settings.json / hooks bleeding into rollouts) flip it deliberately — see
* docs/guides/skillopt.md, "Hermetic claude-cli rollouts".
*/
export function resolveHermeticConfigDir(
diff --git a/src/core/ai/recipes/claude-cli.ts b/src/core/ai/recipes/claude-cli.ts
index 0862679225..68bfbdcb1d 100644
--- a/src/core/ai/recipes/claude-cli.ts
+++ b/src/core/ai/recipes/claude-cli.ts
@@ -83,10 +83,20 @@ export const claudeCli: Recipe = {
],
supports_tools: true,
supports_subagent_loop: true,
- // The CLI handles caching internally and does not surface it via the
- // standard cache_control control plane. From the gateway's POV the
- // model does not support prompt caching.
- supports_prompt_cache: false,
+ // The CLI caches prompt prefixes automatically — including the
+ // `--print` runs this provider dispatches, which Claude Code puts in
+ // its "main conversation" TTL bucket (one hour on a Claude
+ // subscription, five minutes on an API key).
+ // https://code.claude.com/docs/en/prompt-caching
+ //
+ // This field asks "does the provider cache at all" — see the contract
+ // on ProviderCapabilities.supportsPromptCaching in ../capabilities.ts,
+ // which is explicit that it is NOT "does it honor our markers", and
+ // that the degraded:no_caching advice "is wrong for a provider that
+ // caches without being asked". It was exactly that advice this recipe
+ // used to trigger. Declaring `false` because the gateway cannot drive
+ // the cache answered the other question.
+ supports_prompt_cache: true,
max_context_tokens: 200000,
// Cost figures match the underlying Claude API tier, but the actual
// bill is borne by the subscription. We report them for the budget
diff --git a/src/core/ai/recipes/ollama.ts b/src/core/ai/recipes/ollama.ts
index 79cd1600dd..5f9f23f5c1 100644
--- a/src/core/ai/recipes/ollama.ts
+++ b/src/core/ai/recipes/ollama.ts
@@ -1,4 +1,5 @@
import type { Recipe } from '../types.ts';
+import { GLM_THINKING_BY_DEFAULT_RE } from './zhipu.ts';
export const ollama: Recipe = {
id: 'ollama',
@@ -69,7 +70,13 @@ export const ollama: Recipe = {
supports_tools: false,
supports_subagent_loop: false,
supports_prompt_cache: false,
- supports_structured_outputs: false,
+ // Ollama enforces `response_format: json_schema` server-side
+ // (grammar-constrained decoding since 0.5) for every loaded model, so
+ // unlike tools this is a provider-wide fact, not a per-model one.
+ // chat() sends the caller's `responseSchema` here (facts extraction,
+ // #4863) and expand() takes the strict generateObject lane with its
+ // existing rejected-recipe fallback.
+ supports_structured_outputs: true,
// Reasoning-by-default local families spend output budget on internal
// reasoning before emitting answer text, and Ollama bills it against
// `max_tokens` — so callers that size output caps must grant headroom
@@ -84,8 +91,11 @@ export const ollama: Recipe = {
// qwen2.5-* tags can never be swallowed by it, and `qwen3-coder` (the
// instruct-only Qwen3 variant, no thinking mode) is excluded by
// lookahead. `phi4-mini-reasoning` is a reasoning model and matches
- // alongside `phi4-reasoning`.
+ // alongside `phi4-reasoning`. GLM-4.5+/5.x (`glm-5.3-flash[:cloud]`,
+ // `glm-4.6`) reuse the zhipu recipe's cutoff (gbrain#4727) — a reporter
+ // hit the 4000 cap on GLM-5.3-flash via Ollama cloud; `glm-4:9b` stays out.
thinking_by_default: (modelId: string) =>
+ GLM_THINKING_BY_DEFAULT_RE.test(modelId) ||
/^(?:qwen3[0-9]*(?!-coder)(?:[.\-:]|$)|deepseek-r[0-9]|gpt-oss(?:[.\-:]|$)|magistral(?:[.\-:]|$)|phi[0-9]+(?:-mini)?-reasoning)/i.test(
modelId,
),
diff --git a/src/core/ai/recipes/openrouter.ts b/src/core/ai/recipes/openrouter.ts
index 4cd5e80a4c..2dc6e97e76 100644
--- a/src/core/ai/recipes/openrouter.ts
+++ b/src/core/ai/recipes/openrouter.ts
@@ -2,6 +2,7 @@ import type { Recipe } from '../types.ts';
import { openrouterModelSupportsSubagentLoop } from '../openrouter-families.ts';
import { deepseekReasoningContentCompatFetch } from './deepseek.ts';
import { openaiModelSupportsPromptCache } from './openai.ts';
+import { GLM_THINKING_BY_DEFAULT_RE } from './zhipu.ts';
/**
* Private in-process marker header. `gateway.chat()` sets it when the caller
@@ -53,10 +54,14 @@ export function openrouterRequiresExplicitPromptCache(modelId: string): boolean
* Native DeepSeek v4 thinks by default (recipe `thinking_by_default: true`,
* #4172) and OpenRouter's DeepSeek hosts serve the same models — reasoning
* bills as OUTPUT tokens against max_tokens, so output-cap sizing must grant
- * the same headroom on the OR route (#4758).
+ * the same headroom on the OR route (#4758). Z.ai's GLM-4.5+/5.x think by
+ * default too (zhipu recipe, gbrain#4727) and OR bills their reasoning as
+ * completion tokens — same cutoff, same headroom under the `z-ai/` prefix.
*/
export function openrouterThinkingByDefault(modelId: string): boolean {
- return modelId.trim().toLowerCase().startsWith('deepseek/');
+ const normalized = modelId.trim().toLowerCase();
+ if (normalized.startsWith('deepseek/')) return true;
+ return normalized.startsWith('z-ai/') && GLM_THINKING_BY_DEFAULT_RE.test(normalized);
}
/**
diff --git a/src/core/ai/recipes/zhipu.ts b/src/core/ai/recipes/zhipu.ts
index 3cecbd26bb..ef37ac0266 100644
--- a/src/core/ai/recipes/zhipu.ts
+++ b/src/core/ai/recipes/zhipu.ts
@@ -15,6 +15,16 @@ import type { Recipe } from '../types.ts';
*
* Reference: https://open.bigmodel.cn/
*/
+
+/**
+ * GLM-4.5+ and the GLM-5.x series reason by default and bill that reasoning
+ * as output tokens (gbrain#4727). Shared with the ollama / openrouter recipes,
+ * which host the same models under their own prefixes, so the version cutoff
+ * lives in exactly one place. Pre-4.5 ids (glm-4, glm-4-plus, glm-3-turbo)
+ * do not match and keep the conservative output caps.
+ */
+export const GLM_THINKING_BY_DEFAULT_RE = /glm-(?:4\.[5-9]|[5-9])/i;
+
export const zhipu: Recipe = {
id: 'zhipu',
name: 'Zhipu AI (智谱AI BigModel)',
@@ -31,12 +41,9 @@ export const zhipu: Recipe = {
// enforce it), so newer GLM ids pass without a recipe edit.
models: ['glm-5.3', 'glm-5.3-flash', 'glm-5.1', 'glm-4.6', 'glm-4.5'],
supports_tools: true,
- // GLM-4.5+ and the GLM-5.x series reason by default and bill that
- // reasoning as output tokens (gbrain#4727) — the exact semantic
- // thinking_by_default documents (see deepseek.ts). Predicate scoped to
- // 4.5+ ids so older GLM ids routed through this recipe (glm-4,
- // glm-4-plus, glm-3-turbo) keep the conservative output caps.
- thinking_by_default: (modelId) => /glm-(4\.[5-9]|[5-9])/i.test(modelId),
+ // The exact semantic thinking_by_default documents (see deepseek.ts);
+ // predicate + rationale on GLM_THINKING_BY_DEFAULT_RE above.
+ thinking_by_default: (modelId) => GLM_THINKING_BY_DEFAULT_RE.test(modelId),
// gbrain-side stable tool ids (v0.38 D11) decoupled the loop from
// Anthropic response formats; GLM tool calling is stable through the
// OpenAI-compat path, same as deepseek/groq.
diff --git a/src/core/backfill-base.ts b/src/core/backfill-base.ts
index e7da71db78..09faaebafb 100644
--- a/src/core/backfill-base.ts
+++ b/src/core/backfill-base.ts
@@ -105,7 +105,9 @@ const DEFAULT_MAX_ERRORS = 200;
const DEFAULT_PER_BATCH_TIMEOUT_SEC = 600;
const MIN_BATCH_SIZE = 16;
-function checkpointKey(name: string): string {
+/** Config-table key a backfill's keyset cursor persists under. Exported so other
+ * resumable keyset loops (reindex-search-vector) share the convention. */
+export function checkpointKey(name: string): string {
return `backfill.${name}.last_id`;
}
diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.ts
index 4a5a4d0ada..1d8022a406 100644
--- a/src/core/bootstrap/harness.ts
+++ b/src/core/bootstrap/harness.ts
@@ -2108,6 +2108,12 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
// from the host registration or degrade honestly.
let token: string | null = null;
let tokenSource = '';
+ // #4586: the [C8] ownership probe doubles as the LIVE verdict for the
+ // claude-code mcp target. Positive evidence only — a URL that is not ours,
+ // or a non-HTTP transport at OUR (user) scope — flips the displayed state
+ // to 'failed'; not-found / unparseable stays the receipt's honest degrade.
+ // Status is read-only: the receipt itself is never rewritten here.
+ let claudeLiveError: string | null = null;
const claudeMcp = receipt.targets.find((t) => t.host === 'claude-code' && t.kind === 'mcp');
if (claudeMcp) {
try {
@@ -2122,12 +2128,29 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
if (info.found && info.url === receipt.url) {
token = parseClaudeMcpGetBearer(out);
if (token) tokenSource = 'claude registration';
+ } else if (info.found && info.url) {
+ claudeLiveError =
+ `registration now points at ${info.url}, not ${receipt.url} — owned by another install; ` +
+ 're-run `gbrain bootstrap harness --force` to reclaim, or --remove';
+ } else if (info.found) {
+ // No URL line: a stdio (or other non-HTTP) launch. Only a same-scope
+ // entry is a replacement; a project-scope one merely shadows ours
+ // from that cwd, which re-running the harness cannot undo.
+ const type = out.match(/^\s*Type:\s*(\S+)/m)?.[1];
+ if (type && type.toLowerCase() !== 'http' && /^\s*Scope:\s*User\b/im.test(out)) {
+ claudeLiveError =
+ `registration at user scope is now a ${type} serve (a \`claude mcp add\` or ` +
+ '`bootstrap hooks --scope user` replaced the HTTP wiring) — re-run `gbrain bootstrap harness` to reclaim';
+ }
}
}
} catch {
/* degrade */
}
}
+ const liveTargets = receipt.targets.map((t) =>
+ t === claudeMcp && claudeLiveError ? { ...t, state: 'failed' as const, error: claudeLiveError } : t,
+ );
if (!token) {
const codexMcp = receipt.targets.find((t) => t.host === 'codex' && t.kind === 'mcp');
if (codexMcp?.path && existsSync(codexMcp.path)) {
@@ -2216,7 +2239,7 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
token_name: receipt.token.name,
token_verified: tokenVerified,
degraded_per_turn: degraded,
- targets: receipt.targets,
+ targets: liveTargets,
...(instructionsProbes.length > 0 ? { instructions_blocks: instructionsProbes } : {}),
pending_previous_tokens: receipt.token.previous_ids ?? [],
receipt_path: harnessReceiptPath(d.gbrainHome),
@@ -2228,7 +2251,7 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
} else {
d.log(serveLine);
d.log(tokenLine);
- for (const t of receipt.targets) {
+ for (const t of liveTargets) {
d.log(` ${t.host}/${t.kind} (${t.scope}): ${t.state}${t.error ? ` — ${t.error}` : ''}`);
}
for (const p of instructionsProbes) {
@@ -2251,7 +2274,7 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
// crashed apply's pending/failed targets and an unconverged rotation are
// NOT success just because /health answers (ship-review P2). The
// token-unrecoverable honest degrade stays 0 per the documented contract.
- const allTargetsConfirmed = receipt.targets.every((t) => t.state === 'confirmed');
+ const allTargetsConfirmed = liveTargets.every((t) => t.state === 'confirmed');
const rotationConverged = (receipt.token.previous_ids?.length ?? 0) === 0;
// Half-removed state (red-team CRITICAL): --remove under a live PGLite
// serve strips every host target but defers the revoke, leaving a
diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.ts
index f149570b2e..e08f1da229 100644
--- a/src/core/brain-repo-durability.ts
+++ b/src/core/brain-repo-durability.ts
@@ -446,14 +446,23 @@ export function isDurabilityHardened(repoPath: string): boolean {
* never swept into the commit. Never throws; returns false on any failure
* (index.lock contention, nothing changed, detached states) — the DB row and
* the on-disk file remain the durable sinks either way.
+ *
+ * `git add -- <path>` stages a removal as readily as an edit, so
+ * `deletePageThrough` reuses this helper with `action: 'delete write-through'`
+ * — same hardening gate, same explicit-path discipline, distinct subject line.
*/
-export function commitWriteThroughFile(repoPath: string, absPath: string, slug: string): boolean {
+export function commitWriteThroughFile(
+ repoPath: string,
+ absPath: string,
+ slug: string,
+ action: 'write-through' | 'delete write-through' = 'write-through',
+): boolean {
try {
const rel = relative(repoPath, absPath);
if (!rel || rel.startsWith('..') || isAbsolute(rel)) return false;
const gitOpts = { stdio: 'ignore', timeout: 30_000, env: { ...process.env, ...GIT_ENV } } as const;
execFileSync('git', ['-C', repoPath, 'add', '--', rel], gitOpts);
- execFileSync('git', ['-C', repoPath, 'commit', '-m', `gbrain: write-through ${slug}`, '--', rel], gitOpts);
+ execFileSync('git', ['-C', repoPath, 'commit', '-m', `gbrain: ${action} ${slug}`, '--', rel], gitOpts);
return true;
} catch {
return false;
diff --git a/src/core/brainstorm/checkpoint.ts b/src/core/brainstorm/checkpoint.ts
index 4bedc89a80..e678665d3f 100644
--- a/src/core/brainstorm/checkpoint.ts
+++ b/src/core/brainstorm/checkpoint.ts
@@ -63,6 +63,12 @@ export interface BrainstormCheckpoint {
completed_crosses: CheckpointCross[];
failed_crosses: FailedCross[];
judge_done: boolean;
+ /**
+ * Slug the caller saved this run's idea page under. Carried across
+ * `--resume` so a re-scored run overwrites that page instead of forking a
+ * second one under a fresh nonce. Absent when the caller did not save.
+ */
+ idea_slug?: string;
}
const CURRENT_SCHEMA: 2 = 2;
diff --git a/src/core/brainstorm/orchestrator.ts b/src/core/brainstorm/orchestrator.ts
index 7e2e1bc10d..11bf0dfa4f 100644
--- a/src/core/brainstorm/orchestrator.ts
+++ b/src/core/brainstorm/orchestrator.ts
@@ -199,6 +199,13 @@ export interface BrainstormOptions {
* A5: bypass the 7-day staleness gate when --resume is set.
*/
forceResume?: boolean;
+ /**
+ * Slug the caller will save the result page under. Recorded in the
+ * checkpoint on the first run and echoed back as `BrainstormResult.idea_slug`
+ * on `--resume`, so the re-scored page overwrites the one the failed run
+ * saved instead of landing under a fresh nonce.
+ */
+ ideaSlug?: string;
}
/** One idea emitted to the user, with citation transparency (D6). */
@@ -238,6 +245,11 @@ export interface BrainstormResult {
short_of_target: boolean;
/** True iff judge phase failed and ideas were saved unscored (D12). */
judge_failed: boolean;
+ /**
+ * Slug to save this run's page under: the checkpoint's recorded slug when
+ * resuming a run that already saved one, else the caller's `ideaSlug`.
+ */
+ idea_slug?: string;
/** Cost actuals (codex r2 #10). */
cost: {
estimated_usd: number;
@@ -753,6 +765,7 @@ async function _runBrainstormInner(
completed_crosses: prevCheckpoint?.completed_crosses.slice() ?? [],
failed_crosses: prevCheckpoint?.failed_crosses.slice() ?? [],
judge_done: false,
+ idea_slug: prevCheckpoint?.idea_slug ?? opts.ideaSlug,
};
let crossesSinceFlush = 0;
const flush = (): void => {
@@ -902,7 +915,7 @@ async function _runBrainstormInner(
} catch (err) {
judgeFailed = true;
const msg = err instanceof Error ? err.message : String(err);
- stderr(`[${profile.label}] WARN: judge phase failed (${msg}); saving ideas unscored. Re-run with --retry-judge to score.\n`);
+ stderr(`[${profile.label}] WARN: judge phase failed (${msg}); saving ideas unscored. Re-score with: gbrain ${profile.label} --resume ${runId} (see --list-runs)\n`);
}
// ---- Phase 5: assemble BrainstormResult ----
@@ -930,10 +943,20 @@ async function _runBrainstormInner(
// TX4: surface --resume hint when any cross failed during this run.
// The user can re-run with `--resume <run_id>` and we'll retry only
// the missing crosses (failed_crosses + never-attempted).
+ //
+ // #4766: a judge failure keeps the checkpoint too. The flush above already
+ // persisted every completed cross with judge_done=false, so `--resume` is
+ // the judge-only retry: completed crosses short-circuit from disk and
+ // Phase 4 re-runs. Pre-fix this branch keyed on failed_crosses alone, so
+ // all-crosses-green + judge-failed marked judge_done and unlinked the file.
if (liveCheckpoint.failed_crosses.length > 0) {
stderr(
`[${profile.label}] ${liveCheckpoint.failed_crosses.length} cross(es) failed. Resume with: gbrain ${profile.label} --resume ${runId}\n`,
);
+ } else if (judgeFailed) {
+ stderr(
+ `[${profile.label}] Judge failed; ${liveCheckpoint.completed_crosses.length} cross(es) kept in checkpoint ${runId}. Re-score with: gbrain ${profile.label} --resume ${runId}\n`,
+ );
} else {
// Clean completion — every cross succeeded. Clear the checkpoint so we
// don't accumulate noise + so a stale run_id doesn't auto-resume.
@@ -957,6 +980,7 @@ async function _runBrainstormInner(
active_bias_tags: activeBiasTags,
short_of_target: farResult.short_of_target,
judge_failed: judgeFailed,
+ idea_slug: liveCheckpoint.idea_slug,
cost: {
estimated_usd: estimate,
actual_usd: actual,
@@ -1008,7 +1032,7 @@ export function formatBrainstormMarkdown(
lines.push(`# ${result.profile_label === 'lsd' ? 'LSD' : 'Brainstorm'}: ${result.question}`);
lines.push('');
if (result.judge_failed) {
- lines.push('> **Judge phase failed mid-run** — ideas below are unscored. Re-run with `--retry-judge` to score.');
+ lines.push('> **Judge phase failed mid-run** — ideas below are unscored. Re-score with `--resume <run_id>` (see `--list-runs`).');
lines.push('');
}
if (result.short_of_target) {
diff --git a/src/core/by-mention.ts b/src/core/by-mention.ts
index 93a36fcf32..3bb91b543a 100644
--- a/src/core/by-mention.ts
+++ b/src/core/by-mention.ts
@@ -26,6 +26,7 @@
* created it and we trust the gazetteer presence.
*/
+import { createHash } from 'crypto';
import type { BrainEngine } from './engine.ts';
import { isUndefinedTableError } from './utils.ts';
import { CJK_SLUG_CHARS } from './cjk.ts';
@@ -81,6 +82,20 @@ export interface GazetteerEntry {
*/
export type Gazetteer = Map<string, GazetteerEntry[]>;
+/**
+ * Fingerprint of every gazetteer entry (source_id, slug, title, tokens) for
+ * the by-mention resume checkpoint. Hashing only the first-token bucket KEYS
+ * missed a new "Acme Labs" beside an existing "Acme Corp", so resumed pages
+ * silently skipped the new entity.
+ */
+export function hashGazetteer(gazetteer: Gazetteer): string {
+ const entries: string[] = [];
+ for (const bucket of gazetteer.values()) {
+ for (const e of bucket) entries.push(`${e.source_id}\0${e.slug}\0${e.title}\0${e.tokens.join(' ')}`);
+ }
+ return createHash('sha256').update(entries.sort().join('\n')).digest('hex').slice(0, 8);
+}
+
export interface Mention {
/** Target page slug (the entity being mentioned). */
slug: string;
@@ -529,22 +544,25 @@ export async function buildGazetteer(
/**
* Scan body text for mentions of gazetteer entities. Pure function — no
* IO. Returns `Mention[]` ordered by offset, deduped per
- * `(fromSlug → entry.slug)` pair (first-mention-only cap).
+ * `(fromSourceId, fromSlug → entry.source_id, entry.slug)` pair
+ * (first-mention-only cap).
*
* Matcher is maximal-munch: at each token offset, the longest gazetteer
* entry that matches the body-token sequence wins. Single-word entries
* are length-1 maximal matches.
*
* Guards (deterministic):
- * - D13 self-link: skip when `fromSlug === entry.slug`.
+ * - D13 self-link: skip when BOTH `source_id` and `slug` match the
+ * scanning page. Slug uniqueness is `(source_id, slug)`, so once the
+ * cross-source guard is lifted a foreign namesake is a real target.
* - Cross-source: skip when `fromSourceId !== entry.source_id` UNLESS
* `opts.allowCrossSource` (the `link_resolution.cross_source` opt-in —
* the same switch wikilink resolution honours). A same-name entity in
* the scanning page's OWN source always outranks a cross-source twin,
* whichever way the switch is set (bucket order is length-only, so the
* first maximal match may be the foreign twin).
- * - First-mention-only cap: dedup by `entry.slug` (one link per
- * target page regardless of how many body mentions there are).
+ * - First-mention-only cap: dedup by `(entry.source_id, entry.slug)` (one
+ * link per target page regardless of how many body mentions there are).
*
* Code-block stripping via `stripCodeBlocks` (preserves offsets, so the
* returned mention offsets index into the ORIGINAL text not the stripped
@@ -561,7 +579,7 @@ export function findMentionedEntities(
if (tokens.length === 0) return [];
const out: Mention[] = [];
- const seenSlugs = new Set<string>();
+ const seenTargets = new Set<string>();
let i = 0;
while (i < tokens.length) {
@@ -617,7 +635,7 @@ export function findMentionedEntities(
}
// Guards.
- if (matched.slug === opts.fromSlug) {
+ if (matched.source_id === opts.fromSourceId && matched.slug === opts.fromSlug) {
i += matchedTokens;
continue;
}
@@ -625,7 +643,8 @@ export function findMentionedEntities(
i += matchedTokens;
continue;
}
- if (seenSlugs.has(matched.slug)) {
+ const target = `${matched.source_id}\0${matched.slug}`;
+ if (seenTargets.has(target)) {
i += matchedTokens;
continue;
}
@@ -636,7 +655,7 @@ export function findMentionedEntities(
name: matched.title,
offset: head.offset,
});
- seenSlugs.add(matched.slug);
+ seenTargets.add(target);
i += matchedTokens;
}
diff --git a/src/core/cjk.ts b/src/core/cjk.ts
index 8654817db0..62c0bd1e2e 100644
--- a/src/core/cjk.ts
+++ b/src/core/cjk.ts
@@ -42,6 +42,15 @@ export const CJK_RANGES_REGEX = new RegExp(`[${CJK_SLUG_CHARS}]`);
*/
export const SLUG_WORD_CHARS = '\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}\\p{N}';
+/**
+ * Unicode variation selectors (emoji VS1–VS16 U+FE00–FE0F, ideographic IVS
+ * U+E0100–E01EF): Mn-category invisibles that survive the \p{M} keep above.
+ * Both slug grammars — `sync.ts:slugifySegment` and its #4855 twin
+ * `link-extraction.ts:normalizeBasename` — strip them so an emoji folder name
+ * written with VS16 lands on the clean slug and its `[[wikilink]]` resolves.
+ */
+export const SLUG_VARIATION_SELECTORS_RE = /[\uFE00-\uFE0F\u{E0100}-\u{E01EF}]/gu;
+
/**
* Page-slug segment grammar (no anchors): word-char lead, then word-char or
* hyphen continuation. Single source for validatePageSlug (operations.ts),
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 3e60ae5125..50f23a8f6f 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -14,113 +14,113 @@
// (help-text mentions count): accepting an ignored flag is the pre-#2185
// status quo; missing a real one breaks working invocations.
export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
- 'advisor': ['--apply', '--brain', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--skills-dir', '--source', '--surface', '--token-ttl', '--verbose', '--workspace'],
- 'agent': ['--all', '--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated', '--federated-read', '--flag', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-federated', '--no-follow', '--note', '--path', '--port', '--preset', '--reissue', '--repo', '--restore-only', '--scopes', '--show-token', '--since', '--source', '--source-guard', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],
- 'anomalies': ['--brain', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--lookback-days', '--mcp-only', '--no-embedding', '--sigma', '--since', '--source', '--surface', '--token-ttl'],
- 'apply-migrations': ['--ab', '--all', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dry-run', '--exclude', '--exclusive', '--fast', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--from-meetings', '--from-pages', '--help', '--history', '--host-dir', '--http', '--json', '--lang', '--list', '--locks', '--markdown', '--max-age', '--migrate-only', '--migration', '--mode', '--multimodal', '--no-autopilot-install', '--no-embedding', '--no-extract', '--non-interactive', '--phase', '--priority', '--refresh-unqualified', '--remediate', '--require-db', '--rollback', '--skip-verify', '--source', '--stale', '--surface', '--token-ttl', '--undo-wave', '--use-captured-snapshot', '--with-calibration', '--yes'],
- 'auth': ['--allowed-operations', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--exclude', '--fast', '--federated-read', '--force', '--from-pages', '--grant-types', '--help', '--http', '--id', '--if-version', '--json', '--max-concurrent', '--no-embedding', '--profile', '--redirect-uri', '--repair', '--scopes', '--source', '--stale', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],
- 'autopilot': ['--all', '--auto-fix', '--batch', '--brain', '--break-lock', '--by-type', '--check', '--dim', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--exclude', '--explain', '--fast', '--ff-only', '--fix', '--force', '--force-break-lock', '--force-retry', '--from-pages', '--help', '--http', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--json', '--markdown', '--max-age', '--max-rss', '--max-usd', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-federated', '--no-inject', '--no-mutate', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--phase', '--print', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--source', '--stale', '--status', '--surface', '--swap-only', '--target', '--target-score', '--timeout', '--to', '--token-ttl', '--uninstall', '--unsafe-bypass-dream-guard', '--user', '--version', '--yes'],
+ 'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace'],
+ 'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],
+ 'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],
+ 'apply-migrations': ['--brain', '--dry-run', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--require-db', '--skip-verify', '--source', '--yes'],
+ 'auth': ['--allowed-operations', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr-insecure', '--federated-read', '--grant-types', '--help', '--id', '--if-version', '--json', '--max-concurrent', '--profile', '--redirect-uri', '--repair', '--scopes', '--source', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],
+ 'autopilot': ['--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--phase', '--refresh-cache', '--repo', '--source', '--status', '--swap-only', '--target', '--to', '--uninstall', '--user', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
- 'backup': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--count', '--dir', '--explain', '--follow', '--help', '--into', '--json', '--output', '--path', '--porcelain', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restore-only', '--source', '--stale', '--timeout', '--verify'],
+ 'backup': ['--background', '--brain', '--dir', '--explain', '--follow', '--help', '--into', '--json', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--verify'],
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
- 'book-mirror': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--author', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--chapters-dir', '--check', '--content', '--context-file', '--date', '--days', '--dry-run', '--entities', '--exclude', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--max-usd', '--mode', '--model', '--multimodal', '--near-symbol', '--no-confirm', '--no-embedding', '--no-follow', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--remediate', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale', '--stale-ok', '--stats', '--stdin', '--surface', '--timeout', '--timeout-ms', '--title', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],
- 'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--compile', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--fast', '--file', '--flag', '--force', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--isolated', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-embedding', '--no-hooks', '--no-verify', '--once', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push', '--push-only', '--quiet', '--rebase', '--remove', '--repair', '--scope', '--scopes', '--set', '--short', '--show', '--show-toplevel', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--token-ttl', '--unset-all', '--url', '--user-hooks', '--verify', '--version', '--visibility', '--workspace', '--yes'],
- 'brainstorm': ['--all', '--brain', '--chunker-debug', '--code', '--compile', '--exclude', '--fast', '--file', '--fix', '--force', '--force-rechunk', '--force-resume', '--from-pages', '--full', '--help', '--http', '--json', '--judge-model', '--lang', '--limit', '--list-runs', '--markdown', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--model', '--no-embed', '--no-embedding', '--no-save', '--path', '--resume', '--retry-failed', '--retry-judge', '--save', '--source', '--stale', '--strict-budget', '--surface', '--timeout', '--token-ttl', '--yes'],
- 'cache': ['--brain', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--source', '--surface', '--token-ttl', '--yes'],
- 'calibration': ['--ab', '--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--by-mention', '--content', '--date', '--days', '--dry-run', '--entities', '--explain', '--federated', '--file', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--lang', '--limit', '--markdown', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-federated', '--offset', '--page', '--path', '--phase', '--progress-interval', '--progress-json', '--quiet', '--recency', '--regenerate', '--repo', '--restore-only', '--salience', '--save', '--scrub-gstack', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--stale', '--stale-ok', '--stats', '--stdin', '--surface', '--symbol-kind', '--thin', '--trusted-extraction', '--types', '--undo-wave', '--url', '--walk-depth', '--with-calibration', '--with-db', '--yes'],
- 'call': ['--brain', '--federated', '--help', '--http', '--json', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--stale', '--timeout'],
- 'capture': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--by-mention', '--content', '--date', '--days', '--depth', '--entities', '--exclude', '--fast', '--federated', '--file', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--repo', '--restore-only', '--salience', '--save', '--scopes', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--stale-ok', '--stats', '--stdin', '--surface', '--token-ttl', '--trusted-extraction', '--type', '--types', '--url', '--walk-depth', '--what', '--where', '--who', '--with-db', '--yes'],
- 'check-backlinks': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dir', '--dry-run', '--explain', '--follow', '--help', '--include-frontmatter', '--json', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--type'],
+ 'book-mirror': ['--access', '--allow-empty', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--file', '--follow', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--mode', '--model', '--multimodal', '--no-confirm', '--no-follow', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--types', '--url', '--yes'],
+ 'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--file', '--force', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-verify', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push-only', '--quiet', '--rebase', '--remove', '--repair', '--scope', '--scopes', '--set', '--short', '--show', '--show-toplevel', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
+ 'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--markdown', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
+ 'cache': ['--brain', '--help', '--json', '--source', '--yes'],
+ 'calibration': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--dry-run', '--entities', '--file', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--phase', '--regenerate', '--scrub-gstack', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--undo-wave', '--url', '--with-calibration', '--yes'],
+ 'call': ['--brain', '--help', '--json', '--source'],
+ 'capture': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--depth', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--quiet', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--trusted-extraction', '--type', '--types', '--url', '--what', '--where', '--who', '--yes'],
+ 'check-backlinks': ['--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],
- 'check-update': ['--all', '--brain', '--check', '--dim', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],
- 'claw-test': ['--ab', '--agent', '--all', '--auto', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dir', '--exclusive', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--help', '--history', '--http', '--json', '--keep-tempdir', '--lang', '--list-agents', '--live', '--local', '--locks', '--markdown', '--max-age', '--message', '--multimodal', '--no-embed', '--no-embedding', '--no-extract', '--output-format', '--path', '--pglite', '--phase', '--priority', '--progress-json', '--refresh-unqualified', '--remediate', '--rollback', '--run-id', '--scenario', '--skip-verify', '--source', '--stale', '--surface', '--transcripts', '--undo-wave', '--use-captured-snapshot', '--version', '--with-calibration', '--yes'],
- 'code-callees': ['--all', '--all-sources', '--brain', '--chunker-debug', '--help', '--json', '--lang', '--limit', '--no-json', '--source', '--yes'],
- 'code-callers': ['--all', '--all-sources', '--brain', '--chunker-debug', '--help', '--json', '--lang', '--limit', '--no-json', '--source', '--yes'],
- 'code-def': ['--all', '--all-sources', '--brain', '--chunker-debug', '--help', '--json', '--lang', '--limit', '--no-json', '--pretty', '--source', '--yes'],
- 'code-refs': ['--all', '--all-sources', '--brain', '--chunker-debug', '--help', '--json', '--lang', '--limit', '--no-json', '--source', '--yes'],
- 'compile-context': ['--brain', '--budget', '--check', '--federated', '--help', '--include', '--json', '--no-federated', '--out', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--stdout', '--target'],
- 'config': ['--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--column', '--coverage-override', '--date', '--db-url', '--detail', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exclude', '--explain', '--fast', '--federated-read', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--markdown', '--model', '--multimodal', '--no-embedding', '--no-federated', '--path', '--pattern', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--raw', '--recency', '--remediate', '--reset', '--session', '--source', '--stale', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--yes'],
- 'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--delete-brain', '--env', '--force', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--workspace', '--yes'],
- 'connectors': ['--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-browser', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--token', '--try-oauth', '--window-days'],
+ 'check-update': ['--brain', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],
+ 'claw-test': ['--agent', '--brain', '--dir', '--force-retry', '--format', '--help', '--json', '--keep-tempdir', '--list-agents', '--live', '--local', '--locks', '--message', '--no-embed', '--no-embedding', '--output-format', '--pglite', '--progress-json', '--run-id', '--scenario', '--skip-verify', '--source', '--version', '--yes'],
+ 'code-callees': ['--all-sources', '--brain', '--help', '--json', '--lang', '--limit', '--no-json', '--source'],
+ 'code-callers': ['--all-sources', '--brain', '--help', '--json', '--lang', '--limit', '--no-json', '--source'],
+ 'code-def': ['--all-sources', '--brain', '--help', '--json', '--lang', '--limit', '--no-json', '--source'],
+ 'code-refs': ['--all-sources', '--brain', '--help', '--json', '--lang', '--limit', '--no-json', '--source'],
+ 'compile-context': ['--brain', '--budget', '--check', '--help', '--include', '--json', '--out', '--source', '--stdout', '--target'],
+ 'config': ['--background', '--brain', '--coverage-override', '--db-url', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--markdown', '--path', '--pattern', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--raw', '--session', '--source', '--timeout', '--to', '--url', '--yes'],
+ 'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],
+ 'connectors': ['--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-browser', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--window-days'],
'conversation-parser': ['--brain', '--help', '--json', '--source'],
- 'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--supabase', '--surface', '--timeout', '--to', '--url', '--version'],
- 'db-repair': ['--ab', '--all', '--allow-docker', '--apply', '--apply-rewrites', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--db-url', '--dry-run', '--exclude', '--exclusive', '--explain', '--fast', '--filter', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--from-pages', '--help', '--history', '--http', '--json', '--lang', '--locks', '--markdown', '--max-age', '--multimodal', '--name', '--near-symbol', '--no-embedding', '--no-extract', '--path', '--phase', '--prefer-postgres', '--priority', '--quiet', '--refresh-unqualified', '--remediate', '--restart', '--restore-only', '--rollback', '--skip-verify', '--source', '--stale', '--supabase', '--surface', '--symbol-kind', '--thin', '--token-ttl', '--undo-last-rewrite', '--undo-wave', '--url', '--use-captured-snapshot', '--version', '--with-calibration', '--yes'],
- 'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--audit-rejects', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--date', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exclusive', '--explain', '--fast', '--federated', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--index-audit', '--init', '--input', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-jobs', '--max-rss', '--max-usd', '--mcp-even-if-plugin', '--mcp-only', '--migrate-only', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-hooks', '--no-migrate', '--no-mutate', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--print', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--rebuild-rollup', '--recency', '--refresh', '--refresh-unqualified', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--review-lower', '--rollback', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-guard', '--source-id', '--stale', '--stats', '--status', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--user-hooks', '--verbose', '--verify', '--version', '--window', '--with-calibration', '--workers', '--yes'],
- 'dream': ['--all', '--audit-rejects', '--brain', '--break-lock', '--cancel-unmatched', '--date', '--dir', '--drain', '--drain-implied', '--dry-run', '--federated', '--fix', '--force', '--force-break-lock', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--max-age', '--max-usd', '--no-federated', '--no-mutate', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--repo', '--restore-only', '--since', '--source', '--source-guard', '--source-id', '--stale', '--threshold', '--timeout', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
- 'edges-backfill': ['--all', '--all-sources', '--brain', '--concurrency', '--federated', '--help', '--json', '--max-age', '--max-chunks', '--max-cost-usd', '--no-federated', '--older-than', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--timeout', '--workers'],
- 'embed': ['--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--check', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exclude', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--name', '--no', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pglite', '--prefix', '--print', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--serial', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--version'],
- 'engine': ['--apply', '--apply-rewrites', '--brain', '--break-lock', '--db-url', '--exclude', '--explain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--lang', '--markdown', '--multimodal', '--near-symbol', '--no-embedding', '--path', '--prefer-postgres', '--probe', '--quiet', '--restore-only', '--source', '--stale', '--supabase', '--surface', '--symbol-kind', '--thin', '--token-ttl', '--url', '--yes'],
- 'enrich': ['--access', '--all', '--all-sources', '--allow-empty', '--apply', '--asof', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--by-mention', '--check', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--content', '--date', '--days', '--detail', '--dim', '--dir', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--exclude', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--judge-model', '--kind', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--name', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-federated', '--offset', '--older-than', '--order', '--page', '--path', '--print', '--progress-interval', '--progress-json', '--quiet', '--recency', '--reenrich-after', '--remediate', '--resume', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale', '--stale-ok', '--stats', '--stdin', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--token-ttl', '--trusted-extraction', '--types', '--url', '--version', '--walk-depth', '--with-db', '--workers', '--yes'],
- 'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--brain-wide-max-cost-usd', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--capture-pool', '--check', '--code', '--committed-baseline', '--compare', '--compare-limit', '--compile', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--detail', '--dim', '--dimensions', '--distance-min', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--exclude', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fast', '--fix', '--fixtures', '--flag', '--follow', '--force', '--force-rechunk', '--format', '--from-capture', '--from-db', '--from-pages', '--gold', '--grounding-min', '--harness', '--help', '--http', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--lang', '--limit', '--llm', '--markdown', '--max-cost-usd', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--name-only', '--no', '--no-cache', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--print', '--priority', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--receipt-dir', '--recency', '--record', '--refresh-cache', '--remediate', '--reranker', '--reset', '--resolve', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--strict', '--suite', '--suites', '--supabase', '--surface', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--token-ttl', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--verify', '--version', '--with-code-intel', '--yes'],
- 'export': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dir', '--explain', '--federated', '--fix', '--follow', '--full', '--help', '--include-hidden', '--json', '--lang', '--markdown', '--multimodal', '--name-status', '--near-symbol', '--no-federated', '--path', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--slug-prefix', '--source', '--source-guard', '--stale', '--strategy', '--symbol-kind', '--thin', '--timeout', '--type'],
- 'extract': ['--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--catch-up', '--check', '--code', '--concurrency', '--dir', '--dry-run', '--explain', '--federated', '--federated-read', '--follow', '--from-meetings', '--full', '--help', '--include-frontmatter', '--include-hidden', '--infer-dates', '--json', '--kind', '--markdown', '--max-age', '--max-cost-usd', '--name-status', '--ner', '--no-federated', '--older-than', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--remediate', '--repo', '--restore-only', '--run-id', '--since', '--since-created', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--strategy', '--timeout', '--type', '--verbose', '--workers', '--yes'],
- 'extract-conversation-facts': ['--all', '--all-sources', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--by-mention', '--check', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--dim', '--dir', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--federated', '--fix', '--follow', '--force', '--force-break-lock', '--help', '--json', '--judge-model', '--kind', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--name', '--no', '--no-embed', '--no-embedding', '--no-federated', '--older-than', '--override-disabled', '--path', '--pglite', '--print', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--segment-limit', '--session', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--version', '--workers', '--yes'],
- 'features': ['--all', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--progress-json', '--quiet', '--rebuild', '--refresh', '--repo', '--run-id', '--since', '--since-created', '--slugs', '--source', '--source-id', '--stale', '--target', '--type', '--verbose', '--workers'],
- 'files': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--exclude', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--json', '--no-embedding', '--no-federated', '--no-pointer', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--retry-failed', '--save', '--source', '--source-guard', '--stale', '--surface', '--timeout', '--token-ttl', '--type', '--yes'],
- 'forget': ['--access', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--force', '--from-pages', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recency', '--repo', '--restore-only', '--rollup', '--salience', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--stale-ok', '--stats', '--stdin', '--supersessions', '--surface', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],
- 'founder': ['--brain', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--mcp-only', '--no-embedding', '--since', '--source', '--surface', '--token-ttl', '--until'],
- 'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--redact', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],
- 'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude', '--exclude-standard', '--fast', '--fix', '--force', '--from-pages', '--full', '--get', '--help', '--http', '--include-catch-all', '--include-hidden', '--json', '--name-only', '--name-status', '--no-embedding', '--no-verify', '--others', '--source', '--strategy', '--surface', '--timeout', '--token-ttl', '--uninstall', '--write-back'],
- 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--embedding-dimensions', '--embedding-model', '--entity', '--exclude', '--expansion-model', '--fast', '--force', '--from-pages', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--reauth', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--supabase', '--surface', '--sync-budget-ms', '--timeout', '--timeout-ms', '--to', '--token-command', '--token-ttl', '--url', '--version', '--via'],
- 'graph-query': ['--brain', '--depth', '--direction', '--exclude', '--fast', '--federated', '--force', '--from-pages', '--help', '--http', '--include-foreign', '--json', '--mcp-only', '--no-embedding', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--surface', '--token-ttl', '--type'],
- 'hook': ['--allow-unverified-remote', '--auto', '--brain', '--cached', '--count', '--delete-brain', '--detach', '--diff-filter', '--end-of-options', '--env', '--exclude', '--exclude-standard', '--fast', '--force', '--from-pages', '--get', '--harness', '--help', '--http', '--jq', '--json', '--name-only', '--no-embedding', '--others', '--path', '--porcelain', '--project', '--pure', '--quiet', '--remove', '--session', '--show-current', '--show-toplevel', '--source', '--stats', '--status', '--surface', '--token', '--token-ttl'],
- 'import': ['--all', '--allow-empty', '--allow-noncanonical-root', '--asof', '--background', '--brain', '--brain-wide-max-cost-usd', '--cached', '--check', '--code', '--compile', '--concurrency', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--fix', '--follow', '--force', '--force-rechunk', '--fresh', '--from-pages', '--full', '--help', '--http', '--include-gitignored', '--include-hidden', '--json', '--lang', '--log-noop', '--markdown', '--max-age', '--multimodal', '--name', '--name-status', '--no-embed', '--no-embedding', '--no-federated', '--no-gpg-sign', '--no-verify', '--older-than', '--orphan', '--others', '--parallel', '--path', '--pglite', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--short', '--show-toplevel', '--since', '--skip-failed', '--slugs', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--verify', '--workers'],
- 'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--ctx-size', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--entity', '--exclude', '--expansion-model', '--fast', '--flag', '--force', '--from-pages', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--judge-model', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--print', '--probe', '--provenance', '--quiet', '--reranking', '--reset', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--token-ttl', '--touchpoint', '--url', '--version', '--yes'],
- 'integrations': ['--auto', '--brain', '--dry-run', '--embeddings', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--overwrite', '--refresh', '--reranking', '--source', '--surface', '--target', '--token-ttl'],
- 'integrity': ['--auto', '--backend', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--confidence', '--cost', '--dry-run', '--exclude', '--explain', '--fast', '--follow', '--force', '--fresh', '--from-pages', '--help', '--http', '--json', '--limit', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--stale', '--supabase', '--surface', '--timeout', '--token-ttl', '--type', '--url'],
- 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-protected', '--allow-shell-jobs', '--apply', '--asof', '--auto', '--auto-with-prompt', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--cluster', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--content', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--fast', '--federated', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--full-history', '--hard-deadline', '--health-interval', '--held-out', '--help', '--http', '--idempotency-key', '--ids', '--image', '--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', '--lang', '--limit', '--lock', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federate', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-max-cost', '--no-mutate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--offset', '--older-than', '--once', '--order', '--orphan', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--print', '--priority', '--progress-interval', '--progress-json', '--queue', '--quiet', '--rebuild', '--recency', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--run-id', '--salience', '--save', '--segment-limit', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--sigkill-rescue', '--since', '--since-created', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stale-ok', '--stats', '--status', '--stdin', '--strategy', '--surface', '--swap-only', '--symbol-kind', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--token-ttl', '--trusted-extraction', '--type', '--types', '--uninstall', '--unsafe-bypass-dream-guard', '--url', '--user', '--verbose', '--verify', '--version', '--walk-depth', '--watch', '--wedge-rescue', '--with-db', '--workers', '--working-tree', '--yes'],
- 'lint': ['--abbrev-ref', '--abort', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--branch', '--cached', '--check', '--compile', '--dry-run', '--exclude', '--explain', '--fast', '--file', '--fix', '--follow', '--force', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--help', '--http', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-embedding', '--no-verify', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push-only', '--quiet', '--rebase', '--remediate', '--short', '--show-toplevel', '--source', '--stale', '--surface', '--timeout', '--token-ttl', '--unset-all'],
- 'loops': ['--all', '--brain', '--federated-read', '--help', '--http', '--json', '--source', '--source-guard', '--stale-ok', '--status', '--timeout', '--top', '--type'],
- 'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--retry-judge', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--input', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--nice', '--no-mutate', '--older-than', '--once', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebuild', '--rebuild-rollup', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--reset', '--resume', '--run-id', '--safe', '--scope', '--show-current', '--since', '--since-created', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
- 'mcp': ['--admin-token-file', '--agent', '--arg', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--federated-read', '--harness', '--help', '--if-version', '--install', '--json', '--limit', '--profile', '--queue', '--resume', '--root', '--source', '--timeout', '--timeout-ms', '--token-ttl', '--url'],
- 'migrate': ['--ab', '--all', '--auto-update', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--build-index', '--by-mention', '--catch-up', '--check', '--compile', '--days', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--exclude', '--exclusive', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--from-meetings', '--from-pages', '--help', '--history', '--http', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--lang', '--locks', '--markdown', '--max-age', '--model', '--multimodal', '--name', '--nice', '--no', '--no-embed', '--no-embedding', '--no-extract', '--non-interactive', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--phase', '--prefix', '--print', '--priority', '--progress-interval', '--progress-json', '--quiet', '--refresh-unqualified', '--remediate', '--reranker', '--reranking', '--resume', '--retarget', '--rollback', '--since', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--surface', '--timeout', '--to', '--token-ttl', '--undo-wave', '--url', '--use-captured-snapshot', '--version', '--with-calibration', '--yes'],
- 'models': ['--brain', '--detail', '--dim', '--drain', '--embedding-dimensions', '--embedding-model', '--embeddings', '--help', '--json', '--judge-model', '--model', '--multimodal', '--no', '--no-embed', '--print', '--recency', '--reranking', '--reset', '--skip', '--source', '--to', '--version'],
- 'mounts': ['--alias', '--brain', '--cache', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--explain', '--help', '--id', '--json', '--lang', '--lock', '--markdown', '--mcp-url', '--multimodal', '--near-symbol', '--path', '--restore-only', '--skills-dir', '--source', '--stale', '--symbol-kind', '--thin', '--verbose'],
- 'notability-eval': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--model', '--multimodal', '--no', '--no-embed', '--out', '--print', '--repo', '--skip-llm', '--source', '--target-high', '--target-low', '--target-medium', '--to', '--version'],
- 'onboard': ['--access', '--all', '--allow-empty', '--allow-protected', '--apply', '--asof', '--auto', '--auto-with-prompt', '--bound-slug-prefixes', '--brain', '--by-mention', '--check', '--content', '--date', '--days', '--entities', '--explain', '--federated', '--file', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--offset', '--page', '--params', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--remediate', '--remediation-plan', '--resume', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale-ok', '--stats', '--stdin', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],
- 'orphans': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout'],
+ 'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--supabase', '--surface', '--to', '--url', '--version'],
+ 'db-repair': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],
+ 'doctor': ['--abbrev-ref', '--abort', '--all', '--allow-old-serve', '--allow-unverified-remote', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embedding', '--no-hooks', '--no-migrate', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--restore-only', '--resume', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],
+ 'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
+ 'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
+ 'embed': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--include-null-signature', '--json', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to'],
+ 'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
+ 'enrich': ['--access', '--allow-empty', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],
+ 'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--markdown', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--verify', '--with-code-intel', '--yes'],
+ 'export': ['--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type'],
+ 'extract': ['--background', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--dry-run', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--ner', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--workers', '--yes'],
+ 'extract-conversation-facts': ['--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embedding', '--override-disabled', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--segment-limit', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--workers', '--yes'],
+ 'features': ['--all', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--rebuild', '--refresh', '--repo', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--type', '--verbose', '--workers'],
+ 'files': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--yes'],
+ 'forget': ['--access', '--allow-empty', '--as-context', '--asof', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--file', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--query', '--reason', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],
+ 'founder': ['--brain', '--help', '--json', '--mcp-only', '--since', '--source', '--until'],
+ 'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],
+ 'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--get', '--git-common-dir', '--help', '--include-catch-all', '--json', '--name-only', '--no-verify', '--others', '--source', '--type', '--uninstall'],
+ 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--reauth', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via'],
+ 'graph-query': ['--brain', '--depth', '--direction', '--help', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
+ 'hook': ['--allow-unverified-remote', '--auto', '--brain', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--exclude-standard', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--session', '--show-current', '--show-toplevel', '--source'],
+ 'import': ['--allow-empty', '--allow-noncanonical-root', '--background', '--brain', '--cached', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--fresh', '--help', '--include-gitignored', '--json', '--log-noop', '--markdown', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-verify', '--others', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--workers'],
+ 'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],
+ 'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
+ 'integrity': ['--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url'],
+ 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--queue', '--quiet', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'lint': ['--abbrev-ref', '--abort', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--explain', '--file', '--fix', '--follow', '--get', '--git-dir', '--git-path', '--help', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-verify', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],
+ 'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],
+ 'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
+ 'maintain': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--reset', '--resume', '--safe', '--scope', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'mcp': ['--admin-token-file', '--agent', '--arg', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--federated-read', '--harness', '--help', '--if-version', '--install', '--json', '--limit', '--profile', '--queue', '--resume', '--root', '--source', '--timeout-ms', '--token-ttl', '--url'],
+ 'migrate': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-retry', '--force-sunset-target', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--locks', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],
+ 'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--to'],
+ 'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
+ 'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--target-high', '--target-low', '--target-medium', '--to'],
+ 'onboard': ['--access', '--allow-empty', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--date', '--days', '--entities', '--explain', '--file', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--once', '--page', '--params', '--path', '--remediate', '--remediation-plan', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--yes'],
+ 'orphans': ['--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],
- 'pglite-repair': ['--brain', '--break-lock', '--dry-rnu', '--dry-run', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--path', '--quiet', '--source', '--surface', '--token-ttl', '--yes'],
- 'post-upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--exclude', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pglite', '--print', '--quiet', '--recency', '--repo', '--require-db', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--timeout', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'],
- 'protocol': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale-ok', '--stats', '--stdin', '--surface', '--synthesize', '--target', '--timeout', '--token', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],
- 'providers': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--print', '--reranking', '--reset', '--source', '--surface', '--to', '--token-ttl', '--touchpoint', '--version', '--yes'],
+ 'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--help', '--json', '--path', '--source', '--yes'],
+ 'post-upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--concurrency', '--cost-estimate', '--dim', '--embedding-dimensions', '--embedding-model', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--pglite', '--quiet', '--repo', '--require-db', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--swap-only', '--target', '--to', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],
+ 'protocol': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--token', '--trusted-extraction', '--types', '--url', '--yes'],
+ 'providers': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--to', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
- 'quarantine': ['--apply', '--brain', '--code', '--compile', '--exclude', '--fast', '--fix', '--force', '--force-rechunk', '--from-pages', '--help', '--http', '--include-flagged', '--json', '--lang', '--limit', '--markdown', '--no-embed', '--no-embedding', '--source', '--source-id', '--stale', '--surface', '--token-ttl'],
- 'recall': ['--access', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--force', '--from-pages', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recency', '--repo', '--restore-only', '--rollup', '--salience', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--stale-ok', '--stats', '--stdin', '--supersessions', '--surface', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],
- 'reconcile-links': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--explain', '--follow', '--full', '--help', '--include-frontmatter', '--include-hidden', '--json', '--name-status', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--strategy', '--timeout', '--type'],
- 'reindex': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exclude', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--from-pages', '--help', '--http', '--json', '--lang', '--limit', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--older-than', '--path', '--pglite', '--print', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--type', '--version', '--workers', '--yes'],
- 'reindex-code': ['--abi', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--chunker-debug', '--code', '--compile', '--concurrency', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-rechunk', '--help', '--json', '--judge-model', '--lang', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--no', '--no-embed', '--older-than', '--print', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--serial', '--source', '--stale', '--timeout', '--to', '--version', '--workers', '--yes'],
+ 'quarantine': ['--apply', '--brain', '--force', '--force-rechunk', '--help', '--include-flagged', '--json', '--limit', '--markdown', '--no-embed', '--source', '--source-id', '--stale'],
+ 'recall': ['--access', '--allow-empty', '--as-context', '--asof', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--file', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--query', '--reason', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],
+ 'reconcile-links': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
+ 'reindex': ['--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-embed', '--no-embedding', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--workers', '--yes'],
+ 'reindex-code': ['--background', '--brain', '--concurrency', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--markdown', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embed', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--to', '--workers', '--yes'],
'reindex-frontmatter': ['--brain', '--concurrency', '--dry-run', '--force', '--help', '--json', '--slug-prefix', '--source', '--workers', '--yes'],
- 'reindex-search-vector': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--explain', '--follow', '--help', '--json', '--migrate-only', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--yes'],
- 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--diff-filter', '--dir', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--fast', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--full-history', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--lock', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--name-status', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--orphan', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--short', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
- 'remote': ['--brain', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--mcp-only', '--no-embedding', '--scopes', '--source', '--surface', '--timeout', '--token-ttl'],
- 'repair-jsonb': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--exclude', '--explain', '--fast', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--supabase', '--surface', '--timeout', '--token-ttl', '--url'],
+ 'reindex-search-vector': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--yes'],
+ 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--diff-filter', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
+ 'remote': ['--brain', '--help', '--json', '--mcp-only', '--scopes', '--source', '--timeout'],
+ 'repair-jsonb': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
- 'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--all', '--all-sources', '--allow-unverified-remote', '--app-id', '--app-install', '--app-pem', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--file', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include-hidden', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lang', '--limit', '--local', '--markdown', '--max-age', '--max-cost-usd', '--message', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--no-cron', '--no-embedding', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--porcelain', '--profile', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--repair', '--repo', '--repos', '--restore-only', '--scope', '--scopes', '--secret', '--services', '--set', '--short', '--show-toplevel', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--surface', '--symbol-kind', '--takes-holders', '--thin', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],
- 'resolvers': ['--auto', '--backend', '--brain', '--cost', '--help', '--json', '--source'],
- 'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--check', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--exclude', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-sunset-target', '--from-pages', '--help', '--http', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--max-age', '--model', '--multimodal', '--name', '--nice', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--pace', '--pace-max-concurrency', '--parallel', '--prefix', '--print', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranker', '--reranking', '--resume', '--retarget', '--slugs', '--source', '--stale', '--status', '--surface', '--timeout', '--to', '--token-ttl', '--version', '--yes'],
- 'routing-eval': ['--brain', '--fix', '--help', '--json', '--llm', '--skills-dir', '--source', '--strict', '--verbose'],
- 'salience': ['--brain', '--days', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--kind', '--limit', '--mcp-only', '--no-embedding', '--slug-prefix', '--source', '--surface', '--token-ttl'],
- 'schema': ['--alias', '--aliases', '--all', '--apply', '--as-filing-rules', '--asof', '--brain', '--by-mention', '--compile', '--dims', '--exclude', '--expert', '--expert-routing', '--extractable', '--fast', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--inverse', '--json', '--kind', '--no-embedding', '--no-extract', '--pack', '--page-type', '--pattern', '--pending', '--prefix', '--primitive', '--rebuild', '--reset', '--resolve', '--schema-pack', '--since', '--source', '--source-id', '--stale', '--supersessions', '--surface', '--target-type', '--thin', '--to', '--token-ttl', '--with-db'],
- 'self-upgrade': ['--all', '--brain', '--check', '--check-only', '--dim', '--ff-only', '--force', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],
- 'serve': ['--all', '--bind', '--bound-slug-prefixes', '--brain', '--compile', '--enable-dcr', '--enable-dcr-insecure', '--exclude', '--fast', '--federated-read', '--force', '--from-pages', '--help', '--http', '--json', '--log-full-params', '--name', '--no-embedding', '--no-hard-deadline', '--once', '--parallel', '--port', '--prefix', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stale', '--stdio-idle-timeout', '--suppress', '--suppress-bootstrap-token', '--surface', '--timeout', '--token-ttl', '--yes'],
- 'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--verbose', '--writes-pages', '--writes-to'],
- 'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--chunker-debug', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime', '--max-runtime-min', '--model', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--target-model', '--target-models', '--verbose', '--yes'],
- 'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exclude', '--exit-code', '--fast', '--fix', '--force', '--force-unlock', '--format', '--from', '--from-pages', '--frontmatter', '--full', '--harness', '--help', '--homepage', '--http', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-embedding', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--surface', '--target', '--tier', '--token-ttl', '--trust', '--url', '--verbose', '--verify', '--workspace', '--yes'],
- 'skillpack-check': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--strict', '--timeout', '--yes'],
+ 'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--all', '--allow-unverified-remote', '--app-id', '--app-install', '--app-pem', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--clone-dir', '--confirm-destructive', '--count', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude-standard', '--federated', '--federated-read', '--file', '--force', '--format', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--profile', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--repair', '--repos', '--scope', '--scopes', '--secret', '--services', '--set', '--short', '--show-toplevel', '--source', '--source-id', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],
+ 'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
+ 'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-sunset-target', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--yes'],
+ 'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
+ 'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],
+ 'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--force', '--help', '--inverse', '--json', '--kind', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
+ 'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],
+ 'serve': ['--bind', '--brain', '--enable-dcr', '--enable-dcr-insecure', '--help', '--http', '--json', '--log-full-params', '--port', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--token-ttl', '--yes'],
+ 'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
+ 'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--target-model', '--target-models'],
+ 'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--workspace', '--yes'],
+ 'skillpack-check': ['--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abbrev-ref', '--abort', '--access', '--account', '--all', '--all-sources', '--allow-unverified-remote', '--app-id', '--app-install', '--app-pem', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--file', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include-hidden', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lang', '--limit', '--local', '--markdown', '--max-age', '--max-cost-usd', '--message', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--no-cron', '--no-embedding', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--porcelain', '--profile', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--repair', '--repo', '--repos', '--restore-only', '--scope', '--scopes', '--secret', '--services', '--set', '--short', '--show-toplevel', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--surface', '--symbol-kind', '--takes-holders', '--thin', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],
- 'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--dir', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--full-history', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lock', '--max-age', '--max-rss', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--name-status', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--orphan', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--retry-failed', '--section', '--serial', '--short', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--surface', '--timeout', '--token-ttl', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
- 'storage': ['--brain', '--federated', '--fix', '--help', '--json', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--to'],
- 'sweep': ['--all', '--background', '--batch-limit', '--brain', '--brain-wide-max-cost-usd', '--budget-ms', '--check', '--delete-brain', '--explain', '--federated', '--follow', '--help', '--home', '--json', '--name', '--no-delegate', '--no-federated', '--once', '--parallel', '--path', '--prefix', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--source', '--source-guard', '--stale', '--stats', '--timeout'],
- 'sync': ['--abbrev-ref', '--abi', '--abort', '--account', '--all', '--all-sources', '--allow-empty', '--apply', '--apply-rewrites', '--asof', '--auto', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--clone-dir', '--code', '--column', '--compile', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--lock', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--older-than', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--rebuild-rollup', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--since-created', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token-env', '--token-ttl', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],
- 'takes': ['--accept', '--all', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--exclude', '--expired', '--fast', '--federated', '--file', '--force', '--from-pages', '--help', '--holder', '--http', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-federated', '--offset', '--outcome', '--path', '--pglite', '--print', '--quality', '--reject', '--repo', '--restore-only', '--row', '--semantic', '--serial', '--since', '--slugs', '--sort', '--source', '--source-guard', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--token-ttl', '--unit', '--until', '--value', '--version', '--weight', '--who', '--yes'],
- 'think': ['--all', '--anchor', '--bind', '--bound-slug-prefixes', '--brain', '--calibration-holder', '--compile', '--enable-dcr', '--enable-dcr-insecure', '--exclude', '--explain', '--fast', '--federated', '--federated-read', '--force', '--from-pages', '--help', '--http', '--json', '--log-full-params', '--max-usd', '--mcp-only', '--model', '--name', '--no-embed', '--no-embedding', '--no-federated', '--no-hard-deadline', '--once', '--parallel', '--path', '--port', '--prefix', '--print-admin-token', '--public-url', '--repo', '--restore-only', '--rounds', '--save', '--serial', '--since', '--source', '--source-guard', '--stale', '--stdio-idle-timeout', '--suppress', '--suppress-bootstrap-token', '--surface', '--take', '--timeout', '--token-ttl', '--until', '--with-calibration', '--yes'],
- 'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--check', '--code', '--compile', '--days', '--dry-run', '--embed', '--exclude', '--explain', '--facts', '--fast', '--federated', '--follow', '--force', '--format', '--from-pages', '--full', '--help', '--http', '--include-self', '--json', '--limit', '--markdown', '--max-bytes', '--max-cost-usd', '--no-embedding', '--no-federated', '--path', '--print', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--since', '--since-last', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--surface', '--timeout', '--token-ttl'],
- 'upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--exclude', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pglite', '--print', '--quiet', '--recency', '--repo', '--require-db', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--timeout', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'],
- 'waiting': ['--all', '--brain', '--federated-read', '--help', '--http', '--json', '--source', '--source-guard', '--stale-ok', '--status', '--timeout', '--top', '--type'],
- 'watch': ['--brain', '--exclude', '--fast', '--federated', '--force', '--from-pages', '--help', '--http', '--json', '--max-pages', '--min-confidence', '--no-embedding', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--stats', '--surface', '--token-ttl', '--window-turns'],
- 'whoknows': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--by-mention', '--content', '--date', '--days', '--detail', '--entities', '--exclude', '--explain', '--fast', '--federated', '--file', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale-ok', '--stats', '--stdin', '--surface', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],
- 'ze-switch': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--confirm-reembed', '--dim', '--dry-run', '--explain', '--follow', '--force', '--force-sunset-target', '--help', '--ignore-env-override', '--ignore-missing-key', '--json', '--markdown', '--non-interactive', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranker', '--reset', '--resume', '--source', '--stale', '--timeout', '--to', '--undo', '--yes'],
+ 'sources': ['--abbrev-ref', '--abort', '--access', '--account', '--all', '--allow-unverified-remote', '--app-id', '--app-install', '--app-pem', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--clone-dir', '--confirm-destructive', '--count', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude-standard', '--federated', '--federated-read', '--file', '--force', '--format', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--profile', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--repair', '--repos', '--scope', '--scopes', '--secret', '--services', '--set', '--short', '--show-toplevel', '--source', '--source-id', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],
+ 'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
+ 'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],
+ 'sweep': ['--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
+ 'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reset', '--restore-only', '--resume', '--retry-failed', '--scope', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
+ 'think': ['--anchor', '--bind', '--brain', '--calibration-holder', '--enable-dcr', '--enable-dcr-insecure', '--help', '--http', '--json', '--log-full-params', '--mcp-only', '--model', '--port', '--print-admin-token', '--public-url', '--rounds', '--save', '--since', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--take', '--token-ttl', '--until', '--with-calibration', '--yes'],
+ 'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout'],
+ 'upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--concurrency', '--cost-estimate', '--dim', '--embedding-dimensions', '--embedding-model', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--pglite', '--quiet', '--repo', '--require-db', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--swap-only', '--target', '--to', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],
+ 'waiting': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],
+ 'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
+ 'whoknows': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--url', '--yes'],
+ 'ze-switch': ['--background', '--brain', '--confirm-reembed', '--dim', '--dry-run', '--explain', '--follow', '--force', '--help', '--ignore-env-override', '--ignore-missing-key', '--json', '--markdown', '--non-interactive', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--resume', '--source', '--timeout', '--to', '--undo', '--yes'],
};
diff --git a/src/core/config.ts b/src/core/config.ts
index 6078ed7df0..a1b57a41b4 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -5,6 +5,7 @@ import type { EngineConfig, EmbeddingColumnConfig } from './types.ts';
import { applyDbPlaneReadSideMerge, type DbPlaneEngineReader } from './config-db-merge.ts';
import { loadConfigSnapshot } from './config-snapshot.ts';
import { loadGbrainEnvFile } from './gbrain-env-file.ts';
+import { REMOTE_PRIVATE_PAGES_KEY } from './search/private-visibility.ts';
/**
* Where is the active DB URL coming from? Pure introspection, no connection
@@ -246,14 +247,13 @@ export interface GBrainConfig {
max_usd_per_day?: number;
};
/**
- * v0.42 — keep frontmatter links fresh on the incremental cycle. The cycle's
- * extract phase re-extracts only the slugs a sync changed, but `extractForSlugs`
- * extracts BODY links only — frontmatter (`sources:`/`related:` etc.) link edges
- * silently drift stale when a page's YAML is edited externally and synced in.
- * Set true to also extract frontmatter links per changed page each cycle, keeping
- * externally-edited YAML edges fresh without a full rescan. Default false
- * (preserves current behavior). Read via the file/env/DB plane in the cycle's
- * extract dispatch. Disable/enable with
+ * v0.42 — extract frontmatter (`sources:`/`related:` etc.) link edges too, not
+ * just body links, on every extraction path: the incremental cycle, sync's
+ * inline extract, the GitHub/Google source inline extracts, the extract_stale
+ * minion, `gbrain maintain`, and a flagless stale extract sweep
+ * (src/core/extract-frontmatter.ts resolves it once for all of them).
+ * Keeps externally-edited YAML edges fresh without a full rescan. Default
+ * false (body links only). Read via the file/DB plane, file wins. Enable with
* `gbrain config set autopilot.incremental_extract_include_frontmatter <bool>`.
*/
incremental_extract_include_frontmatter?: boolean;
@@ -264,6 +264,16 @@ export interface GBrainConfig {
/** false disables PII scrubbing before insert. Defaults to true. */
scrub_pii?: boolean;
};
+ /**
+ * Adaptive return-sizing (search/return-policy.ts, default OFF). DB-plane
+ * `search.adaptive_return*` rows nest here via loadConfigWithEngine (file > DB).
+ */
+ search?: {
+ adaptive_return?: boolean;
+ adaptive_return_entity_max?: number;
+ adaptive_return_other_max?: number;
+ adaptive_return_min_keep?: number;
+ };
/**
* v0.42 — self-upgrade settings (file plane; read on the hot path before any
@@ -1200,6 +1210,25 @@ export async function loadConfigWithEngine(
merged.eval = mergedEval;
}
+ // #4605 — search.adaptive_return* DB-plane merge, same class as #1475: the
+ // keys are registered and stored, but return-policy.ts reads the NESTED
+ // `cfg.search.*` of THIS merged object (via hybrid.ts), so without this the
+ // row was accepted, echoed by `config get`, and never read. Strict bool;
+ // caps must be finite numbers (return-policy clamps); file > DB; no empty container.
+ const mergedSearch: NonNullable<GBrainConfig['search']> = { ...(merged.search ?? {}) };
+ const dbAdaptiveReturn = await dbBoolStrict('search.adaptive_return');
+ if (mergedSearch.adaptive_return === undefined && dbAdaptiveReturn !== undefined) {
+ mergedSearch.adaptive_return = dbAdaptiveReturn;
+ }
+ for (const cap of ['adaptive_return_entity_max', 'adaptive_return_other_max', 'adaptive_return_min_keep'] as const) {
+ if (mergedSearch[cap] !== undefined) continue;
+ const n = Number(await dbStr(`search.${cap}`));
+ if (Number.isFinite(n)) mergedSearch[cap] = n;
+ }
+ if (Object.keys(mergedSearch).length > 0) {
+ merged.search = mergedSearch;
+ }
+
// #2119-class read-side merge (also #2137/#4297): provider credentials,
// chat/expansion pins, chat_fallback_chain, flat cycle.* (env > file > DB).
// Served from the SAME snapshot as the reads above when available (zero
@@ -1302,21 +1331,48 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// 30 days; interval clamps to >=1 day at read time (backup/status-file.ts).
'backup.check_enabled',
'backup.check_interval_days',
- // DB-plane (v0.32.3 search modes + related)
+ // DB-plane search-mode knobs: one row per key mode.ts reads (its
+ // KNOB_CONFIG_KEY, hand-mirrored so this module stays import-light; pinned
+ // equal by test/config-search-registry.test.ts). camelCase where the code
+ // reads camelCase (#4605 — snake_case rows here had no reader).
'search.mode',
'search.cache.enabled',
'search.cache.similarity_threshold',
'search.cache.ttl_seconds',
- 'search.token_budget',
+ 'search.intentWeighting',
+ 'search.keywordOrFallback',
+ 'search.tokenBudget',
'search.expansion',
- 'search.intent_weighting',
- 'search.limit_default',
- 'search.mode_upgrade_notice_shown',
+ 'search.searchLimit',
+ 'search.reranker.enabled',
+ 'search.reranker.model',
+ 'search.reranker.top_n_in',
+ 'search.reranker.top_n_out',
+ 'search.reranker.timeout_ms',
+ 'search.floor_ratio',
+ 'search.title_boost',
+ 'search.evidence_cosine_floor',
+ 'search.cross_modal.both_mode_text_weight',
+ 'search.cross_modal.both_mode_image_weight',
+ 'search.image_query.text_refinement_weight',
+ 'search.image_query.image_refinement_weight',
'search.unified_multimodal',
'search.unified_multimodal_only',
'search.cross_modal.llm_intent',
+ 'search.graph_signals',
+ 'search.contextual_retrieval',
+ 'search.contextual_retrieval_disabled',
+ 'search.relational_retrieval',
+ 'search.relational_retrieval_depth',
+ // DB-plane search.* singletons read directly via engine.getConfig
+ // (commands/upgrade.ts, ops/image.ts, ops/search.ts, private-visibility.ts,
+ // last-retrieved.ts).
+ 'search.mode_upgrade_notice_shown',
'search.image_query.max_bytes',
- 'search.reranker.enabled',
+ 'search.image_query.daily_budget_usd_per_client',
+ 'search.image_query.remote_max_bytes',
+ 'search.mcp_keyword_only',
+ REMOTE_PRIVATE_PAGES_KEY,
'search.track_retrieval',
// #4415: per-brain query-intent pattern extensions (JSON bank→regex[]),
// merged over the shipped banks in src/core/search/query-intent.ts.
@@ -1542,6 +1598,10 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// reconcile-links, and sweep. The documented off-switch is `gbrain config
// set auto_link false` — same unregistered-key class as auto_chronicle.
'auto_link',
+ // #4987: the write-path timeline extractor's off switch (read by
+ // isAutoTimelineEnabled); registered so `gbrain config set auto_timeline off`
+ // works without --force, as the compiled-truth guide documents.
+ 'auto_timeline',
// v0.46.3: the provider_sunset doctor check's own suppression escape hatch
// (doctor.ts) and docs/guides/embedding-migration.md both document
// `gbrain config set doctor.suppress_provider_sunset true`, but the key was
@@ -1571,6 +1631,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// Registering it here is what makes `gbrain config set sync.exclude ...`
// work — the operator path to the feature (unregistered-key class).
'sync.exclude',
+ // #4901: the dot-directory WAIVER's persisted twin (unioned with the per-call
+ // include-hidden flag, which bulk sync refuses); registered so `config set` accepts it.
+ 'sync.include_hidden',
// #2179: clamp window for DCR-requested per-client token TTLs. Read by
// `gbrain serve --http` at startup; unset min defaults to 300s, unset max
// defaults fail-closed to max(--token-ttl, min).
@@ -1589,6 +1652,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// Read by performSync + runImport summary aggregation; 'false'/'0'/'off'
// silences both surfaces (schema lint rules stay active).
'schema.type_warnings',
+ // #4795 reindex-search-vector marker (doctor fts_reindex_incomplete reads it); `config unset` is the escape hatch.
+ 'fts.reindex_in_progress',
];
/**
diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.ts
index 4966cbc8df..53c5fa5e50 100644
--- a/src/core/context/turn-context.ts
+++ b/src/core/context/turn-context.ts
@@ -35,6 +35,7 @@ import {
import { volunteerContext, type VolunteeredPage } from './volunteer.ts';
import { getBrainHotMemoryMeta } from '../facts/meta-hook.ts';
import { buildEntityCard, type EntityCard, type EntityOpenThread } from '../verbs/entity-card.ts';
+import { estimateTokens } from '../search/token-budget.ts';
/**
* v0.45.7 ambient recall (issue #1). The per-turn assembler is extended into the
@@ -646,6 +647,31 @@ export function assembleDeltaContext(
* does not enforce maxBytes, so the section bounds itself). */
export const CHECKPOINT_LINKS_RENDER_CAP = 10;
+// #4761: ONE template per item, shared by the renderers below and the budget
+// packers in ops/facts.ts — the packer prices exactly the bytes the renderer
+// emits, so `text` honors budget_tokens instead of overshooting it.
+export const renderCardLine = (c: EntityCard): string =>
+ `- **${c.entity.title}** → \`${c.entity.slug}\`${c.summary ? ` — ${c.summary}` : ''} (use get_page/entity before relying on details)`;
+export const renderThreadLine = (t: EntityOpenThread): string =>
+ `- [${t.kind}] ${t.text}${t.date ? ` (${t.date})` : ''}`;
+export const renderFactLine = (f: TurnContextFact): string =>
+ `- ${f.fact}${f.entity_slug ? ` [${f.entity_slug}]` : ''} (${f.confidence.toFixed(2)})`;
+export const renderPageLine = (p: DeltaPage): string => `- **${p.title}** → \`${p.slug}\` (${p.updated_at})`;
+
+const PACK_HEADERS = ['## Standing entities', '## Open threads', '## Hot memory (recent facts)'] as const;
+const deltaHeaders = (since?: string): readonly [string, string, string] => {
+ const s = since ? ` since ${since}` : '';
+ return [`## Pages changed${s}`, `## New facts${s}`, `## Thread updates${s}`];
+};
+/** Tokens the envelope + every section header cost once rendered (each header
+ * rides a blank line before it). The packers reserve this up front so
+ * estimateTokens(text) <= budget_tokens holds whenever any item fits; a
+ * section that ends up empty is over-reserved — the safe direction. */
+const headerCost = (headers: readonly string[]): number =>
+ estimateTokens([TURN_CONTEXT_ENVELOPE, ...headers.flatMap((h) => ['', h])].join('\n') + '\n');
+export const packHeaderCost = (): number => headerCost(PACK_HEADERS);
+export const deltaHeaderCost = (since?: string): number => headerCost(deltaHeaders(since));
+
export function renderPack(
cards: EntityCard[],
openThreads: EntityOpenThread[],
@@ -665,27 +691,9 @@ export function renderPack(
're-pull with get_page. Trust these links over the compaction summary.',
);
}
- if (cards.length) {
- lines.push('', '## Standing entities');
- for (const c of cards) {
- const syn = c.summary ? ` — ${c.summary}` : '';
- lines.push(`- **${c.entity.title}** → \`${c.entity.slug}\`${syn} (use get_page/entity before relying on details)`);
- }
- }
- if (openThreads.length) {
- lines.push('', '## Open threads');
- for (const t of openThreads) {
- const d = t.date ? ` (${t.date})` : '';
- lines.push(`- [${t.kind}] ${t.text}${d}`);
- }
- }
- if (facts.length) {
- lines.push('', '## Hot memory (recent facts)');
- for (const f of facts) {
- const ent = f.entity_slug ? ` [${f.entity_slug}]` : '';
- lines.push(`- ${f.fact}${ent} (${f.confidence.toFixed(2)})`);
- }
- }
+ if (cards.length) lines.push('', PACK_HEADERS[0], ...cards.map(renderCardLine));
+ if (openThreads.length) lines.push('', PACK_HEADERS[1], ...openThreads.map(renderThreadLine));
+ if (facts.length) lines.push('', PACK_HEADERS[2], ...facts.map(renderFactLine));
return lines.join('\n');
}
@@ -698,24 +706,9 @@ export function renderDelta(
): string {
if (!pages.length && !facts.length && !threads.length) return '';
const lines: string[] = [TURN_CONTEXT_ENVELOPE];
- const sinceNote = since ? ` since ${since}` : '';
- if (pages.length) {
- lines.push('', `## Pages changed${sinceNote}`);
- for (const p of pages) lines.push(`- **${p.title}** → \`${p.slug}\` (${p.updated_at})`);
- }
- if (facts.length) {
- lines.push('', `## New facts${sinceNote}`);
- for (const f of facts) {
- const ent = f.entity_slug ? ` [${f.entity_slug}]` : '';
- lines.push(`- ${f.fact}${ent} (${f.confidence.toFixed(2)})`);
- }
- }
- if (threads.length) {
- lines.push('', `## Thread updates${sinceNote}`);
- for (const t of threads) {
- const d = t.date ? ` (${t.date})` : '';
- lines.push(`- [${t.kind}] ${t.text}${d}`);
- }
- }
+ const [pagesHeader, factsHeader, threadsHeader] = deltaHeaders(since);
+ if (pages.length) lines.push('', pagesHeader, ...pages.map(renderPageLine));
+ if (facts.length) lines.push('', factsHeader, ...facts.map(renderFactLine));
+ if (threads.length) lines.push('', threadsHeader, ...threads.map(renderThreadLine));
return lines.join('\n');
}
diff --git a/src/core/conversation-parser/parse.ts b/src/core/conversation-parser/parse.ts
index 38ae0272e9..714287e612 100644
--- a/src/core/conversation-parser/parse.ts
+++ b/src/core/conversation-parser/parse.ts
@@ -325,7 +325,7 @@ export function applyPattern(
body: string,
entry: PatternEntry,
dateCtx: DateContext,
- diag?: { unrecognized_headings: string[] },
+ diag?: { unrecognized_headings: string[]; date_fallback_count?: number },
): MatchedMessage[] {
if (!body) return [];
const out: MatchedMessage[] = [];
@@ -400,8 +400,17 @@ export function applyPattern(
const m = entry.regex.exec(line);
if (m) {
- const iso = buildIso(m, entry, runningCtx);
- if (iso === null) continue; // reconstruction failed; skip line
+ let iso = buildIso(m, entry, runningCtx);
+ if (iso === null) {
+ // Reconstruction failed (e.g. a localized month name). Dropping the
+ // anchor would fold this message's body into the PREVIOUS speaker
+ // (silent misattribution, phase still regex_match), so open the
+ // message anyway and count it. Inherit the previous anchor's
+ // timestamp so ordering and downstream segment continuity survive;
+ // midnight of the page date only when this is the first anchor.
+ iso = out[out.length - 1]?.timestamp ?? `${runningCtx.fallbackDate}T00:00:00Z`;
+ if (diag) diag.date_fallback_count = (diag.date_fallback_count ?? 0) + 1;
+ }
const rawSpeaker = m[entry.captures.speaker_group] ?? '';
const speaker = cleanSpeaker(rawSpeaker, entry.speaker_clean);
let text = '';
@@ -660,7 +669,7 @@ export function parseConversation(
};
}
- const diag = { unrecognized_headings: [] as string[] };
+ const diag = { unrecognized_headings: [] as string[], date_fallback_count: 0 };
const messages = applyPattern(body, top.entry, dateCtx, diag);
// Timezone warning surface (D19).
@@ -679,6 +688,8 @@ export function parseConversation(
matched_pattern_id: top.entry.id,
patterns_scored: patternsScored,
timezone_warning,
+ // Anchors rescued onto a fallback timestamp; undefined when zero.
+ date_fallback_count: diag.date_fallback_count || undefined,
// #4136 — populated unconditionally (NOT behind opts.diagnostic): the
// extractor's decline gate depends on it. Undefined when empty.
unrecognized_headings:
diff --git a/src/core/conversation-parser/types.ts b/src/core/conversation-parser/types.ts
index 7b1e4c2a82..410107e7a5 100644
--- a/src/core/conversation-parser/types.ts
+++ b/src/core/conversation-parser/types.ts
@@ -86,6 +86,13 @@ export interface ParseResult {
* decline (the parser stays purely descriptive). Undefined when empty so
* healthy-page JSON output is byte-identical. */
unrecognized_headings?: string[];
+ /** Matched anchor lines whose date could not be reconstructed (localized
+ * month names, malformed digits). Each still opens its own message —
+ * inheriting the previous anchor's timestamp, or the page's fallback date
+ * at midnight for the first — so its body is never folded into the
+ * previous speaker. Undefined when zero so healthy-page JSON output is
+ * byte-identical. */
+ date_fallback_count?: number;
}
/**
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index bad322456e..0e3241c112 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -52,6 +52,7 @@ import { getCliOptions, cliOptsToProgressOptions } from './cli-options.ts';
import { tryAcquireDbLock, reapDeadHolderLocks, LockStolenError, type DbLockHandle } from './db-lock.ts';
import { assertValidSourceId } from './source-id.ts';
import { PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, type PhaseScope } from './cycle/phase-scope.ts';
+import { assertEmbedNotStalled } from './embed-stall.ts';
export { PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, type PhaseScope } from './cycle/phase-scope.ts';
@@ -1355,21 +1356,11 @@ async function runPhaseExtract(
): Promise<PhaseResult> {
try {
const { runExtractCore } = await import('../commands/extract.ts');
- const { loadConfig } = await import('./config.ts');
- // Default off: the incremental cycle extracts body links only unless the
- // operator opts in to keeping externally-edited frontmatter links fresh too.
- // Both planes, file wins (env > file > DB precedence, per loadConfigWithEngine):
- // `gbrain config set autopilot.incremental_extract_include_frontmatter true`
- // writes the DB plane (engine.setConfig), so a file-plane-only read here
- // would make the documented enable command a silent no-op (#2120 class).
- const fileVal = loadConfig()?.autopilot?.incremental_extract_include_frontmatter;
- let includeFrontmatter = fileVal === true;
- if (fileVal === undefined) {
- try {
- includeFrontmatter =
- (await engine.getConfig('autopilot.incremental_extract_include_frontmatter')) === 'true';
- } catch { /* config table unreadable → default off */ }
- }
+ const { resolveIncludeFrontmatter } = await import('./extract-frontmatter.ts');
+ // Shared resolver (file plane wins, then DB plane, fail-closed) so this
+ // cycle, sync's inline extract, the extract_stale minion and maintain all
+ // answer the same way; `1`/`yes`/`on` now count as true here too.
+ const includeFrontmatter = await resolveIncludeFrontmatter(engine);
// Extract is read-mostly against the filesystem + write to links table.
// Honor dryRun by skipping with a 'skipped' entry: extract doesn't have
// a clean dry-run mode today and runCycle should be honest about it.
@@ -1633,6 +1624,7 @@ async function runPhaseEmbed(engine: BrainEngine, dryRun: boolean, signal?: Abor
// #394: quiet — the cycle reports embed counts via its own PhaseResult;
// raw `[dry-run] Would embed ...` stdout lines would corrupt `dream --json`.
const result = await runEmbedCore(engine, { stale: true, dryRun, signal, quiet: true });
+ assertEmbedNotStalled(result); // #4599: a watchdog-aborted drain is a failed phase, not 'ok'
const embeddedCount = dryRun ? result.would_embed : result.embedded;
return {
phase: 'embed',
@@ -2109,9 +2101,10 @@ export async function runCycle(
}) as Promise<T>;
};
let lockStolenAbort = false;
- // Raced variant for the 5 long phases (synthesize / extract_atoms / patterns
- // / synthesize_concepts / consolidate): even where their opts now carry the
- // signal (#4077 synthesize/patterns, consolidate), a steal must be able to
+ // Raced variant for the long phases (synthesize / extract_atoms / patterns
+ // / synthesize_concepts / recompute_emotional_weight / consolidate): even
+ // where their opts now carry the signal (#4077 synthesize/patterns,
+ // consolidate, #4797 recompute), a steal must be able to
// stop the WAIT while the phase unwinds cooperatively; extract_atoms and
// synthesize_concepts still can't carry one (W6). Steal-free cycles behave
// byte-identically to timePhase.
@@ -2570,10 +2563,16 @@ export async function runCycle(
...(synthesizeWrittenSlugs ?? []),
]))
: undefined;
- const { result, duration_ms } = await timePhase(() =>
+ // #4797: raced + signal + lock-refresh + progress, like consolidate —
+ // the full-brain write is sliced inside the phase; these hooks fire
+ // between slices so a long first run stays observable and abortable.
+ const { result, duration_ms } = await racedTimePhase(() =>
runPhaseRecomputeEmotionalWeight(engine, {
dryRun,
affectedSlugs: incremental,
+ signal: cycleSignal,
+ yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),
+ onProgress: () => progress.tick(),
}),
);
result.duration_ms = duration_ms;
@@ -2652,7 +2651,7 @@ export async function runCycle(
// #4102: `once` bypasses the cycle.propose_takes.enabled off switch
// for `gbrain dream --phase propose_takes --once` (same semantics as
// conversation_facts_backfill / enrich_thin above).
- const { result, duration_ms } = await timePhase(() => runPhaseProposeTakes(calibrationCtx, { repoPath: brainDir ?? undefined, deadlineAtMs: opts.deadlineAtMs ?? null, once: opts.onceForPhase === 'propose_takes' }) as Promise<PhaseResult>);
+ const { result, duration_ms } = await timePhase(() => runPhaseProposeTakes(calibrationCtx, { dryRun, repoPath: brainDir ?? undefined, deadlineAtMs: opts.deadlineAtMs ?? null, once: opts.onceForPhase === 'propose_takes' }) as Promise<PhaseResult>);
result.duration_ms = duration_ms;
phaseResults.push(result);
progress.finish();
@@ -2663,7 +2662,7 @@ export async function runCycle(
checkAborted(cycleSignal);
progress.start('cycle.grade_takes');
const { runPhaseGradeTakes } = await import('./cycle/grade-takes.ts');
- const { result, duration_ms } = await timePhase(() => runPhaseGradeTakes(calibrationCtx, { deadlineAtMs: opts.deadlineAtMs ?? null }) as Promise<PhaseResult>);
+ const { result, duration_ms } = await timePhase(() => runPhaseGradeTakes(calibrationCtx, { dryRun, deadlineAtMs: opts.deadlineAtMs ?? null }) as Promise<PhaseResult>);
result.duration_ms = duration_ms;
phaseResults.push(result);
progress.finish();
@@ -2674,7 +2673,7 @@ export async function runCycle(
checkAborted(cycleSignal);
progress.start('cycle.calibration_profile');
const { runPhaseCalibrationProfile } = await import('./cycle/calibration-profile.ts');
- const { result, duration_ms } = await timePhase(() => runPhaseCalibrationProfile(calibrationCtx, { deadlineAtMs: opts.deadlineAtMs ?? null }) as Promise<PhaseResult>);
+ const { result, duration_ms } = await timePhase(() => runPhaseCalibrationProfile(calibrationCtx, { dryRun, deadlineAtMs: opts.deadlineAtMs ?? null }) as Promise<PhaseResult>);
result.duration_ms = duration_ms;
phaseResults.push(result);
progress.finish();
diff --git a/src/core/cycle/base-phase.ts b/src/core/cycle/base-phase.ts
index 89f8ebd058..cdfb06f9bd 100644
--- a/src/core/cycle/base-phase.ts
+++ b/src/core/cycle/base-phase.ts
@@ -49,7 +49,12 @@ export interface ScopedReadOpts {
export interface BasePhaseOpts {
/** Optional progress reporter. Phases call tick() / start() through the base. */
reporter?: ProgressReporter;
- /** Dry-run mode propagated from cycle opts. Subclasses honor this in process(). */
+ /**
+ * Dry-run mode propagated from cycle opts. Honored in run(): the phase is
+ * skipped (`status: 'skipped'`, `reason: 'no_dry_run_support'`) before
+ * process() is called — every subclass bills LLM calls and INSERTs rows and
+ * has no dry-run path of its own (#4823). `ctx.dryRun` is honored too.
+ */
dryRun?: boolean;
/** Optional explicit budget override in USD. Otherwise base reads config. */
budgetUsd?: number;
@@ -198,6 +203,21 @@ export abstract class BaseCyclePhase {
// to thread this would have been the v0.34.1 leak class. Now structural.
const scope = sourceScopeOpts(ctx);
+ // `--dry-run` promises "preview without writing". No subclass has a
+ // dry-run path (LLM calls + INSERT take_proposals / take_grade_cache /
+ // calibration_profiles), so skip here — one guard for all three, the same
+ // shape extract / resolve_symbol_edges use (#4823). Read both channels so
+ // a caller that forgets to thread opts.dryRun still can't bill.
+ if (opts.dryRun || ctx.dryRun === true) {
+ return {
+ phase: this.name,
+ status: 'skipped',
+ duration_ms: Date.now() - t0,
+ summary: `dry-run: ${this.name} skipped (LLM calls + DB writes)`,
+ details: { dryRun: true, reason: 'no_dry_run_support' },
+ };
+ }
+
// Budget meter construction. The default path reads config; tests inject.
if (!opts.meter) {
const budgetUsd = this.resolveBudgetUsd(ctx, opts);
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index cb3d1da3cd..507ccab0d3 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -89,6 +89,11 @@ interface ExistingPageFact {
// drifted and re-heals through the wipe+reinsert fallback.
superseded_by: number | string | null;
expired_at: Date | string | null;
+ // #4870 — fence cells the reconcile must honor. Both columns are NOT NULL
+ // enums whose CHECK matches the fence's validated values, so a plain
+ // equality compare cannot churn on case/format/NULL.
+ visibility: string;
+ notability: string;
}
function factContentKey(fact: string, source: string | null | undefined): string {
@@ -218,7 +223,7 @@ async function listExistingFactsForPage(
sourceId: string,
): Promise<ExistingPageFact[]> {
return engine.executeRaw<ExistingPageFact>(
- `SELECT id, fact, source, row_num, superseded_by, expired_at
+ `SELECT id, fact, source, row_num, superseded_by, expired_at, visibility, notability
FROM facts
WHERE source_id = $1
AND source_markdown_slug = $2
@@ -702,13 +707,26 @@ export async function runExtractFacts(
const dbTargetId = f.superseded_by == null ? null : Number(f.superseded_by);
return resolvedTargetId !== dbTargetId;
});
+ // #4870 — a visibility / notability edit on an existing row leaves the
+ // content key, row_num and struck-state untouched, so none of the terms
+ // above fire and the edit was a silent no-op. Compare the two fence
+ // cells the parser already validates; the wipe+reinsert transports them.
+ // ponytail: confidence is skipped — it is a REAL column, so an equality
+ // compare would need the fence formatter to avoid float-noise churn;
+ // route it through formatConfidence if a confidence-edit report lands.
+ const hasAttributeDrift = existing.some(f => {
+ const desired = desiredByKey.get(factContentKey(f.fact, f.source));
+ return desired !== undefined
+ && (desired.visibility !== f.visibility || desired.notability !== f.notability);
+ });
if (
existing.length === extracted.length &&
!hasStaleExisting &&
!hasDuplicateExisting &&
!hasRowNumDrift &&
- !hasSupersessionDrift
+ !hasSupersessionDrift &&
+ !hasAttributeDrift
) {
continue;
}
@@ -724,7 +742,7 @@ export async function runExtractFacts(
// conversation facts (#1928), and soft-expired legacy rows (#2646)
// survive.
let deleteForPageFirst: { slug: string; excludeSourcePrefixes: string[]; preserveExpiredLegacy: boolean } | undefined;
- if (hasStaleExisting || hasDuplicateExisting || hasRowNumDrift || hasSupersessionDrift) {
+ if (hasStaleExisting || hasDuplicateExisting || hasRowNumDrift || hasSupersessionDrift || hasAttributeDrift) {
deleteForPageFirst = { slug, excludeSourcePrefixes: ['cli:'], preserveExpiredLegacy: true };
toInsert = extracted;
}
diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts
index 3e31254897..4d75cb7e4d 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -54,8 +54,10 @@ export interface PatternsPhaseOpts {
yieldDuringPhase?: () => Promise<void>;
/**
* issue #2860 — `gbrain dream --phase patterns --once`. Bypasses the
- * `dream.patterns.enabled` gate for THIS call only; never reads or
- * writes config.
+ * `dream.patterns.enabled` gate AND the #4879 no-new-evidence gate for
+ * THIS call only; never reads or writes the `.enabled` key. A completed
+ * forced run still stamps `dream.patterns.last_evidence_ts` so the next
+ * autopilot tick doesn't re-pay for evidence the operator just consumed.
*/
once?: boolean;
/**
@@ -154,6 +156,25 @@ export async function runPhasePatterns(
);
}
+ // #4879: evidence watermark. Autopilot re-dispatches this phase every
+ // global tick (~60 min); without a consumed-marker it re-paid a Sonnet
+ // run on the same unchanged reflections and minted near-duplicate pattern
+ // pages. Skip when no reflection is newer than the evidence the last
+ // COMPLETED run consumed (rows are ORDER BY updated_at DESC, so [0] is
+ // the high-water mark). Absent/unparseable stamp fails open, same as
+ // synthesize's checkCooldown; `--once` forces past it.
+ const newestEvidenceMs = reflections[0].updatedAt.getTime();
+ if (!opts.once) {
+ const stampMs = Date.parse((await engine.getConfig(LAST_EVIDENCE_KEY)) ?? '');
+ if (Number.isFinite(stampMs) && newestEvidenceMs <= stampMs) {
+ return skipped(
+ 'no_new_evidence',
+ `${reflections.length} reflections in window, none newer than last completed run ` +
+ `(${new Date(stampMs).toISOString()}); pass --once to force`,
+ );
+ }
+ }
+
if (opts.dryRun) {
return ok(`dry-run: would detect patterns over ${reflections.length} reflections`, {
reflections_considered: reflections.length,
@@ -356,6 +377,13 @@ export async function runPhasePatterns(
};
}
+ // #4879: stamp the EVIDENCE watermark (not now()) only on a completed
+ // child — fail/warn/timeout above must retry next tick. A reflection
+ // edited between gather and here has updated_at > stamp, so the next run
+ // still fires. Zero writes stamps too: the model saw this evidence and
+ // named nothing; re-running it is exactly the spend bug.
+ await engine.setConfig(LAST_EVIDENCE_KEY, new Date(newestEvidenceMs).toISOString());
+
return ok(`${writtenRefs.length} pattern page(s) written/updated (${outcome})`, details);
} catch (e) {
return failed(makeError('InternalError', 'PATTERNS_PHASE_FAIL',
@@ -468,10 +496,16 @@ async function loadPatternsConfig(engine: BrainEngine): Promise<PatternsConfig>
// ── Reflection gathering ─────────────────────────────────────────────
+/** #4879: config-plane STATE row (not a user knob) — ISO of the newest
+ * reflection `updated_at` the last completed run consumed. Same class as
+ * `dream.synthesize.last_completion_ts`; `dream.` is already a known prefix. */
+const LAST_EVIDENCE_KEY = 'dream.patterns.last_evidence_ts';
+
interface ReflectionRef {
slug: string;
title: string;
excerpt: string;
+ updatedAt: Date;
}
async function gatherReflections(
@@ -482,8 +516,10 @@ async function gatherReflections(
const since = new Date(Date.now() - lookbackDays * 24 * 60 * 60 * 1000).toISOString();
// Reflections live under the configured source slug prefix (bound as a
// parameter; see PatternsConfig.sourceSlugPrefix / dream.patterns.source_slug_prefix).
- const rows = await engine.executeRaw<{ slug: string; title: string | null; compiled_truth: string | null }>(
- `SELECT slug, title, compiled_truth
+ const rows = await engine.executeRaw<{
+ slug: string; title: string | null; compiled_truth: string | null; updated_at: string | Date;
+ }>(
+ `SELECT slug, title, compiled_truth, updated_at
FROM pages
WHERE slug LIKE $2
AND updated_at >= $1::timestamptz
@@ -494,6 +530,9 @@ async function gatherReflections(
return rows.map(r => ({
slug: r.slug,
title: r.title ?? r.slug,
+ // Both engines hand timestamptz back as Date; wrap so a string-returning
+ // driver shape still parses (backfill-registry.ts precedent).
+ updatedAt: new Date(r.updated_at),
// A raw UTF-16 slice can split an astral character at the boundary and
// leave a lone surrogate. Postgres rejects that when the prompt is bound
// into the minion job's JSONB payload. Use the shared safe truncator so a
diff --git a/src/core/cycle/recompute-emotional-weight.ts b/src/core/cycle/recompute-emotional-weight.ts
index 4a96d6fbaa..a947078d37 100644
--- a/src/core/cycle/recompute-emotional-weight.ts
+++ b/src/core/cycle/recompute-emotional-weight.ts
@@ -3,11 +3,16 @@
* it sees the union of (sync-touched, synthesize-written) pages with fresh
* tag + take state. Pure deterministic computation; no LLM calls.
*
- * Two SQL round-trips total regardless of brain size (codex C4#3, C4#4):
+ * One read plus bounded writes (codex C4#3, C4#4; #4797):
* 1. batchLoadEmotionalInputs — single CTE-shaped read with per-table
* pre-aggregates so a page × N tags × M takes never produces N×M rows.
* 2. setEmotionalWeightBatch — composite-keyed (slug, source_id) UPDATE
- * FROM unnest so multi-source brains can't get cross-source fan-out.
+ * FROM unnest so multi-source brains can't get cross-source fan-out,
+ * issued in slices of WRITE_SLICE rows. PGLite runs each statement
+ * synchronously on the main thread, so ONE full-brain UPDATE blocks the
+ * lock refresher, progress, and SIGTERM for its whole duration; between
+ * slices the phase checks the abort signal, refreshes the cycle lock
+ * (yieldDuringPhase), ticks progress, and yields a macrotask.
*
* In incremental mode (`affectedSlugs` non-empty), only those pages are
* touched. In full mode (`affectedSlugs` undefined or null) every page in
@@ -35,10 +40,19 @@ export interface RecomputeEmotionalWeightOpts {
affectedSlugs?: string[];
/** GBrain config for high_emotion_tags + user_holder overrides. */
config?: GBrainConfig;
+ /** Cooperative abort — checked before every write slice. */
+ signal?: AbortSignal;
+ /** Cycle-lock refresh / steal detection hook, awaited between write slices. */
+ yieldDuringPhase?: () => Promise<void>;
+ /** Progress tick, fired after every write slice. */
+ onProgress?: () => void;
}
+/** Rows per UPDATE statement. Bounds how long PGLite wedges the main thread. */
+const WRITE_SLICE = 1000;
+
export interface RecomputeEmotionalWeightResult extends PhaseResult {
- /** Number of pages whose emotional_weight was (re)computed. */
+ /** Number of pages whose emotional_weight was (re)computed (evaluated). */
pages_recomputed: number;
}
@@ -91,11 +105,29 @@ export async function runPhaseRecomputeEmotionalWeight(
}, start);
}
- const updated = await engine.setEmotionalWeightBatch(writes);
+ let updated = 0;
+ for (let i = 0; i < writes.length; i += WRITE_SLICE) {
+ if (opts.signal?.aborted) {
+ const reason = opts.signal.reason instanceof Error
+ ? opts.signal.reason.message
+ : String(opts.signal.reason || 'aborted');
+ throw new Error(`recompute_emotional_weight aborted: ${reason}`);
+ }
+ updated += await engine.setEmotionalWeightBatch(writes.slice(i, i + WRITE_SLICE));
+ opts.onProgress?.();
+ if (i + WRITE_SLICE < writes.length) {
+ try { await opts.yieldDuringPhase?.(); } catch { /* keepalive errors non-fatal */ }
+ // Macrotask yield: PGLite resolves queries on a microtask chain, so a
+ // tight loop of statements still starves the timers phase (same reason
+ // GBRAIN_SYNC_YIELD_EVERY uses setTimeout(0), not setImmediate).
+ await new Promise(r => setTimeout(r, 0));
+ }
+ }
- return result('ok', `recompute_emotional_weight (${updated} pages)`, updated, {
+ return result('ok', `recompute_emotional_weight (${updated} updated / ${writes.length} evaluated)`, writes.length, {
mode: opts.affectedSlugs ? 'incremental' : 'full',
- pages_recomputed: updated,
+ pages_recomputed: writes.length,
+ pages_updated: updated,
}, start);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index ccf943e54e..01edbad3ca 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -73,6 +73,9 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'cycle_freshness',
'dangling_aliases',
'effective_date_health',
+ // #4795 — reindex-search-vector marker still set: keyword index split
+ // across two tokenizers until the resumed run finishes.
+ 'fts_reindex_incomplete',
'embed_staleness',
'embedding_column_registry',
'embedding_env_override',
@@ -222,6 +225,9 @@ export const META_CHECK_NAMES: ReadonlySet<string> = new Set([
'cycle_phase_scope',
'default_source_local_path',
'eval_capture',
+ // #4613 — links_link_source_check CHECK shape: schema coherence healed by
+ // `gbrain apply-migrations` (sibling of pages_upsert_arbiter).
+ 'links_link_source_check',
'minions_migration',
'multi_source_drift',
'pack_upgrade_available',
diff --git a/src/core/embedding-pricing.ts b/src/core/embedding-pricing.ts
index 6e71e8d47f..63c981d916 100644
--- a/src/core/embedding-pricing.ts
+++ b/src/core/embedding-pricing.ts
@@ -79,6 +79,18 @@ export const EMBEDDING_PRICING: Record<string, EmbeddingPricing> = {
// Perplexity (https://docs.perplexity.ai/getting-started/pricing, verified 2026-07-28)
'perplexity:pplx-embed-v1-0.6b': { pricePerMTok: 0.004 },
'perplexity:pplx-embed-v1-4b': { pricePerMTok: 0.03 },
+ // Google (https://ai.google.dev/gemini-api/docs/pricing, verified 2026-09-07).
+ // #4344 class: both models are in the hosted recipe list
+ // (src/core/ai/recipes/google.ts) but had no rows, so cost estimates read
+ // "unavailable" for every brain on them — including the OpenRouter-routed
+ // ones, since `openrouter:google/gemini-embedding-001` resolves here through
+ // the #2504 nested-vendor retry. The two rates differ, so one shared row
+ // would misprice whichever model it didn't come from.
+ 'google:gemini-embedding-001': { pricePerMTok: 0.15 },
+ // gemini-embedding-2 is multimodal and priced per input kind ($0.45/1M image,
+ // $6.50 audio, $12.00 video). Same convention as voyage-multimodal-3 above:
+ // the TEXT rate is the row, pixel/audio token pricing is out of scope here.
+ 'google:gemini-embedding-2': { pricePerMTok: 0.20 },
};
export type PriceLookupResult =
diff --git a/src/core/engine.ts b/src/core/engine.ts
index b6969097bb..737d025144 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -2412,11 +2412,11 @@ export interface BrainEngine {
/**
* v0.35.5 — lossless DB-side migration of fact rows from one slug to
* another within a single source. UPDATEs `entity_slug` and
- * `source_markdown_slug` on every active fact row whose
- * `source_markdown_slug` matches the phantom slug. Every other column
- * (embedding, valid_from, valid_until, kind, notability, confidence,
- * source_session, status, etc.) is preserved verbatim — codex #3 fix
- * for the writeFactsToFence lossy-migration trap.
+ * `source_markdown_slug` on every active fact row keyed on the phantom
+ * slug, and offsets `row_num` past the canonical page's current
+ * MAX(row_num) — all rows incl. expired, since partial idx_facts_fence_key
+ * only excludes NULL — so overlapping fence rows never collide (#4558);
+ * NULL row_num stays NULL. Every other column is preserved verbatim.
*
* Idempotent: re-run after success finds no rows to update and returns
* `{migrated: 0}`. Hard-deletes are out of scope; the caller wipes the
@@ -2531,13 +2531,13 @@ export interface BrainEngine {
): Promise<CodeEdgeResult[]>;
/**
- * "What does this symbol call?" Returns edges from chunks whose
- * from_symbol_qualified = qualifiedName. Same source-scoping semantics
- * as getCallersOf.
+ * "What does this symbol call?" Edges from chunks whose from_symbol_qualified
+ * = qualifiedName; same source scoping as getCallersOf. opts.bareFallback (#4670):
+ * zero-row miss + delimiter-free input re-keys on content_chunks.symbol_name.
*/
getCalleesOf(
qualifiedName: string,
- opts?: { sourceId?: string; allSources?: boolean; limit?: number },
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean },
): Promise<CodeEdgeResult[]>;
/**
@@ -2602,8 +2602,8 @@ export interface BrainEngine {
* source — a slug-only UPDATE would fan out across sources, the same bug
* that the v0.18.0 link batches fixed for cross-source edges.
*
- * Returns the count of rows actually updated. Pages whose `(slug, source_id)`
- * tuple doesn't exist (race with delete) are silently skipped.
+ * Rewrites ONLY rows whose stored weight differs (`IS DISTINCT FROM`, #4797) —
+ * returns rows CHANGED; missing `(slug, source_id)` tuples are skipped.
*/
setEmotionalWeightBatch(rows: EmotionalWeightWriteRow[]): Promise<number>;
diff --git a/src/core/enrichment/completeness.ts b/src/core/enrichment/completeness.ts
index b5e7997aa7..692d8846ef 100644
--- a/src/core/enrichment/completeness.ts
+++ b/src/core/enrichment/completeness.ts
@@ -82,7 +82,7 @@ function hasBacklinkHint(page: Page): number {
// (we stay pure here). If the rubric needs engine-backed signal, a later
// variant of scorer can inject backlinkCount.
const body = page.compiled_truth ?? '';
- const wikiLinks = (body.match(/\[[^\]]+\]\([^)]*\.md\)/g) ?? []).length;
+ const wikiLinks = (body.match(/\[[^\]]+\]\([^)]*\.md(?:#[^)]*)?\)/g) ?? []).length;
if (wikiLinks === 0) return 0;
if (wikiLinks >= 3) return 1;
return wikiLinks / 3;
diff --git a/src/core/extract-frontmatter.ts b/src/core/extract-frontmatter.ts
new file mode 100644
index 0000000000..e1088ed621
--- /dev/null
+++ b/src/core/extract-frontmatter.ts
@@ -0,0 +1,44 @@
+/**
+ * `autopilot.incremental_extract_include_frontmatter` — one answer for every
+ * extraction path: the cycle, sync's inline extract, the GitHub/Google source
+ * inline extracts, the `extract_stale` minion, `gbrain maintain`, and
+ * `gbrain extract --stale` without an explicit flag.
+ *
+ * The knob shipped in v0.42 but only the cycle read it. Every other path
+ * extracted body links only AND then stamped `links_extracted_at`, so with the
+ * knob on a page came out of an unattended sync marked fresh without its
+ * frontmatter edges, and the cycle's stale drain (the one path that honoured
+ * the knob) never revisited it. The siblings defeated the documented knob.
+ *
+ * Both planes, file wins (same precedence as loadConfigWithEngine). `gbrain
+ * config set` writes the DB plane, so a file-only read would make the
+ * documented enable command a silent no-op (#2120 class). A non-boolean
+ * file-plane value is not an answer — it falls through to the DB plane. Fails
+ * closed: absent, garbled or unreadable values yield false.
+ */
+
+import { isConfigTruthy, loadConfig } from './config.ts';
+
+export const INCLUDE_FRONTMATTER_KEY = 'autopilot.incremental_extract_include_frontmatter';
+
+/**
+ * `explicit` (a `--include-frontmatter` flag) wins; otherwise file plane, then
+ * DB plane via `getConfig` (truthiness through isConfigTruthy, so `1`/`yes`/`on`
+ * work as for every other boolean key); otherwise false.
+ */
+export async function resolveIncludeFrontmatter(
+ engine: { getConfig(key: string): Promise<string | null> } | null | undefined,
+ explicit?: boolean,
+): Promise<boolean> {
+ if (explicit !== undefined) return explicit;
+ const fileVal = loadConfig()?.autopilot?.incremental_extract_include_frontmatter;
+ // Only a real boolean is a file-plane answer; a hand-edited "true"/1 used to
+ // resolve false AND shadow the DB plane (silent `config set` no-op, #2120 class).
+ if (typeof fileVal === 'boolean') return fileVal;
+ if (!engine) return false;
+ try {
+ return isConfigTruthy(await engine.getConfig(INCLUDE_FRONTMATTER_KEY));
+ } catch {
+ return false; // config table unreadable → default off
+ }
+}
diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.ts
index ccf13c3705..49e082e6c1 100644
--- a/src/core/facts/extract.ts
+++ b/src/core/facts/extract.ts
@@ -330,6 +330,48 @@ export function buildExtractorSystem(admitsLow: boolean): string {
const MAX_TURN_TEXT_CHARS = 8000;
+/**
+ * #4863 — JSON Schema for the extractor reply, sent as `responseSchema` on
+ * every chat() call. Only openai-compatible recipes that declare
+ * `supports_structured_outputs` (Ollama: server-side grammar-constrained
+ * decoding) receive it; every other lane ignores it. Mirrors RawExtracted:
+ * fact + kind carry data, the rest are nullable. `parseExtractorJsonDetailed`
+ * still validates the text — the schema removes the malformed-JSON class on
+ * small local models, it does not replace the parser. OpenAI-strict-safe:
+ * `@ai-sdk/openai-compatible` sends `strict: true` by default, and strict
+ * mode demands every property in `required` (nullable via type unions) plus
+ * `additionalProperties: false` on each object — so a proxied backend that
+ * honors strict accepts this schema instead of 400ing on it. The parser
+ * still tolerates absent keys for backends that ignore the schema.
+ */
+const FACTS_EXTRACTION_SCHEMA: Record<string, unknown> = {
+ type: 'object',
+ properties: {
+ facts: {
+ type: 'array',
+ items: {
+ type: 'object',
+ properties: {
+ fact: { type: 'string' },
+ kind: { type: 'string', enum: [...ALL_EXTRACT_KINDS] },
+ entity: { type: ['string', 'null'] },
+ confidence: { type: ['number', 'null'] },
+ notability: { type: 'string', enum: ['high', 'medium', 'low'] },
+ metric: { type: ['string', 'null'] },
+ value: { type: ['number', 'null'] },
+ unit: { type: ['string', 'null'] },
+ period: { type: ['string', 'null'] },
+ },
+ required: ['fact', 'kind', 'entity', 'confidence', 'notability', 'metric', 'value', 'unit', 'period'],
+ additionalProperties: false,
+ },
+ },
+ },
+ required: ['facts'],
+ additionalProperties: false,
+};
+const FACTS_RESPONSE_SCHEMA = { name: 'facts_extraction', schema: FACTS_EXTRACTION_SCHEMA };
+
export type ExtractFailureReason =
| 'chat_unavailable'
| 'provider_error'
@@ -476,6 +518,7 @@ export async function extractFactsFromTurnWithOutcome(
messages: [{ role: 'user', content: userContent }],
maxTokens,
abortSignal: input.abortSignal,
+ responseSchema: FACTS_RESPONSE_SCHEMA,
});
// #2113: never checked pre-fix — a truncated response (stopReason
// 'length', e.g. reasoning tokens eating the cap on mandatory-reasoning
@@ -493,6 +536,7 @@ export async function extractFactsFromTurnWithOutcome(
messages: [{ role: 'user', content: userContent }],
maxTokens: effectiveMaxTokens,
abortSignal: input.abortSignal,
+ responseSchema: FACTS_RESPONSE_SCHEMA,
});
if (result.stopReason === 'length') {
process.stderr.write(
@@ -533,6 +577,7 @@ export async function extractFactsFromTurnWithOutcome(
messages: [{ role: 'user', content: userContent }],
maxTokens: effectiveMaxTokens,
abortSignal: input.abortSignal,
+ responseSchema: FACTS_RESPONSE_SCHEMA,
});
} catch (err) {
if (isAbort(err)) throw err;
diff --git a/src/core/fts-language.ts b/src/core/fts-language.ts
index 5b8cf1e399..53e24d9442 100644
--- a/src/core/fts-language.ts
+++ b/src/core/fts-language.ts
@@ -24,6 +24,16 @@
const VALID_CONFIG_NAME = /^[a-z][a-z0-9_]*$/;
const DEFAULT_LANGUAGE = 'english';
+/**
+ * Config-table key `gbrain reindex-search-vector` sets (value = target
+ * language) before it flips the trigger functions and clears only after both
+ * backfills finish. While present, rows written after the flip and rows not
+ * yet backfilled are tokenized under different configurations, so keyword
+ * search matches only part of the corpus; doctor's `fts_reindex_incomplete`
+ * check fails on it (#4795).
+ */
+export const FTS_REINDEX_MARKER_KEY = 'fts.reindex_in_progress';
+
let cachedLanguage: string | null = null;
/**
diff --git a/src/core/github-source.ts b/src/core/github-source.ts
index e5e0c7853e..314e6c4182 100644
--- a/src/core/github-source.ts
+++ b/src/core/github-source.ts
@@ -1484,13 +1484,16 @@ async function runExtractAndEmbed(
if (!deps.opts.noExtract && totalChanges <= 100) {
try {
- const { extractLinksForSlugs, extractTimelineForSlugs, stampExtracted } = await import('../commands/extract.ts');
+ const { extractLinksForSlugs, extractTimelineForSlugs, stampExtracted, slugsSafeToStamp } = await import('../commands/extract.ts');
const extractOpts = { sourceId: deps.sourceId };
- await extractLinksForSlugs(deps.engine, deps.cfg.dir, pagesAffected, extractOpts);
- await extractTimelineForSlugs(deps.engine, deps.cfg.dir, pagesAffected, extractOpts);
+ const linksResult = await extractLinksForSlugs(deps.engine, deps.cfg.dir, pagesAffected, extractOpts);
+ const timelineResult = await extractTimelineForSlugs(deps.engine, deps.cfg.dir, pagesAffected, extractOpts);
+ // Stamp only the slugs both hooks actually read from disk; a page the
+ // extractor skipped stays stale for 'gbrain extract --stale'.
await stampExtracted(
deps.engine,
- pagesAffected.map((slug) => ({ slug, source_id: deps.sourceId })),
+ slugsSafeToStamp(linksResult, timelineResult)
+ .map((slug) => ({ slug, source_id: deps.sourceId })),
);
} catch { /* extraction is best-effort */ }
} else if (totalChanges > 100 && !deps.opts.noExtract) {
diff --git a/src/core/google/google-source.ts b/src/core/google/google-source.ts
index 34ba92136b..e32a01a28b 100644
--- a/src/core/google/google-source.ts
+++ b/src/core/google/google-source.ts
@@ -911,13 +911,16 @@ async function runExtractAndEmbed(
if (!deps.opts.noExtract && totalChanges <= 100) {
try {
- const { extractLinksForSlugs, extractTimelineForSlugs, stampExtracted } = await import('../../commands/extract.ts');
+ const { extractLinksForSlugs, extractTimelineForSlugs, stampExtracted, slugsSafeToStamp } = await import('../../commands/extract.ts');
const extractOpts = { sourceId: deps.sourceId };
- await extractLinksForSlugs(deps.engine, deps.cfg.dir, pagesAffected, extractOpts);
- await extractTimelineForSlugs(deps.engine, deps.cfg.dir, pagesAffected, extractOpts);
+ const linksResult = await extractLinksForSlugs(deps.engine, deps.cfg.dir, pagesAffected, extractOpts);
+ const timelineResult = await extractTimelineForSlugs(deps.engine, deps.cfg.dir, pagesAffected, extractOpts);
+ // Stamp only the slugs both hooks actually read from disk; a page the
+ // extractor skipped stays stale for 'gbrain extract --stale'.
await stampExtracted(
deps.engine,
- pagesAffected.map((slug) => ({ slug, source_id: deps.sourceId })),
+ slugsSafeToStamp(linksResult, timelineResult)
+ .map((slug) => ({ slug, source_id: deps.sourceId })),
);
} catch { /* extraction is best-effort */ }
} else if (totalChanges > 100 && !deps.opts.noExtract) {
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index e9d70e838c..0b2ca3538d 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -277,6 +277,31 @@ function invalidYamlFrontmatterError(parsed: ReturnType<typeof parseMarkdown>):
return `Invalid YAML frontmatter: ${detail}. Quote scalar values that contain ": " or fix the frontmatter block.`;
}
+/**
+ * #4588: refresh `pages.source_path` on the import SKIP path. A row whose slug
+ * moved before the sync rename repair (GATE13) existed still names the OLD
+ * file; write-through prefers source_path, so every later write recreates the
+ * old directory, and the full-sync reconcile reads the stale path as "file
+ * removed" and soft-deletes the live page. The changed-content path already
+ * heals this via putPage's `COALESCE(EXCLUDED.source_path, …)`; the
+ * unchanged-content skip is the natural heal moment and used to discard the
+ * real path importFile handed in. `current` is the path getPage already read:
+ * equal → no statement at all (an unchanged 20k-file tree must not issue 20k
+ * zero-row UPDATEs, each firing the generation-clock trigger); undefined
+ * (projection-less engine) falls through and `IS DISTINCT FROM` keeps the
+ * UPDATE zero-row. brainstorm passes `${slug}.md`, the value putPage writes on
+ * its own path. Bookkeeping only — never fails the import.
+ */
+async function refreshSourcePath(engine: BrainEngine, slug: string, sourceId: string | undefined, sourcePath: string | undefined, current: string | null | undefined): Promise<void> {
+ if (!sourcePath || current === sourcePath) return;
+ try {
+ await engine.executeRaw(
+ 'UPDATE pages SET source_path = $1 WHERE source_id = $2 AND slug = $3 AND deleted_at IS NULL AND source_path IS DISTINCT FROM $1',
+ [sourcePath, sourceId ?? 'default', slug],
+ );
+ } catch { /* bookkeeping only — never fail the import over it */ }
+}
+
/**
* Import content from a string. Core pipeline:
* parse -> hash -> embed (external) -> transaction(version + putPage + tags + chunks)
@@ -729,6 +754,7 @@ export async function importFromContent(
};
if (existing?.content_hash === hash && !opts.forceRechunk) {
+ await refreshSourcePath(engine, slug, sourceId, opts.sourcePath, existing?.source_path);
return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}) };
}
@@ -753,6 +779,7 @@ export async function importFromContent(
parsed.timeline || '',
hash,
);
+ await refreshSourcePath(engine, slug, sourceId, opts.sourcePath, existing?.source_path);
return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}) };
}
}
@@ -1473,7 +1500,7 @@ export async function importCodeFile(
});
// Hash for idempotency. CHUNKER_VERSION is folded in so chunker shape
- // changes across releases force clean re-chunks without sync --force.
+ // changes across releases force clean re-chunks without a forced re-import.
const hash = createHash('sha256')
.update(JSON.stringify({ title, type: 'code', content, lang, chunker_version: CHUNKER_VERSION }))
.digest('hex');
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index 0d1d84c22c..0bdc8b8f55 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -17,7 +17,7 @@ import { ensureWellFormed } from './text-safe.ts';
import { stripCodeBlocks } from './markdown-code.ts';
import { parseInlineCitationTimelineEntries } from './timeline-citations.ts';
import { slugifyPath, slugifySegment } from './sync.ts';
-import { SLUG_WORD_CHARS } from './cjk.ts';
+import { SLUG_WORD_CHARS, SLUG_VARIATION_SELECTORS_RE } from './cjk.ts';
import { foldNonDecomposingLatin } from './latin-fold.ts';
// #3190: pack-aware link typing. link-inference imports only manifest-v1
// (zod) + redos-guard (node:vm) — no cycle back into this module.
@@ -49,6 +49,16 @@ export { parseInlineCitationTimelineEntries, type InlineCitationTimelineCandidat
* OR updated_at > links_extracted_at`. It is an ISO-8601 string (NOT a number) —
* the column is TIMESTAMPTZ and the predicate binds it as `::timestamptz`.
*/
+// 2026-09-09: #4985 — normalizeBasename strips Unicode variation selectors (twin
+// of slugifySegment), so emoji+VS16 wikilinks re-resolve to the clean slug.
+// 2026-09-09 (same wave): #4977 — the page-role prior no longer applies to
+// links inside the machine-written list sections rolePriorSuppressedRanges
+// matches (Timeline, See also, Related, Facts, Sources, Links, Email mention
+// links, Backlinks, Significant moments), so pre-fix extractions re-run.
+// NOTE: a re-run ADDS a 'mentions' row beside the prior-typed works_at/advises
+// row — link_type is part of the links conflict key and the insert is
+// ON CONFLICT DO NOTHING with no prune — it does NOT demote the old edge;
+// cleaning those up is a separate maintainer decision.
// 2026-09-06: #4873 — pass 1b accepts a leading `./` (and, same wave, the
// `../` / `./../` sibling forms + the folded bare-wikilink grammar), so pages
// whose links were pruned by the sweep reconcile re-extract on `extract --stale`.
@@ -66,7 +76,7 @@ export { parseInlineCitationTimelineEntries, type InlineCitationTimelineCandidat
// PRE-wave code after this date reads as fresh and won't re-extract until
// the page is next edited; no fixed watermark can cover code that keeps
// running past it.
-export const LINK_EXTRACTOR_VERSION_TS = '2026-09-06T00:00:00Z';
+export const LINK_EXTRACTOR_VERSION_TS = '2026-09-09T00:00:00Z';
// ─── Entity references ──────────────────────────────────────────
@@ -117,6 +127,16 @@ export interface EntityRef {
* so flat directories and sibling links produced zero DB-path edges.
*/
sameDir?: boolean;
+ /**
+ * Char offset of the link match in the page content
+ * (stripCodeBlocks and the pass masks are length-preserving, so the
+ * offset is valid against the original content). Lets extractPageLinks
+ * anchor the context window and the Timeline/See-also role-prior
+ * suppression at the ACTUAL link, not at the first occurrence of the
+ * display text — a Timeline link whose display name also appears in the
+ * bio used to anchor early and take the bio's typing.
+ */
+ index?: number;
}
/**
@@ -172,7 +192,7 @@ const ANY_DIR_SEGMENT = '[a-z0-9][a-z0-9_-]*';
* are dropped by the callers' existence checks, exactly as before.
*/
const ENTITY_REF_RE = new RegExp(
- `\\[([^\\]]+)\\]\\((?:\\.\\.\\/)*(${ANY_DIR_SEGMENT}\\/[^)\\s]+?)(?:\\.md)?\\)`,
+ `\\[([^\\]]+)\\]\\((?:\\.\\.\\/)*(${ANY_DIR_SEGMENT}\\/[^)\\s#]+?)(?:\\.md)?(?:#[^)]*)?\\)`,
'g',
);
@@ -240,7 +260,8 @@ const MARKDOWN_LABEL_WIKILINK_RE = /\[[^\]\n]*\[\[[^\]\n]+\]\][^\]\n]*\]\([^)\n]
/**
* #3190: same-directory markdown link — `[Name](slug.md)` whose target has
- * NO directory segment and NO scheme/anchor (`/`, `:`, `#` all excluded).
+ * NO directory segment and NO scheme (`/`, `:` excluded). A trailing
+ * `#anchor` is stripped (#4995), as every wikilink regex here already does.
* #4873: an explicit `./` prefix (`[Name](./slug.md)`, `[Name](./sub/x.md)`)
* is the same page-dir-relative intent — the FS walker's join() eats it — so
* the relative arm admits `/` in the tail. The arm takes ANY leading run of
@@ -254,7 +275,7 @@ const MARKDOWN_LABEL_WIKILINK_RE = /\[[^\]\n]*\[\[[^\]\n]+\]\][^\]\n]*\]\([^)\n]
* linking page's directory happens in extractPageLinks (this module has no
* page context here).
*/
-const SAME_DIR_MD_RE = /\[([^\]]+)\]\((?:((?:\.{1,2}\/)+)([^):#\s]+?)|([^)/:#\s]+?))\.md\)/g;
+const SAME_DIR_MD_RE = /\[([^\]]+)\]\((?:((?:\.{1,2}\/)+)([^):#\s]+?)|([^)/:#\s]+?))\.md(?:#[^)]*)?\)/g;
/**
* A code-reference found in markdown prose. Created by extractCodeRefs and
@@ -389,6 +410,7 @@ export function extractEntityRefs(content: string): EntityRef[] {
// exact {name, slug, dir} shape (no upLevels key) so equality consumers
// are unaffected.
if (up) ref.upLevels = up[0].length / 3;
+ ref.index = match.index;
refs.push(ref);
markdownRanges.push([match.index, match.index + match[0].length]);
}
@@ -413,6 +435,7 @@ export function extractEntityRefs(content: string): EntityRef[] {
const ref: EntityRef = { name, slug: target, dir: '', sameDir: true };
const ups = match[2] ? match[2].split('/').filter(seg => seg === '..').length : 0;
if (ups) ref.upLevels = ups;
+ ref.index = at;
refs.push(ref);
markdownRanges.push([at, at + match[0].length]);
}
@@ -430,7 +453,7 @@ export function extractEntityRefs(content: string): EntityRef[] {
if (slug.endsWith('.md')) slug = slug.slice(0, -3);
const displayName = (match[3] || slug).trim();
const dir = slug.split('/')[0];
- refs.push({ name: displayName, slug, dir, sourceId });
+ refs.push({ name: displayName, slug, dir, sourceId, index: match.index });
qualifiedRanges.push([match.index, match.index + match[0].length]);
}
@@ -446,7 +469,7 @@ export function extractEntityRefs(content: string): EntityRef[] {
if (slug.endsWith('.md')) slug = slug.slice(0, -3);
const displayName = (match[2] || slug).trim();
const dir = slug.split('/')[0];
- refs.push({ name: displayName, slug, dir });
+ refs.push({ name: displayName, slug, dir, index: match.index });
unqualifiedRanges.push([match.index, match.index + match[0].length]);
}
@@ -478,7 +501,7 @@ export function extractEntityRefs(content: string): EntityRef[] {
if (slug.endsWith('.md')) slug = slug.slice(0, -3);
const displayName = (match[2] || slug).trim();
const dir = slug.includes('/') ? slug.split('/')[0] : '';
- refs.push({ name: displayName, slug, dir, needsResolution: true });
+ refs.push({ name: displayName, slug, dir, needsResolution: true, index: match.index });
}
return refs;
@@ -617,12 +640,19 @@ export async function extractPageLinks(
// here and every such edge landed as 'mentions'.
const pack = opts.pack ?? null;
const packBudget = pack ? new PageRegexBudget() : undefined;
- const typeFor = (ctx: string, targetSlug: string): string => {
+ // Timeline / See-also links never receive the page-role prior — see
+ // rolePriorSuppressedRanges (matched on the code-stripped content, so a
+ // fenced `## Timeline` never opens a range). idx is the link's position in
+ // `content` (stripCodeBlocks and the wikilink mask are length-preserving,
+ // so indices line up); idx < 0 / undefined keeps the old behavior.
+ const suppressedRanges = rolePriorSuppressedRanges(stripCodeBlocks(content));
+ const typeFor = (ctx: string, targetSlug: string, idx?: number): string => {
if (pack) {
const packVerb = inferLinkTypeFromPack(pack, pageType as string, ctx, packBudget);
if (packVerb) return packVerb;
}
- return inferLinkType(pageType, ctx, content, targetSlug);
+ const suppressPrior = idx !== undefined && idx >= 0 && inSuppressedRange(suppressedRanges, idx);
+ return inferLinkType(pageType, ctx, suppressPrior ? undefined : content, targetSlug);
};
// 1. Markdown entity refs.
@@ -646,11 +676,11 @@ export async function extractPageLinks(
}
const target = climbed ? '' : slugifyPath(segs.join('/'));
if (target && target !== slug) {
- const idx = content.indexOf(ref.name);
+ const idx = ref.index ?? content.indexOf(ref.name);
const context = idx >= 0 ? excerpt(content, idx, 240) : ref.name;
candidates.push({
targetSlug: target,
- linkType: typeFor(context, target),
+ linkType: typeFor(context, target, idx),
context,
linkSource: 'markdown',
});
@@ -676,11 +706,11 @@ export async function extractPageLinks(
// Pre-fix these refs were silently dropped (flag off) or demoted to
// untyped wikilink_basename edges (flag on).
if (slashIdx !== -1 && ref.slug !== slug) {
- const litIdx = content.indexOf(ref.slug);
+ const litIdx = ref.index ?? content.indexOf(ref.slug);
const litContext = litIdx >= 0 ? excerpt(content, litIdx, 240) : ref.name;
candidates.push({
targetSlug: ref.slug,
- linkType: typeFor(litContext, ref.slug),
+ linkType: typeFor(litContext, ref.slug, litIdx),
context: litContext,
linkSource: 'markdown',
});
@@ -704,11 +734,11 @@ export async function extractPageLinks(
// Self-loop guard: `[[own-basename]]` on the root page itself.
if (!form || form === slug) continue;
bareDirect.add(form);
- const litIdx = content.indexOf(ref.slug);
+ const litIdx = ref.index ?? content.indexOf(ref.slug);
const litContext = litIdx >= 0 ? excerpt(content, litIdx, 240) : ref.name;
candidates.push({
targetSlug: form,
- linkType: typeFor(litContext, form),
+ linkType: typeFor(litContext, form, litIdx),
context: litContext,
linkSource: 'markdown',
});
@@ -759,7 +789,10 @@ export async function extractPageLinks(
}
continue;
}
- const idx = content.indexOf(ref.name);
+ // Anchor at the ref's true match offset when the pass
+ // recorded one — first-occurrence-of-display-text anchoring let a
+ // Timeline link inherit the bio's context (and its verb typing).
+ const idx = ref.index ?? content.indexOf(ref.name);
// Wider context window (240 chars vs original 80) catches verbs that
// appear at sentence-or-paragraph distance from the slug — common in
// narrative prose where a partner's investment verbs appear once and
@@ -767,11 +800,14 @@ export async function extractPageLinks(
const context = idx >= 0 ? excerpt(content, idx, 240) : ref.name;
// Relative markdown links resolve against THIS page's directory (fixes
// cross-dir edges for nested / subtree-scoped content); absolute refs pass
- // through unchanged.
- const targetSlug = resolveRelativeSlug(slug, ref);
+ // through unchanged. #4995: lowercased (pass-1 markdown + 2a/2b wikilink
+ // refs) — validateSlug stores every slug lowercase on both engines, so a
+ // mixed-case candidate could never resolve. NOT slugifyPath: it strips
+ // characters validateSlug permits and would mangle a legit put_page slug.
+ const targetSlug = resolveRelativeSlug(slug, ref).toLowerCase();
candidates.push({
targetSlug,
- linkType: typeFor(context, targetSlug),
+ linkType: typeFor(context, targetSlug, idx),
context,
linkSource: 'markdown',
});
@@ -805,7 +841,7 @@ export async function extractPageLinks(
const context = excerpt(strippedContent, m.index, 240);
candidates.push({
targetSlug: m[1],
- linkType: typeFor(context, m[1]),
+ linkType: typeFor(context, m[1], m.index),
context,
linkSource: 'markdown',
});
@@ -955,6 +991,49 @@ const ADVISOR_ROLE_RE = /\b(?:full-time advisor|professional advisor|advises (?:
// pages mentioning their employees use the page-role layer differently.
const EMPLOYEE_ROLE_RE = /\b(?:is an? (?:senior|staff|principal|lead|backend|frontend|full-?stack|ML|data|security|DevOps|platform)? ?engineer at|is an? (?:senior|staff|principal|lead)? ?(?:developer|designer|product manager|engineering manager|director|VP) (?:at|of)|holds? the (?:CTO|CEO|CFO|COO|CMO|CRO|VP) (?:role|position|seat|title) at|is the (?:CTO|CEO|CFO|COO|CMO|CRO) of|employee at|on the team at|works on .{0,30} at)\b/i;
+/**
+ * Content index ranges where the page-role prior must NOT apply: the
+ * machine-written list sections — Timeline, See also, Related, Facts,
+ * Sources, Links, Email mention links, Backlinks, Significant moments
+ * (headingRe below is the one source of truth). Links there are list-shaped, per-event references
+ * ("2026-05-12 — met with [[companies/x]]", Iron-Law back-links) — the
+ * role prior is a statement about the AUTHOR's standing relationships, not
+ * about every entity that passes through their timeline, so applying it
+ * there mints unevidenced works_at/advises edges on every re-import (on
+ * one 12k-page brain: ~7.4k such edges re-minted in a month, right after
+ * a ~19.5k cleanup; same class as #3466). Per-edge verbs inside these
+ * sections still type normally — only the globalContext fallback is
+ * suppressed, so absent explicit evidence the edge stays 'mentions'.
+ *
+ * A range runs from its heading to the next heading of the same or higher
+ * level (or EOF). Case-insensitive; matches "See also" / "See-also". Both
+ * grammars require the ATX space after the `#`s, so a column-0 tag line
+ * (`#links`) is neither an opener nor a closer.
+ */
+function rolePriorSuppressedRanges(content: string): Array<[number, number]> {
+ const ranges: Array<[number, number]> = [];
+ const headingRe = /^(#{1,6})[ \t]+(?:timeline|see[ -]also|related|facts|sources|links|email mention links|backlinks|significant moments)\b[^\n]*$/gim;
+ const anyHeadingRe = /^(#{1,6})[ \t]/gm;
+ let m: RegExpExecArray | null;
+ while ((m = headingRe.exec(content)) !== null) {
+ const level = m[1].length;
+ anyHeadingRe.lastIndex = m.index + m[0].length;
+ // Deeper headings (`###` under `## Timeline`) stay inside the range; the
+ // first same-or-higher one closes it.
+ let next: RegExpExecArray | null;
+ while ((next = anyHeadingRe.exec(content)) !== null && next[1].length > level) { /* nested subsection */ }
+ ranges.push([m.index, next ? next.index : content.length]);
+ }
+ return ranges;
+}
+
+function inSuppressedRange(ranges: Array<[number, number]>, idx: number): boolean {
+ for (const [start, end] of ranges) {
+ if (idx >= start && idx < end) return true;
+ }
+ return false;
+}
+
/**
* Infer link_type from page context. Deterministic regex heuristics, no LLM.
*
@@ -1128,7 +1207,8 @@ export function normalizeBasename(s: string): string {
// the ASCII page slug does not, and the lookup misses in silence:
// `[[\u0110\u1ee9c Example]]` keyed `\u0111uc-example` and never found `people/duc-example`.
const folded = foldNonDecomposingLatin(
- s.normalize('NFD').replace(/[\u0300-\u036f]/g, '').normalize('NFC').toLowerCase(),
+ s.normalize('NFD').replace(/[\u0300-\u036f]/g, '').normalize('NFC')
+ .replace(SLUG_VARIATION_SELECTORS_RE, '').toLowerCase(), // twin of slugifySegment's strip (#4985)
);
return folded.replace(BASENAME_KEEP_RE, '').trim().replace(/\s+/g, '-');
}
diff --git a/src/core/link-source-check-repair.ts b/src/core/link-source-check-repair.ts
new file mode 100644
index 0000000000..b8d2c28c51
--- /dev/null
+++ b/src/core/link-source-check-repair.ts
@@ -0,0 +1,124 @@
+/**
+ * #4613 — links_link_source_check constraint-shape self-heal.
+ *
+ * Migration v114 (#1941) opened `links.link_source` from a closed allowlist to
+ * a kebab-case format gate. The migrator trusts the version ledger
+ * (`m.version > current`), so a brain stamped >= 114 whose live CHECK still
+ * carries the pre-v114 allowlist (restore from a drifted snapshot, manual DDL,
+ * an interrupted historical migration) never replays v114 — and every kebab
+ * provenance write (`atom-provenance`, `concept-provenance`) is rejected while
+ * `doctor` reports the schema current.
+ *
+ * Third instance of the #2038 / #550 pattern: key the check off the actual
+ * constraint SHAPE in pg_constraint (not the ledger), run the repair on every
+ * migrate pass once the ledger has reached v114, refuse loudly instead of
+ * half-applying. The repair only ever restores the migration-declared
+ * definition — it never touches rows. Violating rows are probed BEFORE any
+ * DDL: when present, nothing is altered (the old constraint, if any, stays in
+ * place) and the count is reported for manual resolution — so a brain with a
+ * bad row never pays for a failing ALTER on every engine open.
+ */
+
+import type { BrainEngine } from './engine.ts';
+
+const CONSTRAINT_NAME = 'links_link_source_check';
+
+/** The migration that introduced the kebab gate; `runMigrations` skips the self-heal below this ledger. */
+export const LINK_SOURCE_GATE_MIGRATION_VERSION = 114;
+
+/**
+ * Kebab provenance-tag format gate (migration v114 / #1941). ONE copy here;
+ * the drift-guard test pins it to the literal in migrate.ts v114, schema.sql
+ * and pglite-schema.ts.
+ */
+export const LINK_SOURCE_KEBAB_RE = '^[a-z][a-z0-9]*(-[a-z0-9]+)*$';
+
+const GATE_PREDICATE = `(link_source ~ '${LINK_SOURCE_KEBAB_RE}' AND char_length(link_source) <= 64)`;
+
+const DROP_DDL = `ALTER TABLE links DROP CONSTRAINT IF EXISTS ${CONSTRAINT_NAME};`;
+const ADD_DDL = `ALTER TABLE links ADD CONSTRAINT ${CONSTRAINT_NAME} CHECK (link_source IS NULL OR ${GATE_PREDICATE})`;
+const VALIDATE_DDL = `ALTER TABLE links VALIDATE CONSTRAINT ${CONSTRAINT_NAME}`;
+
+export type LinkSourceCheckDrift = 'absent' | 'wrong_def' | 'not_validated';
+
+export interface LinkSourceCheckStatus {
+ /** The links table exists (nothing to check if not). */
+ tablePresent: boolean;
+ constraintPresent: boolean;
+ /** `pg_get_constraintdef` output; null when absent. */
+ def: string | null;
+ /** Which drift shape was found; null when the live shape matches v114. */
+ drift: LinkSourceCheckDrift | null;
+ needsRepair: boolean;
+}
+
+export async function checkLinkSourceCheck(engine: BrainEngine): Promise<LinkSourceCheckStatus> {
+ const tbl = await engine.executeRaw<{ reg: string | null }>(`SELECT to_regclass('links')::text AS reg`);
+ if (!tbl[0]?.reg) {
+ return { tablePresent: false, constraintPresent: false, def: null, drift: null, needsRepair: false };
+ }
+ const rows = await engine.executeRaw<{ def: string; convalidated: boolean }>(
+ `SELECT pg_get_constraintdef(oid) AS def, convalidated FROM pg_constraint
+ WHERE conrelid = to_regclass('links') AND conname = '${CONSTRAINT_NAME}'`,
+ );
+ const row = rows[0];
+ // pg_get_constraintdef deparses the regex Const verbatim, so a substring
+ // match on the literal distinguishes v114 from any older allowlist.
+ const drift: LinkSourceCheckDrift | null = !row
+ ? 'absent'
+ : !row.def.includes(LINK_SOURCE_KEBAB_RE)
+ ? 'wrong_def'
+ : !row.convalidated
+ ? 'not_validated'
+ : null;
+ return { tablePresent: true, constraintPresent: !!row, def: row?.def ?? null, drift, needsRepair: drift !== null };
+}
+
+export interface LinkSourceCheckRepairResult {
+ repaired: boolean;
+ /** Rows whose link_source fails the kebab gate (they block the ADD). */
+ violations: number;
+ reason: 'already_correct' | 'no_table' | 'violations' | 'restored';
+}
+
+async function countViolations(engine: BrainEngine): Promise<number> {
+ const bad = await engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*)::text AS n FROM links WHERE link_source IS NOT NULL AND NOT ${GATE_PREDICATE}`,
+ );
+ return parseInt(bad[0]?.n ?? '0', 10);
+}
+
+/**
+ * Restore the v114 definition when the live shape drifted. Mirrors v114's
+ * engine split: on Postgres a plain `ADD CONSTRAINT ... CHECK` takes ACCESS
+ * EXCLUSIVE + a full validation scan on `links`, so the repair does DROP +
+ * `ADD ... NOT VALID` in one transaction (atomic, no scan) and then `VALIDATE
+ * CONSTRAINT` outside it (SHARE UPDATE EXCLUSIVE, doesn't block reads or
+ * writes); a `not_validated` drift only needs the VALIDATE. PGLite
+ * (single-writer WASM, no lock concern) keeps the one-shot DROP + ADD in one
+ * transaction. Violating rows are counted BEFORE any DDL, so a brain with a
+ * bad row never pays for a failing ALTER at every engine open; the post-DDL
+ * count only classifies a row written between the probe and the ALTER.
+ */
+export async function repairLinkSourceCheck(engine: BrainEngine): Promise<LinkSourceCheckRepairResult> {
+ const status = await checkLinkSourceCheck(engine);
+ if (!status.tablePresent) return { repaired: false, violations: 0, reason: 'no_table' };
+ if (!status.needsRepair) return { repaired: false, violations: 0, reason: 'already_correct' };
+ const violations = await countViolations(engine);
+ if (violations > 0) return { repaired: false, violations, reason: 'violations' };
+ try {
+ if (engine.kind === 'postgres') {
+ if (status.drift !== 'not_validated') {
+ await engine.transaction((tx) => tx.runMigration(0, `${DROP_DDL} ${ADD_DDL} NOT VALID;`));
+ }
+ await engine.runMigration(0, VALIDATE_DDL);
+ } else {
+ await engine.transaction((tx) => tx.runMigration(0, `${DROP_DDL} ${ADD_DDL};`));
+ }
+ } catch (e) {
+ const late = await countViolations(engine);
+ if (late === 0) throw e; // not a data problem — surface the real error
+ return { repaired: false, violations: late, reason: 'violations' };
+ }
+ return { repaired: true, violations: 0, reason: 'restored' };
+}
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 0d2a84f04b..0c9287ffc1 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -10,6 +10,7 @@ import {
} from './retry-matcher.ts';
import { repairTimelineDedupIndex, repairLegacyTimelineSourceRows } from './timeline-dedup-repair.ts';
import { repairPagesUpsertArbiter } from './pages-upsert-arbiter.ts';
+import { repairLinkSourceCheck, LINK_SOURCE_GATE_MIGRATION_VERSION } from './link-source-check-repair.ts';
import { GRANT_COLUMNS_SQL, GRANT_AUDIT_SCHEMA_SQL, GRANT_SPEND_COLUMNS_SQL } from './grants/schema.ts';
import { FACT_WITHDRAWAL_SCHEMA_SQL, FACT_WITHDRAWAL_BACKFILL_SQL } from './facts/withdrawal-schema.ts';
import { repairLegacyClientGrants } from './grants/migration.ts';
@@ -6925,6 +6926,27 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: num
}
} catch { /* best-effort; doctor reports the drift if this couldn't run */ }
+ // #4613: same drift class for links_link_source_check. A brain stamped past
+ // v114 whose CHECK still carries the pre-v114 allowlist rejects every kebab
+ // provenance write; the version counter can't see it. Refuses loudly on
+ // violators. Ledger-gated: below v114 the pending loop replays v114 itself
+ // (the repair would rewrite the constraint twice; pre-v11 has no column).
+ if (current >= LINK_SOURCE_GATE_MIGRATION_VERSION) {
+ try {
+ const l = await repairLinkSourceCheck(engine);
+ if (l.repaired) {
+ console.error(`[migrate] restored links_link_source_check to the v114 kebab-case gate (#4613)`);
+ } else if (l.reason === 'violations') {
+ console.error(
+ `[migrate] cannot restore links_link_source_check: ${l.violations} links row(s) have a ` +
+ `non-kebab link_source — fix or delete them, then re-run (#4613). See \`gbrain doctor\`.`,
+ );
+ }
+ } catch (e) {
+ console.error(`[migrate] links_link_source_check self-heal could not run (#4613): ${e instanceof Error ? e.message : String(e)}`);
+ }
+ }
+
if (pending.length === 0) {
return { applied: 0, current };
}
diff --git a/src/core/minions/protected-names.ts b/src/core/minions/protected-names.ts
index 8493e54872..82e62aeb5d 100644
--- a/src/core/minions/protected-names.ts
+++ b/src/core/minions/protected-names.ts
@@ -49,7 +49,8 @@ export const PROTECTED_JOB_NAMES: ReadonlySet<string> = new Set([
// consenting user decision. PROTECTED + manual_only in
// src/core/onboard/render.ts:toOnboardRecommendation ensures autopilot
// can't auto-apply; user must run `gbrain onboard --auto-with-prompt`
- // or submit explicitly via `gbrain jobs submit unify-types --allow-protected`.
+ // or submit explicitly via `gbrain jobs submit unify-types` (the local CLI
+ // submit path sets allowProtectedSubmit for protected names itself).
'unify-types',
// v0.42.0.0 — SkillOpt: optimizer Sonnet/Opus loops over a benchmark.
// Preemptive register entry (v1 is CLI-only foreground; future Minion
@@ -60,8 +61,9 @@ export const PROTECTED_JOB_NAMES: ReadonlySet<string> = new Set([
// calls Haiku to extract atoms (~$0.30/source/run), so it MUST NOT be
// submittable by an MCP/OAuth-scoped caller — same posture as the protected
// `extract-takes-from-pages`. Only trusted local callers (the autopilot
- // auto-drain branch, an explicit `gbrain jobs submit extract-atoms-drain
- // --allow-protected`) can insert it.
+ // auto-drain branch, an explicit `gbrain jobs submit extract-atoms-drain`
+ // from the CLI — which sets allowProtectedSubmit for protected names itself;
+ // no submit flag exists or is needed) can insert it.
'extract-atoms-drain',
]);
diff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.ts
index 9b2efe755a..4373261c6b 100644
--- a/src/core/minions/tools/brain-allowlist.ts
+++ b/src/core/minions/tools/brain-allowlist.ts
@@ -29,6 +29,9 @@ import type { AuthInfo, Operation, OperationContext } from '../../operations.ts'
import { paramDefToSchema } from '../../../mcp/tool-defs.ts';
import { normalizeOptionalParams, validateParams } from '../../../mcp/validate-params.ts';
import { validateSourceId } from '../../utils.ts';
+import { parseMarkdown, serializeMarkdown } from '../../markdown.ts';
+import { loadActivePackForWriteVocabulary } from '../../schema-pack/write-vocabulary.ts';
+import { classifyStoredType, sanitizeTypeForDisplay } from '../../schema-pack/type-usage.ts';
import type { ToolCtx, ToolDef } from '../types.ts';
/**
@@ -319,12 +322,52 @@ export function buildBrainTools(opts: BuildBrainToolsOpts): ToolDef[] {
const params = normalizeOptionalParams(op, raw);
const validationError = validateParams(op, params);
if (validationError) throw new Error(`${toolName}: ${validationError}`);
+ if (op.name === 'put_page' && opts.allowedSlugPrefixes?.length) {
+ await pinUndeclaredType(params, opCtx);
+ }
return op.handler(opCtx, params);
},
};
});
}
+/**
+ * #4852: trusted-workspace subagents (dream synth agentic lane, patterns,
+ * delegated jobs — the `allowedSlugPrefixes` writers) author page content
+ * model-side, and the model mints types no bundled pack declares
+ * (`reflection` / `original` / `pattern`). The orchestrator reverse-writes
+ * that type to disk as explicit frontmatter, so every `gbrain sync` re-warns.
+ * The oneshot lane already pins its output to 'note' (F5 in
+ * subagent-oneshot.ts); this extends the same rule to the tool-calling lanes:
+ * an EXPLICIT frontmatter type the active pack classifies as `undeclared`
+ * rewrites to 'note' with the model's type kept in `frontmatter.legacy_type`
+ * (the base-v2 D12 shape). Declared types and aliases pass through untouched
+ * (alias_of stays a sync warning); no resolvable pack → no-op (the #4655
+ * fail-open posture). Never rejects — patterns children run require_writes
+ * and a rejection would dead-letter the whole phase. Runs BEFORE import so
+ * content_hash is computed once over the final type (no re-chunk churn).
+ */
+async function pinUndeclaredType(
+ params: Record<string, unknown>,
+ opCtx: OperationContext,
+): Promise<void> {
+ if (typeof params.content !== 'string' || typeof params.slug !== 'string') return;
+ const parsed = parseMarkdown(params.content, `${params.slug}.md`);
+ if (parsed.typeExplicit !== true) return;
+ const pack = await loadActivePackForWriteVocabulary(opCtx);
+ if (!pack || classifyStoredType(parsed.type, pack.manifest).kind !== 'undeclared') return;
+ params.content = serializeMarkdown(
+ { ...parsed.frontmatter, legacy_type: parsed.type },
+ parsed.compiled_truth,
+ parsed.timeline,
+ { type: 'note', title: parsed.title, tags: parsed.tags },
+ );
+ opCtx.logger.warn(
+ `undeclared type '${sanitizeTypeForDisplay(parsed.type)}' normalized to 'note' ` +
+ `(legacy_type kept; pack ${pack.manifest.name})`,
+ );
+}
+
/**
* Apply the caller's `allowed_tools` subset to a registry. Unknown tool
* names throw a clear error at load time (NOT silently ignored) so
diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.ts
index 7758cf6b26..33dc16881b 100644
--- a/src/core/ops/admin.ts
+++ b/src/core/ops/admin.ts
@@ -146,7 +146,8 @@ const run_doctor: Operation = {
// Source isolation (cross-model P1): a source-bound caller's report must
// not aggregate other sources' activity. Scope-aware checks (connection,
// brain_score, chronicle_projection_health, multi_source_drift,
- // volunteer_channels, extract_atoms_backlog) filter on these ids;
+ // volunteer_channels, extract_atoms_backlog,
+ // contextual_retrieval_coverage) filter on these ids;
// unscoped ctx = brain-wide.
const scope = sourceScopeOpts(ctx);
const sourceIds = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : undefined);
diff --git a/src/core/ops/code-intel.ts b/src/core/ops/code-intel.ts
index cbc1bdd0ff..2143aecf4c 100644
--- a/src/core/ops/code-intel.ts
+++ b/src/core/ops/code-intel.ts
@@ -92,6 +92,7 @@ const code_callees: Operation = {
limit,
allSources,
sourceId,
+ bareFallback: true, // #4670: honor the documented "bare or qualified" contract
});
const { resolveCodeReadiness } = await import('../code-graph-readiness.ts');
// #4352: thread trust — see code_callers.
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 166400f8f8..2d2a665ab7 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -495,13 +495,19 @@ function parseEntityList(v: unknown): string[] {
return [];
}
+// #4761: the budget packers price the RENDERED line (+ its newline), never the
+// raw fields — see renderCardLine & co. in context/turn-context.ts. packToBudget
+// treats budget <= 0 as NO CAP, so a sub-floor budget must drop explicitly.
+const lineCost = (line: string) => estimateTokens(line + '\n');
+const dropAll = <T>(items: T[]) => ({ items: [] as T[], meta: { budget: 0, used: 0, dropped: items.length, kept: 0 } });
+
const context_pack: Operation = {
name: 'context_pack',
description:
'MEMORY VERB (v1): budget-packed session-boundary bundle for a set of standing entities — entity cards + open threads + hot facts, zero-LLM, sub-second. Call at session start (warm cold context) and after compaction (rehydrate what the summary lost). WORLD-ONLY by default; pass include_private (honored for LOCAL trusted callers only) to widen all arms. budget_tokens packs server-side (response reports budget_used + dropped_count; cards pack first, then facts). Branch on structured fields, never prose. protocol_version rides every response.',
params: {
entities: { type: 'string', required: true, description: 'Comma-separated entity names/slugs to bundle. Capped at 8.' },
- budget_tokens: { type: 'number', description: 'Server-side token budget (char/4). Cards pack first, then facts. Response adds budget_tokens, budget_used, dropped_count.' },
+ budget_tokens: { type: 'number', description: 'Server-side token budget (char/4). Cards pack first, then facts; each item costs its rendered line and the envelope + section headers are reserved, so `text` fits the budget. Response adds budget_tokens, budget_used (tokens of `text`), dropped_count.' },
since: { type: 'string', description: 'ISO 8601 datetime. When set, open-thread events are filtered to those after this cursor.' },
session_id: { type: 'string', description: 'Opaque session id; keys the hot-memory cache and (on the push path) the session cursor.' },
include_private: { type: 'boolean', description: 'Local trusted callers only: widen ALL arms to include private facts. Ignored (world-only) for remote callers. Default false.' },
@@ -511,7 +517,8 @@ const context_pack: Operation = {
cliHints: { name: 'context-pack' },
annotations: { title: 'context_pack (boundary bundle)', readOnlyHint: true },
handler: async (ctx, p) => {
- const { assembleContextPack, renderPack, isAfter, PACK_DEFAULT_MAX_ENTITIES } = await import('../context/turn-context.ts');
+ const { assembleContextPack, renderPack, isAfter, PACK_DEFAULT_MAX_ENTITIES, renderCardLine, renderThreadLine, renderFactLine, packHeaderCost } =
+ await import('../context/turn-context.ts');
const sourceId = ctx.sourceId ?? 'default';
const rawSince = typeof p.since === 'string' && p.since.trim() ? p.since : undefined;
if (rawSince !== undefined && !Number.isFinite(Date.parse(rawSince))) {
@@ -545,33 +552,33 @@ const context_pack: Operation = {
let cards = res.cards ?? [];
let facts = res.facts ?? [];
- let budgetUsed: number | undefined;
+ // The SAME since filter the assembler applied (pre-landing review: the raw
+ // flatMap silently dropped the documented `since` contract from the
+ // structured array whenever budget packing ran) — shared with the card
+ // cost below, since a card's rendered threads ride its budget.
+ const threadsOf = (c: (typeof cards)[number]) =>
+ (c.open_threads ?? []).filter((t) => !since || (t.date !== null && isAfter(t.date, since)));
let droppedCount: number | undefined;
if (budgetTokens !== null) {
+ // #4761: reserve the envelope + headers, then price each card as its
+ // rendered line plus its rendered (since-filtered) thread lines.
+ const itemBudget = budgetTokens - packHeaderCost();
const cardCost = (c: (typeof cards)[number]) =>
- estimateTokens(`${c.entity.title} ${c.summary} ${(c.open_threads ?? []).map((t) => t.text).join(' ')}`);
- const cardPack = packToBudget(cards, cardCost, budgetTokens);
+ lineCost(renderCardLine(c)) + threadsOf(c).reduce((n, t) => n + lineCost(renderThreadLine(t)), 0);
+ const cardPack = itemBudget > 0 ? packToBudget(cards, cardCost, itemBudget) : dropAll(cards);
cards = cardPack.items;
- const remaining = budgetTokens - cardPack.meta.used;
- const factPack =
- remaining > 0
- ? packToBudget(facts, (f) => estimateTokens(f.fact), remaining)
- : { items: [] as typeof facts, meta: { budget: 0, used: 0, dropped: facts.length, kept: 0 } };
+ const remaining = itemBudget - cardPack.meta.used;
+ const factPack = remaining > 0 ? packToBudget(facts, (f) => lineCost(renderFactLine(f)), remaining) : dropAll(facts);
facts = factPack.items;
- budgetUsed = cardPack.meta.used + factPack.meta.used;
droppedCount = cardPack.meta.dropped + factPack.meta.dropped;
}
- // Recompute open_threads with the SAME since filter the assembler applied
- // (pre-landing review: the raw flatMap silently dropped the documented
- // `since` contract from the structured array whenever budget packing ran).
- const open_threads = cards
- .flatMap((c) => c.open_threads ?? [])
- .filter((t) => !since || (t.date !== null && isAfter(t.date, since)));
+ const open_threads = cards.flatMap(threadsOf);
// Re-render the injectable block from the FINAL sets (adversarial review):
// `text` is what harnesses inject, so it must honor the same budget the
// structured arrays report — the assembler's pre-budget rendering would
- // overrun the declared budget_tokens.
+ // overrun the declared budget_tokens. budget_used reports that text.
const text = budgetTokens !== null ? renderPack(cards, open_threads, facts) : res.text;
+ const budgetUsed = budgetTokens !== null ? estimateTokens(text) : undefined;
return {
protocol_version: MEMORY_VERBS_VERSION,
@@ -607,12 +614,12 @@ const context_pack: Operation = {
const delta: Operation = {
name: 'delta',
description:
- 'MEMORY VERB (v1): "what changed since T" for heartbeats — pages updated after `since` + hot facts newer than `since` + open-thread events after `since`, zero-LLM. Lets a periodic wake maintain warm state in O(changes) instead of re-deriving. Optionally scope thread deltas to `entities`. WORLD-ONLY by default; include_private honored for local trusted callers only. budget_tokens packs server-side (pages first, then facts). protocol_version rides every response.',
+ 'MEMORY VERB (v1): "what changed since T" for heartbeats — pages updated after `since` + hot facts newer than `since` + open-thread events after `since`, zero-LLM. Lets a periodic wake maintain warm state in O(changes) instead of re-deriving. Optionally scope thread deltas to `entities`. WORLD-ONLY by default; include_private honored for local trusted callers only. budget_tokens packs server-side (pages first, then facts; threads are never dropped). protocol_version rides every response.',
params: {
since: { type: 'string', description: 'ISO 8601 cursor. Returns pages/facts/thread-events newer than this timestamp. Optional when session_id carries an established cursor.' },
since_slug: { type: 'string', description: 'Stateless keyset resume: pass back `next_cursor.slug` from the previous response (paired with `since`=next_cursor.since) to page through pages sharing one timestamp. Ignored when session_id is set (the session cursor carries it).' },
entities: { type: 'string', description: 'Optional comma-separated entity scope for thread-event deltas. Capped at 8.' },
- budget_tokens: { type: 'number', description: 'Server-side token budget (char/4). Pages pack first, then facts. Response adds budget_tokens, budget_used, dropped_count.' },
+ budget_tokens: { type: 'number', description: 'Server-side token budget (char/4). Pages pack first, then facts; each item costs its rendered line and the envelope + section headers + every thread line are reserved, so `text` fits the budget. Threads are never dropped (budget_used can exceed the budget only when the header + threads alone do). Response adds budget_tokens, budget_used (tokens of `text`), dropped_count.' },
session_id: { type: 'string', description: 'Opaque session id. Drives the per-session cursor: the first call establishes it, each call advances it to the newest DELIVERED change (at-least-once — with has_more:true the undelivered tail returns on the next wake). Without it, pass an explicit `since` for a stateless delta.' },
include_private: { type: 'boolean', description: 'Local trusted callers only: widen ALL arms to include private facts. Ignored (world-only) for remote callers. Default false.' },
},
@@ -621,7 +628,8 @@ const delta: Operation = {
cliHints: { name: 'delta' },
annotations: { title: 'delta (what changed since)', readOnlyHint: true },
handler: async (ctx, p) => {
- const { assembleDeltaContext, renderDelta, PACK_DEFAULT_MAX_ENTITIES } = await import('../context/turn-context.ts');
+ const { assembleDeltaContext, renderDelta, PACK_DEFAULT_MAX_ENTITIES, renderPageLine, renderFactLine, renderThreadLine, deltaHeaderCost } =
+ await import('../context/turn-context.ts');
const { getSessionContextState, upsertSessionContextState } = await import('../context/session-state.ts');
const sourceId = ctx.sourceId ?? 'default';
const rawSince = typeof p.since === 'string' && p.since.trim() ? p.since : null;
@@ -730,8 +738,9 @@ const delta: Operation = {
// needed; the keyset already excludes everything at/before the cursor.
let pages = res.deltaPages ?? [];
let facts = res.facts ?? [];
+ // Threads are NEVER budget-dropped: they are the commitments a heartbeat
+ // must not miss, and they have no keyset of their own to resume from.
const threads = res.openThreads ?? [];
- let budgetUsed: number | undefined;
let droppedCount: number | undefined;
let factsDropped = 0;
const fetchedPages = pages.length;
@@ -739,15 +748,16 @@ const delta: Operation = {
// packToBudget keeps a contiguous PREFIX (order-preserving, stops at the
// first overflow) — with oldest-first pages the kept set stays contiguous
// from the cursor, which the advance logic below depends on.
- const pagePack = packToBudget(pages, (pg) => estimateTokens(`${pg.title} ${pg.slug}`), budgetTokens);
+ // #4761: reserve the envelope + headers (they embed `since`, so price per
+ // call) AND every thread line, then cost each page/fact as its rendered
+ // line — `text` fits the budget whenever the reserved part alone does.
+ const itemBudget =
+ budgetTokens - deltaHeaderCost(effectiveSince) - threads.reduce((n, t) => n + lineCost(renderThreadLine(t)), 0);
+ const pagePack = itemBudget > 0 ? packToBudget(pages, (pg) => lineCost(renderPageLine(pg)), itemBudget) : dropAll(pages);
pages = pagePack.items;
- const remaining = budgetTokens - pagePack.meta.used;
- const factPack =
- remaining > 0
- ? packToBudget(facts, (f) => estimateTokens(f.fact), remaining)
- : { items: [] as typeof facts, meta: { budget: 0, used: 0, dropped: facts.length, kept: 0 } };
+ const remaining = itemBudget - pagePack.meta.used;
+ const factPack = remaining > 0 ? packToBudget(facts, (f) => lineCost(renderFactLine(f)), remaining) : dropAll(facts);
facts = factPack.items;
- budgetUsed = pagePack.meta.used + factPack.meta.used;
droppedCount = pagePack.meta.dropped + factPack.meta.dropped;
factsDropped = factPack.meta.dropped;
}
@@ -755,6 +765,9 @@ const delta: Operation = {
// has_more covers ALL undelivered content — fetch-limit overflow, budget-
// dropped pages, AND budget-dropped facts (pre-landing review: facts were
// silently lost when pages fit but facts overflowed).
+ // ponytail: dropped facts keep the pre-existing ceiling — the cursor still
+ // advances past delivered pages, so they re-surface only if their
+ // created_at is after the new cursor; a per-arm cursor would fix it.
const hasMore = res.deltaOverflow === true || pagesDropped > 0 || factsDropped > 0;
// Cursor advance (keyset, at-least-once): advance to the last DELIVERED
@@ -786,7 +799,10 @@ const delta: Operation = {
// Re-render the injectable block from the FINAL sets (adversarial review):
// `text` must honor the budget AND the boundary-tie exclusion the
// structured arrays reflect — the assembler's render predates both.
+ // budget_used reports that text; it exceeds budget_tokens only when the
+ // header + the never-truncated threads alone do.
const text = renderDelta(pages, facts, threads, effectiveSince);
+ const budgetUsed = budgetTokens !== null ? estimateTokens(text) : undefined;
return {
protocol_version: MEMORY_VERBS_VERSION,
diff --git a/src/core/ops/files.ts b/src/core/ops/files.ts
index 2f62326f53..1e7c1e9549 100644
--- a/src/core/ops/files.ts
+++ b/src/core/ops/files.ts
@@ -99,7 +99,7 @@ const file_upload: Operation = {
const { createStorage } = await import('../storage.ts');
const storage = await createStorage(ctx.config.storage as any);
- const { sqlQueryForEngine } = await import('../sql-query.ts');
+ const { sqlQueryForEngine, executeRawJsonb, FILES_METADATA_MERGE_SQL } = await import('../sql-query.ts');
const sql = sqlQueryForEngine(ctx.engine);
const existing = await sql`SELECT id FROM files WHERE content_hash = ${hash} AND storage_path = ${storagePath}`;
if (existing.length > 0) {
@@ -121,14 +121,22 @@ const file_upload: Operation = {
}
try {
- await sql`
- INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)
- VALUES (${pageSlug}, ${filename}, ${storagePath}, ${mimeType}, ${stat.size}, ${hash}, ${'{}'}::jsonb)
- ON CONFLICT (storage_path) DO UPDATE SET
- content_hash = EXCLUDED.content_hash,
- size_bytes = EXCLUDED.size_bytes,
- mime_type = EXCLUDED.mime_type
- `;
+ // #4910: stamp the storage lane (doctor image_assets / files verify
+ // classify on it) and merge metadata on conflict so legacy `{}` rows
+ // heal on their next content change. Real object via executeRawJsonb —
+ // never a JSON string into ::jsonb (#2339).
+ await executeRawJsonb(
+ ctx.engine,
+ `INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)
+ VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb)
+ ON CONFLICT (storage_path) DO UPDATE SET
+ content_hash = EXCLUDED.content_hash,
+ size_bytes = EXCLUDED.size_bytes,
+ mime_type = EXCLUDED.mime_type,
+ ${FILES_METADATA_MERGE_SQL}`,
+ [pageSlug, filename, storagePath, mimeType, stat.size, hash],
+ [{ storage: (ctx.config.storage as { backend: string }).backend }],
+ );
} catch (dbErr) {
// Rollback: clean up storage if DB write failed
try {
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index f4f51d807e..431f2dfd99 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -12,7 +12,7 @@ import { clampSearchLimit } from '../engine.ts';
import type { Page, PageType } from '../types.ts';
import { importFromContent } from '../import-file.ts';
import { serializePageToMarkdown } from '../markdown.ts';
-import { writePageThrough, deletePageThrough, resolvePageWriteTarget, type WriteThroughResult } from '../write-through.ts';
+import { writePageThrough, deletePageThrough, resolvePageWriteTarget, withNoRepoWriteThroughWarning, type WriteThroughResult } from '../write-through.ts';
import { extractPageLinks, isAutoLinkEnabled, isAutoTimelineEnabled, isGlobalBasenameEnabled, parseTimelineEntries, makeResolver, type UnresolvedFrontmatterRef } from '../link-extraction.ts';
// #3190: pack-aware link typing on the put_page auto-link path.
import { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';
@@ -332,7 +332,7 @@ const fetch_page: Operation = {
const put_page: Operation = {
name: 'put_page',
- description: 'Write or replace a page (markdown with frontmatter). REPLACES the entire page; this is not a partial edit. Before modifying an existing page, read its canonical content with `get_page include_content:true`, then submit the complete page. Chunks, embeds, reconciles tags, and (when auto_link/auto_timeline are enabled) extracts + reconciles graph links and timeline entries. Remote (MCP) callers: body wikilinks are NOT reconciled into the graph — auto_link/auto_timeline are skipped for untrusted writers (response reports auto_links: {skipped: "remote"}); use local capture/put_page for link extraction. For large content on Windows (pipe-buffer limit ~45KB) or any file-as-input workflow, use `gbrain capture --file PATH --slug SLUG` — capture reads the file as a Buffer with a binary-NUL guard and adds provenance write-through (v0.39.3.0).',
+ description: 'Write or replace a page (markdown with frontmatter). REPLACES the entire page; this is not a partial edit. Before modifying an existing page, read its canonical content with `get_page include_content:true`, then submit the complete page. Chunks, embeds, reconciles tags, and (when auto_link/auto_timeline are enabled) extracts + reconciles graph links and timeline entries. Remote (MCP) callers: body wikilinks are NOT reconciled into the graph — auto_link/auto_timeline are skipped for untrusted writers (response reports auto_links: {skipped: "remote"}); a stdio `gbrain serve` sweeps them at startup + on idle; `gbrain serve --http` does not self-sweep — run `gbrain sweep --once`, or use local capture/put_page for inline link extraction. Remote callers also receive write_through.warning when the resolved write source has no repo configured, because the DB row has no durable markdown file. For large content on Windows (pipe-buffer limit ~45KB) or any file-as-input workflow, use `gbrain capture --file PATH --slug SLUG` — capture reads the file as a Buffer with a binary-NUL guard and adds provenance write-through (v0.39.3.0).',
params: {
slug: { type: 'string', required: true, description: 'Page slug' },
content: { type: 'string', required: true, description: 'Complete markdown content with YAML frontmatter. REPLACES the entire page; this is not a partial edit. Read the canonical page first with `get_page include_content:true` before modifying it.' },
@@ -633,7 +633,7 @@ const put_page: Operation = {
// been reconciled into the graph.
const hint = 'auto_link/auto_timeline run for trusted local writers only; '
+ 'body wikilinks were saved as text but NOT reconciled into the graph. '
- + 'Use local `gbrain capture`/`gbrain call put_page` for link extraction.';
+ + 'A stdio `gbrain serve` sweeps them at startup + on idle; `gbrain serve --http` does not self-sweep — run `gbrain sweep --once` (delegates to a live serve over IPC), use local `gbrain capture`/`gbrain call put_page` for inline link extraction, or add_link for edges needed now.';
autoLinks = { skipped: 'remote', hint };
autoTimeline = { skipped: 'remote', hint };
} else if (result.parsedPage) {
@@ -831,7 +831,7 @@ const put_page: Operation = {
...(writerLint ? { writer_lint: writerLint } : {}),
...(factsQueued ? { facts_backstop: factsQueued } : {}),
...(chronicleQueued ? { chronicle_backstop: chronicleQueued } : {}),
- ...(writeThrough ? { write_through: writeThrough } : {}),
+ ...(writeThrough ? { write_through: ctx.remote !== false ? withNoRepoWriteThroughWarning(writeThrough, ctx.sourceId ?? 'default') : writeThrough } : {}),
};
},
cliHints: { name: 'put', positional: ['slug'], stdin: 'content' },
@@ -1104,7 +1104,7 @@ async function runAutoLink(
const delete_page: Operation = {
name: 'delete_page',
- description: 'Soft-delete a page. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed.',
+ description: 'Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the result write_through field reports removed + path, or a skipped reason. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed.',
params: {
slug: { type: 'string', required: true, description: "Slug of the page to soft-delete, e.g. 'people/alice-example'." },
source_id: { type: 'string', description: "#4329: source holding the row to soft-delete (a multi-source brain can hold the same slug in several sources). Defaults to ctx.sourceId. Remote callers may only target their write source — federated read grants do not confer delete access." },
@@ -1168,7 +1168,7 @@ const delete_page: Operation = {
const restore_page: Operation = {
name: 'restore_page',
- description: 'v0.26.5 — restore a soft-deleted page (clear deleted_at). Returns success only if the page was actually soft-deleted. After this op, the page reappears in search and in get_page/list_pages without the include_deleted flag.',
+ description: 'v0.26.5 — restore a soft-deleted page (clear deleted_at) and re-create its markdown file on disk (the counterpart to delete_page removing it; the result write_through field reports the outcome). Returns success only if the page was actually soft-deleted. After this op, the page reappears in search and in get_page/list_pages without the include_deleted flag.',
params: {
slug: { type: 'string', required: true, description: "Slug of the soft-deleted page to restore, e.g. 'people/alice-example'." },
source_id: { type: 'string', description: "#4329: source holding the row to restore (a multi-source brain can hold the same slug in several sources). Defaults to ctx.sourceId. Remote callers may only target their write source — federated read grants do not confer restore access." },
diff --git a/src/core/ops/schema-packs.ts b/src/core/ops/schema-packs.ts
index 1a9a5814f5..65cc54c1a7 100644
--- a/src/core/ops/schema-packs.ts
+++ b/src/core/ops/schema-packs.ts
@@ -141,7 +141,10 @@ const schema_lint: Operation = {
// count as declared — parity with the active-pack branch below.
manifest = (await resolveLoadedPack(loader(path))).manifest;
} else {
- const resolved = await loadActivePack({ cfg, remote: ctx.remote ?? true, sourceId: ctx.sourceId });
+ // #4653: tier-4 DB-plane schema_pack, same read get_active_schema_pack does.
+ const { readDbSchemaPack } = await import('../schema-pack/best-effort.ts');
+ const dbConfig = await readDbSchemaPack(ctx.engine);
+ const resolved = await loadActivePack({ cfg, remote: ctx.remote ?? true, sourceId: ctx.sourceId, dbConfig });
manifest = resolved.manifest;
}
// File-plane only over MCP; the engine-aware --with-db opt-in is
@@ -158,8 +161,11 @@ const schema_graph: Operation = {
handler: async (ctx) => {
const { loadActivePack } = await import('../schema-pack/load-active.ts');
const { loadConfig } = await import('../config.ts');
+ const { readDbSchemaPack } = await import('../schema-pack/best-effort.ts');
const cfg = loadConfig();
- const pack = await loadActivePack({ cfg, remote: ctx.remote ?? true, sourceId: ctx.sourceId });
+ // #4653: tier-4 DB-plane schema_pack, same read get_active_schema_pack does.
+ const dbConfig = await readDbSchemaPack(ctx.engine);
+ const pack = await loadActivePack({ cfg, remote: ctx.remote ?? true, sourceId: ctx.sourceId, dbConfig });
const nodes = pack.manifest.page_types.map((t) => ({ name: t.name, primitive: t.primitive }));
const edges: Array<{ from: string; verb: string; to: string }> = [];
for (const lt of pack.manifest.link_types) {
@@ -188,8 +194,11 @@ const schema_explain_type: Operation = {
handler: async (ctx, p) => {
const { loadActivePack } = await import('../schema-pack/load-active.ts');
const { loadConfig } = await import('../config.ts');
+ const { readDbSchemaPack } = await import('../schema-pack/best-effort.ts');
const cfg = loadConfig();
- const pack = await loadActivePack({ cfg, remote: ctx.remote ?? true, sourceId: ctx.sourceId });
+ // #4653: tier-4 DB-plane schema_pack, same read get_active_schema_pack does.
+ const dbConfig = await readDbSchemaPack(ctx.engine);
+ const pack = await loadActivePack({ cfg, remote: ctx.remote ?? true, sourceId: ctx.sourceId, dbConfig });
const found = pack.manifest.page_types.find((t) => t.name === p.type);
if (!found) return { error: 'type_not_found', type: p.type as string, pack: pack.manifest.name };
return { schema_version: 1, pack: pack.manifest.name, type: found };
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 6f4594e2ec..b2b2918bc0 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -24,6 +24,7 @@ import type { HybridSearchMeta } from '../types.ts';
import { bumpLastRetrievedAt } from '../last-retrieved.ts';
import { applySnippetCap, DEFAULT_AGENT_SNIPPET_CHARS } from '../search/snippet-cap.ts';
import { resolveExcludePrivatePages } from '../search/private-visibility.ts';
+import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';
import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION } from '../operations-descriptions.ts';
import { OperationError } from './contract.ts';
import type { Operation, OperationContext } from './contract.ts';
@@ -56,6 +57,44 @@ async function resolveEffectiveLimit(ctx: OperationContext, p: Record<string, un
// --- Search ---
+type SourceScope = { sourceId?: string; sourceIds?: string[] };
+
+/**
+ * #5004: does the caller's read scope still hold markdown pages below the
+ * safe-chunk index version? Every remote chunk read withholds them (the
+ * `requireSafeChunks` predicate in each engine leg) until
+ * `gbrain reindex --markdown` seals them, so an empty remote result on such
+ * a brain is a policy gap, not a clean miss. Same scope precedence as
+ * sourceScopeOpts (federated array > scalar > brain-wide); indexed LIMIT 1
+ * probe, portable SQL on both engines, fail-open.
+ *
+ * The predicate is the plain range `chunker_version < N` (the column is
+ * SMALLINT NOT NULL, so it is the same set as `NOT safeChunksFilter`), NOT
+ * the COALESCE form the read legs use: only the range is sargable, and this
+ * runs on every empty remote result — on a fully sealed brain the COALESCE
+ * form walked every markdown page. The probe deliberately ignores the call's
+ * `types` / `excludePrivate` filters: it answers "is the fence withholding
+ * anything in scope", not "would this exact query have matched".
+ */
+async function hasUnsealedPagesInScope(ctx: OperationContext, scope: SourceScope): Promise<boolean> {
+ const [sourceClause, params] = scope.sourceIds?.length
+ ? ['AND p.source_id = ANY($1::text[])', [scope.sourceIds]]
+ : scope.sourceId
+ ? ['AND p.source_id = $1', [scope.sourceId]]
+ : ['', []];
+ try {
+ const rows = await ctx.engine.executeRaw(
+ `SELECT 1 FROM pages p JOIN sources s ON s.id = p.source_id
+ WHERE p.page_kind = 'markdown' AND p.deleted_at IS NULL AND NOT s.archived
+ AND p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION} ${sourceClause} LIMIT 1`,
+ params,
+ );
+ return rows.length > 0;
+ } catch {
+ return false;
+ }
+}
+
/**
* WP2/D3 + E1: the `retrieval` response-meta payload for the search/query
* ops. Carries the already-computed HybridSearchMeta signal (vector arm,
@@ -63,18 +102,30 @@ async function resolveEffectiveLimit(ctx: OperationContext, p: Record<string, un
* the concept-shaped hint, so an MCP caller can distinguish "clean miss"
* from "the pipeline degraded" without a second call. The `hint` is
* non-contractual prose (agents read it; nothing should parse it).
+ *
+ * #5004: this is the ONE producer of the channel (keyword-only path included,
+ * which never runs hybridSearch), so the safe-chunk fence is disclosed here:
+ * an empty result for a remote caller whose scope still holds unsealed pages
+ * gets `safe_index_pending` appended. The withholding itself is unchanged.
*/
-function buildRetrievalResponseMeta(
+async function buildRetrievalResponseMeta(
+ ctx: OperationContext,
+ scope: SourceScope,
queryText: string,
results: unknown[],
meta: HybridSearchMeta | null,
opts: { conceptHint?: boolean } = {},
-): Record<string, unknown> {
- const m = meta as (HybridSearchMeta & { degraded?: unknown; retrieved_count?: number }) | null;
+): Promise<Record<string, unknown>> {
+ const m = meta as (HybridSearchMeta & { degraded?: unknown[]; retrieved_count?: number }) | null;
const hint = opts.conceptHint && looksConceptShaped(queryText)
? "concept-shaped question — the 'query' tool adds multi-query expansion and recovers " +
'synonym-phrased matches this keyword-leaning search can miss.'
: undefined;
+ const safeIndexPending = results.length === 0 && ctx.remote !== false
+ && await hasUnsealedPagesInScope(ctx, scope);
+ const degraded = safeIndexPending
+ ? [...(m?.degraded ?? []), { stage: 'safe_index_pending' }]
+ : m?.degraded;
return {
returned_count: results.length,
retrieved_count: m?.retrieved_count ?? results.length,
@@ -83,8 +134,8 @@ function buildRetrievalResponseMeta(
expansion_applied: m.expansion_applied,
...(m.cache ? { cache: m.cache.status } : {}),
...(m.token_budget ? { token_budget: m.token_budget } : {}),
- ...(m.degraded !== undefined ? { degraded: m.degraded } : {}),
} : {}),
+ ...(degraded !== undefined ? { degraded } : {}),
...(hint ? { hint } : {}),
};
}
@@ -241,7 +292,7 @@ const search: Operation = {
await stampUnverifiedExtractions(ctx.engine, results, { ...scope, excludePrivate });
bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
maybeCaptureSearch(ctx, queryText, results, Date.now() - startedAt, false);
- ctx.emitResponseMeta?.('retrieval', buildRetrievalResponseMeta(queryText, results, null, { conceptHint: true }));
+ ctx.emitResponseMeta?.('retrieval', await buildRetrievalResponseMeta(ctx, scope, queryText, results, null, { conceptHint: true }));
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return applySnippetCap(results, snippetCap);
}
@@ -268,7 +319,7 @@ const search: Operation = {
const latency_ms = Date.now() - startedAt;
bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
- ctx.emitResponseMeta?.('retrieval', buildRetrievalResponseMeta(queryText, results, capturedMeta, { conceptHint: true }));
+ ctx.emitResponseMeta?.('retrieval', await buildRetrievalResponseMeta(ctx, scope, queryText, results, capturedMeta, { conceptHint: true }));
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return applySnippetCap(results, snippetCap);
},
@@ -694,7 +745,7 @@ const query: Operation = {
// WP2/D3: query never nudges toward itself — no concept hint here.
// #1663: the CRAG grade rides the same retrieval meta channel.
ctx.emitResponseMeta?.('retrieval', {
- ...buildRetrievalResponseMeta(queryText, results, capturedMeta),
+ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, results, capturedMeta)),
crag,
});
// #3800: cap AFTER capture/meta/CRAG so every internal consumer graded
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 7457de9882..fdfd962634 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1716,7 +1716,7 @@ export class PGLiteEngine implements BrainEngine {
`SELECT id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, deleted_at,
effective_date, effective_date_source,
source_kind, source_uri, ingested_via, ingested_at,
- contextual_retrieval_mode
+ contextual_retrieval_mode, source_path
FROM pages WHERE ${where.join(' AND ')}
ORDER BY (source_id = $${anchorParamIdx}) DESC, source_id ASC
LIMIT 1`,
@@ -2033,13 +2033,21 @@ export class PGLiteEngine implements BrainEngine {
sourceId: string,
): Promise<{ migrated: number }> {
// Parity with PostgresEngine.migrateFactsToCanonical. UPDATE preserves
- // every column except entity_slug + source_markdown_slug. Active rows
+ // every column except entity_slug + source_markdown_slug + row_num,
+ // which is offset past canonical's current MAX(row_num) (#4558; NULL
+ // stays NULL, expired rows count — see the Postgres twin). Active rows
// only (expired_at IS NULL) so we don't disturb the supersession audit
// trail.
const { rows } = await this.db.query(
`UPDATE facts
SET entity_slug = $1,
- source_markdown_slug = $1
+ source_markdown_slug = $1,
+ row_num = facts.row_num + COALESCE((
+ SELECT MAX(f2.row_num) FROM facts f2
+ WHERE f2.source_id = $2
+ AND f2.source_markdown_slug = $1
+ AND f2.row_num IS NOT NULL
+ ), 0)
WHERE source_id = $2
AND source_markdown_slug = $3
AND expired_at IS NULL
@@ -5994,7 +6002,7 @@ export class PGLiteEngine implements BrainEngine {
async getCalleesOf(
qualifiedName: string,
- opts?: { sourceId?: string; allSources?: boolean; limit?: number },
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean },
): Promise<import('./types.ts').CodeEdgeResult[]> {
return codeEdgesImpl.getCalleesOf(this.codeEdgesDeps, qualifiedName, opts);
}
diff --git a/src/core/pglite-engine/code-edges.ts b/src/core/pglite-engine/code-edges.ts
index 64dc468922..9aa43c5ada 100644
--- a/src/core/pglite-engine/code-edges.ts
+++ b/src/core/pglite-engine/code-edges.ts
@@ -118,25 +118,36 @@ export async function getCallersOf(
export async function getCalleesOf(
deps: PgliteCodeEdgesDeps,
qualifiedName: string,
- opts?: { sourceId?: string; allSources?: boolean; limit?: number },
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean },
): Promise<import('../types.ts').CodeEdgeResult[]> {
const limit = Math.min(opts?.limit ?? 100, 500);
const sourceClause = opts?.allSources || !opts?.sourceId
? ''
: `AND source_id = '${opts.sourceId.replace(/'/g, "''")}'`;
- const { rows } = await deps.db.query(
+ const run = (fromPredicate: string) => deps.db.query(
`SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
edge_type, edge_metadata, source_id, true as resolved
FROM code_edges_chunk
- WHERE from_symbol_qualified = $1 ${sourceClause}
+ WHERE ${fromPredicate} ${sourceClause}
UNION ALL
SELECT id, from_chunk_id, NULL as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
edge_type, edge_metadata, source_id, false as resolved
FROM code_edges_symbol
- WHERE from_symbol_qualified = $1 ${sourceClause}
+ WHERE ${fromPredicate} ${sourceClause}
LIMIT $2`,
[qualifiedName, limit],
);
+ let { rows } = await run('from_symbol_qualified = $1');
+ // #4670: nested chunks (C#/Java/Ruby/Rust, TS class methods) store a
+ // QUALIFIED from_symbol_qualified, so the exact path misses the bare
+ // method name the op contract accepts. Opt-in only (code_callees op +
+ // CLI): on a zero-row miss for a delimiter-free input, re-key the same
+ // UNION on content_chunks.symbol_name — exact + indexed, never LIKE (`_`
+ // is a wildcard). Off for the code_flow BFS, whose bare leaf names must
+ // not inherit a same-named class method's callees.
+ if (rows.length === 0 && opts?.bareFallback && !/[.#:]/.test(qualifiedName)) {
+ ({ rows } = await run('from_chunk_id IN (SELECT id FROM content_chunks WHERE symbol_name = $1)'));
+ }
return (rows as Record<string, unknown>[]).map(rowToCodeEdge);
}
diff --git a/src/core/pglite-engine/salience.ts b/src/core/pglite-engine/salience.ts
index 648b40e356..3bad2d8dcf 100644
--- a/src/core/pglite-engine/salience.ts
+++ b/src/core/pglite-engine/salience.ts
@@ -62,19 +62,20 @@ export async function setEmotionalWeightBatch(deps: PgliteSalienceDeps, rows: Em
const sourceIds = rows.map(r => r.source_id);
const weights = rows.map(r => r.weight);
// Composite-keyed UPDATE FROM unnest (codex C4#3).
- // v0.29.1: bump salience_touched_at when emotional_weight actually changes
- // so the salience query window picks up newly-salient old pages. Mirror
- // of postgres-engine.ts.
+ // Only rows whose weight actually changes are rewritten (#4797): a same-value
+ // row would fire the per-row BEFORE UPDATE triggers (generation bump +
+ // search_vector) for nothing — on a first full-brain pass that is nearly
+ // every page — and PGLite runs the statement synchronously on the main
+ // thread. salience_touched_at bumps on every rewritten row so the salience
+ // window picks up newly-salient old pages. Mirror of postgres-engine.
const result = await deps.db.query(
`UPDATE pages
SET emotional_weight = u.weight,
- salience_touched_at = CASE
- WHEN pages.emotional_weight IS DISTINCT FROM u.weight THEN now()
- ELSE pages.salience_touched_at
- END
+ salience_touched_at = now()
FROM unnest($1::text[], $2::text[], $3::real[])
AS u(slug, source_id, weight)
WHERE pages.slug = u.slug AND pages.source_id = u.source_id
+ AND pages.emotional_weight IS DISTINCT FROM u.weight
RETURNING 1`,
[slugs, sourceIds, weights]
);
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 43963302b0..41d2ccce58 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -697,7 +697,7 @@ export class PostgresEngine implements BrainEngine {
SELECT id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, deleted_at,
effective_date, effective_date_source,
source_kind, source_uri, ingested_via, ingested_at,
- contextual_retrieval_mode
+ contextual_retrieval_mode, source_path
FROM pages
WHERE slug = ${slug} ${sourceCondition} ${deletedCondition} ${privacy}
ORDER BY (source_id = ${anchorSourceId}) DESC, source_id ASC
@@ -1009,8 +1009,15 @@ export class PostgresEngine implements BrainEngine {
): Promise<{ migrated: number }> {
const sql = this.sql;
// UPDATE preserves every other column (embedding, valid_*, kind,
- // status, notability, confidence, source_session, ...). Idempotent
- // by virtue of the WHERE clause matching nothing on re-run.
+ // status, notability, confidence, source_session, ...) except
+ // row_num, which is offset past canonical's current MAX(row_num)
+ // (#4558): canonical already owns fence rows 1..N, so carrying the
+ // phantom's row_num across collides on the partial UNIQUE
+ // idx_facts_fence_key. Same seed rule fence-write.ts uses for that
+ // index. MAX counts expired rows too (the index only excludes NULL);
+ // NULL + M stays NULL (legacy-guard semantics intact). extract_facts
+ // hasRowNumDrift re-harmonises the numbering against the disk fence.
+ // Idempotent by virtue of the WHERE clause matching nothing on re-run.
//
// We scope to `expired_at IS NULL` so the migration touches only
// active facts. Forgotten / superseded rows that already carry an
@@ -1020,7 +1027,13 @@ export class PostgresEngine implements BrainEngine {
const result = await sql`
UPDATE facts
SET entity_slug = ${canonicalSlug},
- source_markdown_slug = ${canonicalSlug}
+ source_markdown_slug = ${canonicalSlug},
+ row_num = facts.row_num + COALESCE((
+ SELECT MAX(f2.row_num) FROM facts f2
+ WHERE f2.source_id = ${sourceId}
+ AND f2.source_markdown_slug = ${canonicalSlug}
+ AND f2.row_num IS NOT NULL
+ ), 0)
WHERE source_id = ${sourceId}
AND source_markdown_slug = ${phantomSlug}
AND expired_at IS NULL
@@ -5462,7 +5475,7 @@ export class PostgresEngine implements BrainEngine {
async getCalleesOf(
qualifiedName: string,
- opts?: { sourceId?: string; allSources?: boolean; limit?: number },
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean },
): Promise<import('./types.ts').CodeEdgeResult[]> {
return codeEdgesImpl.getCalleesOf(this.codeEdgesDeps, qualifiedName, opts);
}
diff --git a/src/core/postgres-engine/code-edges.ts b/src/core/postgres-engine/code-edges.ts
index b17752a8c6..fd8ad53f09 100644
--- a/src/core/postgres-engine/code-edges.ts
+++ b/src/core/postgres-engine/code-edges.ts
@@ -110,26 +110,33 @@ export async function getCallersOf(
export async function getCalleesOf(
deps: PgCodeEdgesDeps,
qualifiedName: string,
- opts?: { sourceId?: string; allSources?: boolean; limit?: number },
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean },
): Promise<import('../types.ts').CodeEdgeResult[]> {
const sql = deps.sql;
const limit = Math.min(opts?.limit ?? 100, 500);
const scopedSource: string | null =
!opts?.allSources && opts?.sourceId ? opts.sourceId : null;
- const rows = await sql`
+ const run = (fromPredicate: ReturnType<typeof sql>) => sql`
SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
edge_type, edge_metadata, source_id, true as resolved
FROM code_edges_chunk
- WHERE from_symbol_qualified = ${qualifiedName}
+ WHERE ${fromPredicate}
${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
UNION ALL
SELECT id, from_chunk_id, NULL::int as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
edge_type, edge_metadata, source_id, false as resolved
FROM code_edges_symbol
- WHERE from_symbol_qualified = ${qualifiedName}
+ WHERE ${fromPredicate}
${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
LIMIT ${limit}
`;
+ let rows = await run(sql`from_symbol_qualified = ${qualifiedName}`);
+ // #4670: parity twin of the PGLite fallback — see pglite-engine/code-edges.ts.
+ // Opt-in; zero-row exact miss + delimiter-free input re-keys on the bare
+ // content_chunks.symbol_name (exact, never LIKE).
+ if (rows.length === 0 && opts?.bareFallback && !/[.#:]/.test(qualifiedName)) {
+ rows = await run(sql`from_chunk_id IN (SELECT id FROM content_chunks WHERE symbol_name = ${qualifiedName})`);
+ }
return rows.map(r => pgRowToCodeEdge(r as Record<string, unknown>));
}
diff --git a/src/core/postgres-engine/salience.ts b/src/core/postgres-engine/salience.ts
index c1253b8e6f..bff97abfc7 100644
--- a/src/core/postgres-engine/salience.ts
+++ b/src/core/postgres-engine/salience.ts
@@ -88,22 +88,21 @@ export async function setEmotionalWeightBatch(deps: PgSalienceDeps, rows: Emotio
// Composite-keyed UPDATE FROM unnest (codex C4#3): pages.slug is unique
// only within a source, so a slug-only join would fan out across sources.
//
- // v0.29.1: bump salience_touched_at to NOW() ONLY when emotional_weight
- // actually changes. The salience query window then includes the page in
- // GREATEST(updated_at, salience_touched_at) >= boundary, so a previously
- // calm page that just became salient surfaces in the recent salience
- // results without a content edit. No-op writes (same weight) leave
- // salience_touched_at alone — preserves "actual change" semantics.
+ // Only rows whose emotional_weight actually changes are rewritten (#4797):
+ // a same-value row is skipped entirely — no new tuple version, no per-row
+ // BEFORE UPDATE trigger fan-out (generation bump + search_vector), not
+ // counted in the return value. Every rewritten row bumps
+ // salience_touched_at to NOW() so the salience query window
+ // (GREATEST(updated_at, salience_touched_at) >= boundary) surfaces a
+ // previously calm page that just became salient without a content edit.
const result = await sql`
UPDATE pages
SET emotional_weight = u.weight,
- salience_touched_at = CASE
- WHEN pages.emotional_weight IS DISTINCT FROM u.weight THEN now()
- ELSE pages.salience_touched_at
- END
+ salience_touched_at = now()
FROM unnest(${slugs}::text[], ${sourceIds}::text[], ${weights}::real[])
AS u(slug, source_id, weight)
WHERE pages.slug = u.slug AND pages.source_id = u.source_id
+ AND pages.emotional_weight IS DISTINCT FROM u.weight
RETURNING 1
`;
return result.length;
diff --git a/src/core/schema-pack/best-effort.ts b/src/core/schema-pack/best-effort.ts
index 50b344743a..16f0f37ec5 100644
--- a/src/core/schema-pack/best-effort.ts
+++ b/src/core/schema-pack/best-effort.ts
@@ -53,12 +53,34 @@ export async function loadActivePackBestEffort(
cfg: loadConfig(),
remote: ctx.remote ?? true,
sourceId: ctx.sourceId,
+ // #4653: tier-4 DB-plane schema_pack. Without it every caller here fell
+ // through to the file/default tiers while `schema active` and
+ // get_active_schema_pack honored the DB tier — a split resolution
+ // inside one process.
+ dbConfig: await readDbSchemaPack(ctx.engine),
});
} catch {
return null;
}
}
+/**
+ * Read the DB-plane `schema_pack` key (tier 4) from a live engine. Null-safe
+ * and never throws: callers without an engine (tests pass `engine: null`) or
+ * on brains predating the config table get undefined and fall through to
+ * env/file resolution. ONE spelling of the tier-4 read, shared by the CLI
+ * inspection verbs, the MCP schema ops and both loaders in this module.
+ */
+export async function readDbSchemaPack(
+ engine: Pick<BrainEngine, 'getConfig'> | null | undefined,
+): Promise<string | undefined> {
+ try {
+ return (await engine?.getConfig?.('schema_pack'))?.trim() || undefined;
+ } catch {
+ return undefined;
+ }
+}
+
/**
* Resolve the active pack for a LOCAL, engine-backed surface.
*
@@ -70,11 +92,11 @@ export async function loadActivePackBestEffort(
* OperationContext (and passes something like `{ engine } as never`)
* silently runs under REMOTE trust gating. A tier-1 trust rejection then
* returns null — indistinguishable from "there is no pack".
- * - **DB-side pack visibility.** Reads the engine's `schema_pack` config key
- * and pairs it with FILE-ONLY config, so a post-unify DB-side pack flip is
- * visible. Full `loadConfig()` merges transient env/database state and can
- * resolve a DIFFERENT pack than the onboard checks do — which is how a
- * recommender and its handler end up disagreeing about the same brain.
+ * - **FILE-ONLY config.** Pairs the engine's `schema_pack` config key with
+ * `loadConfigFileOnly()`, matching the onboard checks. Full `loadConfig()`
+ * merges transient env/database state and can resolve a DIFFERENT pack
+ * than the onboard checks do — which is how a recommender and its handler
+ * end up disagreeing about the same brain.
*
* Same null contract as `loadActivePackBestEffort` (D4): null means the pack
* could not be resolved and is NOT a license to fall back to hardcoded
@@ -90,10 +112,7 @@ export async function loadActivePackForLocalEngine(
engine: Pick<BrainEngine, 'getConfig'>,
): Promise<ResolvedPack | null> {
try {
- let dbConfig: string | undefined;
- try {
- dbConfig = (await engine.getConfig('schema_pack')) ?? undefined;
- } catch { /* engine.config may not exist on very old brains */ }
+ const dbConfig = await readDbSchemaPack(engine);
return await loadActivePack({ cfg: loadConfigFileOnly(), remote: false, dbConfig })
.catch(() => null);
} catch {
diff --git a/src/core/schema-pack/load-active.ts b/src/core/schema-pack/load-active.ts
index 61c41498a1..8e51850bca 100644
--- a/src/core/schema-pack/load-active.ts
+++ b/src/core/schema-pack/load-active.ts
@@ -38,6 +38,7 @@ import {
type ResolutionResult,
} from './registry.ts';
import { isBundledPackName } from './bundled.ts';
+import { isValidPackName } from './mutate.ts';
import { bundledPackPath } from './bundled-assets.ts';
/**
@@ -111,7 +112,11 @@ function defaultPackLocator(name: string): string | null {
if (existsSync(repoRootFallback)) return repoRootFallback;
return null;
}
- // User-installed pack at ~/.gbrain/schema-packs/<name>/pack.{yaml,json}
+ // User-installed pack at ~/.gbrain/schema-packs/<name>/pack.{yaml,json}.
+ // SECURITY: `name` can come from the tier-4/5 DB or gbrain.yml string —
+ // gate it (same slug grammar as locateMutablePackFile) BEFORE the join so
+ // a path-shaped value can't reach anything outside schema-packs/.
+ if (!isValidPackName(name)) return null;
const baseDir = gbrainPath('schema-packs', name);
const candidates = ['pack.yaml', 'pack.yml', 'pack.json'];
for (const c of candidates) {
diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts
index 5e75285619..dcf8121063 100644
--- a/src/core/search/hybrid.ts
+++ b/src/core/search/hybrid.ts
@@ -12,6 +12,9 @@
import { sanitizeRemoteBody } from '../remote-body.ts';
import type { BrainEngine } from '../engine.ts';
import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts';
+// Type-only (erased at compile time — mode.ts stays a runtime dynamic import
+// at each call site below): the loaded snapshot shape for _searchModeInput.
+import type { ResolveSearchModeInput } from './mode.ts';
import type {
SearchResult,
PageReadPolicy,
@@ -1102,6 +1105,19 @@ export interface HybridSearchOpts extends SearchOpts {
* public contract.
*/
_telemetryCacheStatus?: 'miss' | 'disabled';
+
+ /**
+ * INTERNAL (#4359) — the LOADED search-mode config snapshot (the return
+ * value of `loadSearchModeConfig`), threaded from `hybridSearchCached`
+ * into the inner `hybridSearch` so the cached path reads the config table
+ * once and both sides resolve from the SAME snapshot (two independent
+ * reads let a mid-request config change key the cache row from a stale
+ * snapshot). Only the LOADED snapshot is shared — each site still calls
+ * `resolveSearchMode` itself (the wrapper folds in cache-only knobs), so
+ * bare `hybridSearch` keeps resolving on its own for direct callers
+ * (`[CDX-5+6]`), which leave this undefined. Not part of the public contract.
+ */
+ _searchModeInput?: ResolveSearchModeInput;
}
/**
@@ -1254,8 +1270,9 @@ export async function hybridSearch(
// because eval-replay and eval-longmemeval call bare hybridSearch — and
// per-mode evals would not test production search if modes lived only in
// the wrapper. See `[CDX-5+6]` in the plan.
+ // (#4359) hybridSearchCached threads its already-loaded snapshot; reuse it.
const { loadSearchModeConfig, resolveSearchMode } = await import('./mode.ts');
- const modeInput = await loadSearchModeConfig(engine);
+ const modeInput = opts?._searchModeInput ?? await loadSearchModeConfig(engine);
const resolvedMode = resolveSearchMode({
// T4/D5 — per-call mode selector (e.g. `--mode tokenmax`). The op layer
// only passes this for trusted/local callers; remote callers leave it
@@ -2822,18 +2839,10 @@ export async function hybridSearchCached(
// resolver bare hybridSearch's own `resolvedMode` uses (including 0 —
// see mode.ts `resolveSearchMode`'s `pick()`), so mirroring it here
// keeps hit/miss consistent for the common case without a second
- // config round-trip. Caveat: this is a SEPARATE `resolveSearchMode`
- // call from the one bare hybridSearch performs internally on a miss
- // (hybrid.ts's inner `resolvedMode`, computed when `hybridSearch` is
- // invoked below) — not literally the same object — so a `search.mode`
- // / `search.searchLimit` config change landing between these two
- // resolutions within one request could theoretically desync the
- // stored row's actual size from what its own `knobsHash` (built from
- // `resolvedForCache`) implies. Narrow and pre-existing (the double
- // resolution itself predates this PR); tracked as #4359, not fixed
- // here — closing it would mean threading one resolved snapshot into
- // the inner `hybridSearch` call, a larger change than this PR's
- // `|| 20` → `|| resolvedMode.searchLimit` substitution.
+ // config round-trip. This is still a SEPARATE `resolveSearchMode` call
+ // from the inner one (the wrapper folds in a `cache_enabled` perCall
+ // knob), but both now resolve from the SAME loaded snapshot — the miss
+ // path threads it via `_searchModeInput` (#4359).
const limit = opts?.limit || resolvedForCache.searchLimit;
const offset = opts?.offset || 0;
const sliced = scopedResults.slice(offset, offset + limit);
@@ -2918,6 +2927,8 @@ export async function hybridSearchCached(
// function) with the cache-consult outcome. 'hit' already returned above,
// so only miss/disabled reach this call.
_telemetryCacheStatus: cacheStatus === 'disabled' ? 'disabled' : 'miss',
+ // (#4359) one config read per call: thread the snapshot loaded above.
+ _searchModeInput: modeInputForCache,
onMeta: (m) => {
innerMetaBox.current = m;
// Do NOT call userOnMeta here — we'll emit a merged meta below
diff --git a/src/core/search/mode.ts b/src/core/search/mode.ts
index 369c0c2fd8..7d4113befc 100644
--- a/src/core/search/mode.ts
+++ b/src/core/search/mode.ts
@@ -873,7 +873,7 @@ export function attributeKnob<K extends keyof ModeBundle>(
return { knob, value: resolved[knob], source: 'per-call', source_detail: 'SearchOpts' };
}
if (ov[knob] !== undefined) {
- return { knob, value: resolved[knob], source: 'override', source_detail: `config: search.${knob}` };
+ return { knob, value: resolved[knob], source: 'override', source_detail: `config: ${KNOB_CONFIG_KEY[knob]}` };
}
if (resolved.mode_valid) {
return { knob, value: resolved[knob], source: 'mode', source_detail: `mode: ${resolved.resolved_mode}` };
@@ -1643,57 +1643,57 @@ export function loadOverridesFromConfig(
return out;
}
+/**
+ * knob → the config key `loadOverridesFromConfig` reads it from (#4605). The
+ * Record type forces a row per ModeBundle knob. `attributeKnob` prints these
+ * (the dashboard's copy-pasteable `config set` target — knob name and key
+ * spelling differ for 14 of them); SEARCH_MODE_CONFIG_KEYS derives from it;
+ * KNOWN_CONFIG_KEYS (config.ts, kept import-light) mirrors it by hand, pinned
+ * equal by test/config-search-registry.test.ts.
+ */
+export const KNOB_CONFIG_KEY: Readonly<Record<keyof ModeBundle, string>> = Object.freeze({
+ cache_enabled: 'search.cache.enabled',
+ cache_similarity_threshold: 'search.cache.similarity_threshold',
+ cache_ttl_seconds: 'search.cache.ttl_seconds',
+ intentWeighting: 'search.intentWeighting',
+ keywordOrFallback: 'search.keywordOrFallback',
+ tokenBudget: 'search.tokenBudget',
+ expansion: 'search.expansion',
+ expansion_variant_budget: 'search.expansion_variant_budget',
+ searchLimit: 'search.searchLimit',
+ reranker_enabled: 'search.reranker.enabled',
+ reranker_model: 'search.reranker.model',
+ reranker_top_n_in: 'search.reranker.top_n_in',
+ reranker_top_n_out: 'search.reranker.top_n_out',
+ reranker_timeout_ms: 'search.reranker.timeout_ms',
+ floor_ratio: 'search.floor_ratio',
+ title_boost: 'search.title_boost',
+ evidence_cosine_floor: 'search.evidence_cosine_floor',
+ cross_modal_both_text_weight: 'search.cross_modal.both_mode_text_weight',
+ cross_modal_both_image_weight: 'search.cross_modal.both_mode_image_weight',
+ image_query_text_refinement_weight: 'search.image_query.text_refinement_weight',
+ image_query_image_refinement_weight: 'search.image_query.image_refinement_weight',
+ unified_multimodal: 'search.unified_multimodal',
+ unified_multimodal_only: 'search.unified_multimodal_only',
+ cross_modal_llm_intent: 'search.cross_modal.llm_intent',
+ graph_signals: 'search.graph_signals',
+ // Per-mode default lives in the bundle; these let power users override at
+ // the per-key level without flipping the global mode.
+ contextual_retrieval: 'search.contextual_retrieval',
+ contextual_retrieval_disabled: 'search.contextual_retrieval_disabled',
+ autocut: 'search.autocut',
+ autocut_jump: 'search.autocut_jump',
+ autocut_min_top: 'search.autocut_min_top',
+ autocut_min_keep: 'search.autocut_min_keep',
+ relationalRetrieval: 'search.relational_retrieval',
+ relational_retrieval_depth: 'search.relational_retrieval_depth',
+ relational_rerank_pin: 'search.relational_rerank_pin',
+ keyword_arm_confidence_floor: 'search.keyword_arm_confidence_floor',
+ metadata_boost_gate: 'search.metadata_boost_gate',
+});
+
/** The full list of config keys this module reads. Used by `gbrain search modes --reset`. */
-export const SEARCH_MODE_CONFIG_KEYS: ReadonlyArray<string> = Object.freeze([
- 'search.cache.enabled',
- 'search.cache.similarity_threshold',
- 'search.cache.ttl_seconds',
- 'search.intentWeighting',
- 'search.keywordOrFallback',
- 'search.tokenBudget',
- 'search.expansion',
- 'search.expansion_variant_budget',
- 'search.searchLimit',
- // v0.35.0.0+ reranker keys
- 'search.reranker.enabled',
- 'search.reranker.model',
- 'search.reranker.top_n_in',
- 'search.reranker.top_n_out',
- 'search.reranker.timeout_ms',
- // v0.35.6.0 — floor-ratio gate
- 'search.floor_ratio',
- 'search.title_boost',
- 'search.evidence_cosine_floor',
- // v0.36 cross-modal keys (D3)
- 'search.cross_modal.both_mode_text_weight',
- 'search.cross_modal.both_mode_image_weight',
- 'search.image_query.text_refinement_weight',
- 'search.image_query.image_refinement_weight',
- 'search.unified_multimodal',
- 'search.unified_multimodal_only',
- 'search.cross_modal.llm_intent',
- // v0.40.4 graph signals
- 'search.graph_signals',
- // v0.40.3.0 contextual retrieval — tier override + soft kill switch.
- // Per-mode default lives in the bundle; this key lets power users
- // override at the per-key level without flipping the global mode.
- 'search.contextual_retrieval',
- 'search.contextual_retrieval_disabled',
- // v0.42.3.0 autocut
- 'search.autocut',
- // v0.43 relational recall
- 'search.relational_retrieval',
- 'search.relational_retrieval_depth',
- // Ranker wave (R1) relational rerank pin
- 'search.relational_rerank_pin',
- // Ranker wave (Phase E2) keyword-arm confidence floor
- 'search.keyword_arm_confidence_floor',
- // Ranker wave (Phase E3) metadata boost gate
- 'search.metadata_boost_gate',
- 'search.autocut_jump',
- 'search.autocut_min_top',
- 'search.autocut_min_keep',
-]);
+export const SEARCH_MODE_CONFIG_KEYS: ReadonlyArray<string> = Object.freeze(Object.values(KNOB_CONFIG_KEY));
/**
* The mode-selection config key itself. Separated from SEARCH_MODE_CONFIG_KEYS
@@ -1705,11 +1705,15 @@ export const SEARCH_MODE_KEY = 'search.mode';
/**
* Load the live mode config (mode + per-key overrides) from the brain engine.
* This reads SEARCH_MODE_KEY plus every SEARCH_MODE_CONFIG_KEYS entry, and it
- * runs on every search (twice on the cached path, which resolves the mode
- * before and inside hybridSearch). One key per round trip is free on PGLite
- * and is most of the pre-retrieval wall clock on a hosted Postgres (dozens of
- * pooler-slot grabs per query), so read the whole config table once and
- * answer every key from that snapshot. See config-snapshot.ts.
+ * runs once per direct `hybridSearch` call. (#4359, fixed) On the cached path
+ * it also runs exactly once — `hybridSearchCached` loads the snapshot to
+ * resolve its own cache-key knobs, then threads that SAME snapshot into the
+ * inner `hybridSearch` call (the INTERNAL `HybridSearchOpts._searchModeInput`
+ * field in hybrid.ts) instead of letting it load a second, independent one.
+ * One key per round trip is free on PGLite and is most of the pre-retrieval
+ * wall clock on a hosted Postgres (dozens of pooler-slot grabs per query), so
+ * read the whole config table once and answer every key from that snapshot.
+ * See config-snapshot.ts.
*
* Errors are swallowed and fall through to mode-bundle defaults. The cache
* config table predates v0.32.3 and may not exist on very old brains, and an
diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.ts
index 3dc8564a38..49cc7c22f7 100644
--- a/src/core/search/modes-report.ts
+++ b/src/core/search/modes-report.ts
@@ -91,12 +91,17 @@ export function formatKnobValue(knob: string, value: unknown): string {
* the BRAIN-LEVEL planes (config override > mode bundle); per-call
* SearchOpts overrides on individual searches are not represented here —
* a live search that passes its own knobs can legitimately differ from
- * this report for that one call.
+ * this report for that one call. #4601: the `query` op ALWAYS supplies
+ * `expand` (default on), so the `expansion` row never governs it — say so
+ * here, on the surface operators actually read, or the dashboard gives a
+ * confident wrong answer for the primary agent verb.
*/
export const MODES_REPORT_PER_CALL_NOTE =
'Resolved from config overrides + the active mode bundle. Per-call SearchOpts ' +
'overrides on individual searches are not shown — a call that passes its own ' +
- 'knobs (e.g. expand, autocut, relational) wins for that call only.';
+ 'knobs (e.g. expand, autocut, relational) wins for that call only. The `query` ' +
+ 'op always passes `expand` (default on; `--no-expand` opts out), so the ' +
+ '`expansion` row here does not govern it.';
export interface SearchModesReport {
schema_version: 2;
diff --git a/src/core/skillopt/orchestrator.ts b/src/core/skillopt/orchestrator.ts
index 0720290d88..3528e83732 100644
--- a/src/core/skillopt/orchestrator.ts
+++ b/src/core/skillopt/orchestrator.ts
@@ -553,6 +553,35 @@ async function runOptimizationLoop(
// Apply under LR budget.
const applied = applyEditBatch(checkpoint!.best_skill_text, fresh, lrBudget);
+ if (fresh.length === 0) {
+ // #4741: the optimizer proposed NOTHING (reflect returned/parsed no
+ // edits, or every edit was already in the rejected buffer). This
+ // used to fall into the all-rejected branch below ([].every() is
+ // true) and log the same 'no_edits_applied' as "gated N candidates
+ // and rejected all" — so a whole run of zero candidates read as a
+ // real `no_improvement`. Say so per step; nothing to reject-buffer.
+ const why = reflectResult.errors[0]
+ ? `no_edits_proposed: ${reflectResult.errors[0]}`
+ : 'no_edits_proposed';
+ process.stderr.write(`[skillopt] epoch ${epoch} step ${step}: optimizer proposed no edits (${why})\n`);
+ logEvent({
+ kind: 'step',
+ run_id: runId,
+ skill: skillName,
+ epoch,
+ step,
+ sel_score_median: checkpoint!.best_sel_score,
+ sel_score_runs: [],
+ accepted: false,
+ edits_attempted: 0,
+ edits_applied: 0,
+ delta: 0,
+ reason: why,
+ cumulative_cost_usd: tracker.snapshot().cumulativeCostUsd,
+ } as never);
+ continue;
+ }
+
if (applied.results.every((r) => r.outcome === 'rejected')) {
// Nothing applied; record rejected entries + skip gate.
const newRejections = fresh.map((e) =>
diff --git a/src/core/skillopt/validate-gate.ts b/src/core/skillopt/validate-gate.ts
index 7776d47487..3118281212 100644
--- a/src/core/skillopt/validate-gate.ts
+++ b/src/core/skillopt/validate-gate.ts
@@ -61,6 +61,15 @@ export const SKILLOPT_RUNTIME_EXCEEDED = 'skillopt_runtime_exceeded';
function isRuntimeExceeded(e: unknown): boolean {
return e instanceof Error && e.message === SKILLOPT_RUNTIME_EXCEEDED;
}
+/**
+ * #4741 — every task in a gate failed (dead target provider, e.g. a logged-out
+ * claude-cli child) / every rollout's judge errored (dead judge provider).
+ * Thrown instead of scoring the gate 0.000, so the orchestrator's catch-all
+ * ends the run `errored` with the first provider error as abort_detail.
+ */
+export const SKILLOPT_ALL_ROLLOUTS_FAILED = 'skillopt_all_rollouts_failed';
+export const SKILLOPT_ALL_JUDGE_ERRORS = 'skillopt_all_judge_errors';
+const errMsg = (e: unknown): string => (e instanceof Error ? e.message : String(e));
/**
* Run the validation gate against a candidate skill. Returns GateResult
@@ -124,6 +133,20 @@ export async function runValidationGate(opts: ValidateGateOpts): Promise<GateRes
);
if (aborter && !aborter.ok) throw aborter.error;
+ // #4741: a 100%-failed gate is not a measurement. Any plain (non-tagged)
+ // provider error — a logged-out claude-cli child, a dead endpoint — lands
+ // here as an ordinary !ok item; scoring all of them 0 let a dead provider
+ // finish the whole run as a plausible `no_improvement` / 0.000. Partial
+ // failure below keeps the pessimistic per-task 0 (scoring noise).
+ const failed = settled.filter((s) => s && !s.ok);
+ if (settled.length > 0 && failed.length === settled.length) {
+ const first = failed[0]!.ok ? undefined : failed[0]!.error;
+ throw new Error(
+ `${SKILLOPT_ALL_ROLLOUTS_FAILED}: every task in this gate failed (${failed.length}/${settled.length}); first error: ${errMsg(first)}`,
+ { cause: first },
+ );
+ }
+
// SettledItem<TOut>[] — extract successful results; treat (non-abort) errors as
// score=0 (pessimistic fallback consistent with the judge fail-open posture).
// Errored tasks contribute no scoredRollouts (caller's reflect sees fewer
@@ -133,6 +156,15 @@ export async function runValidationGate(opts: ValidateGateOpts): Promise<GateRes
return { task_id: opts.selSet[idx]!.task_id, median: 0, runs: [] };
});
const scoredRollouts: ScoredRollout[] = settled.flatMap((s) => (s && s.ok) ? s.value.rollouts : []);
+ // #4741: same rule for the judge side. scoreLlm fails open per rollout
+ // (score 0 + judge_error) so one flaky judge call is noise; EVERY rollout
+ // carrying a judge_error is a dead judge provider, not a 0.000 skill.
+ // Rule/qrels judges never set judge_error, so only the LLM judge trips it.
+ if (scoredRollouts.length > 0 && scoredRollouts.every((r) => r.judge_error)) {
+ throw new Error(
+ `${SKILLOPT_ALL_JUDGE_ERRORS}: every rollout's judge failed (${scoredRollouts.length}/${scoredRollouts.length}); first error: ${scoredRollouts[0]!.judge_error}`,
+ );
+ }
const selScore = perTaskMedians.length === 0
? 0
: perTaskMedians.reduce((acc, r) => acc + r.median, 0) / perTaskMedians.length;
diff --git a/src/core/sources-load.ts b/src/core/sources-load.ts
index 6b49d124ea..66a167ae00 100644
--- a/src/core/sources-load.ts
+++ b/src/core/sources-load.ts
@@ -144,7 +144,8 @@ export function parseSourceConfig(config: unknown): Record<string, unknown> {
const shape = recoveredArray ? 'historical JSON array' : `${layers}-layer nested JSON string`;
console.warn(
`[gbrain] source config was stored as a ${shape}; ` +
- `it will be repaired on the next config write. Run 'gbrain doctor' to find affected sources.`,
+ `it will be repaired on the next config-column write (e.g. 'gbrain sources federate' / 'unfederate'). ` +
+ `Run 'gbrain doctor' to find affected sources.`,
);
}
return value ?? {};
diff --git a/src/core/sql-query.ts b/src/core/sql-query.ts
index 3208208778..e23507f922 100644
--- a/src/core/sql-query.ts
+++ b/src/core/sql-query.ts
@@ -141,3 +141,17 @@ export async function executeRawJsonb<R = Record<string, unknown>>(
const params: unknown[] = [...scalarParams, ...jsonbParams];
return engine.executeRaw<R>(sql, params);
}
+
+/**
+ * `ON CONFLICT (storage_path) DO UPDATE SET` fragment for `files.metadata`,
+ * shared by every files upsert (CLI upload / upload-raw / smart upload / sync
+ * in `src/commands/files.ts`, the MCP `file_upload` op in `src/core/ops/files.ts`).
+ * jsonb `||` merges only object||object — any other left operand is
+ * ARRAY-WRAPPED, so a bare `files.metadata || EXCLUDED.metadata` would turn a
+ * #2339-era string-scalar row (`"{}"`, the shape `gbrain repair-jsonb` heals
+ * via `jsonb_typeof = 'string'`) into `["{}", {...}]`: invisible to
+ * repair-jsonb and unreadable by every `.storage` reader. Reset anything that
+ * isn't already an object to `{}` before merging.
+ */
+export const FILES_METADATA_MERGE_SQL =
+ `metadata = (CASE WHEN jsonb_typeof(files.metadata) = 'object' THEN files.metadata ELSE '{}'::jsonb END) || EXCLUDED.metadata`;
diff --git a/src/core/sync-cost-gate.ts b/src/core/sync-cost-gate.ts
index 6822cd4369..e1dd89b540 100644
--- a/src/core/sync-cost-gate.ts
+++ b/src/core/sync-cost-gate.ts
@@ -365,8 +365,13 @@ interface CostGateContext {
autoSubmitEnabled: boolean;
}
+/**
+ * #4684: under `--json` a proceed path never prints — it hands its status
+ * object back as `notice` so the caller nests it in the ONE terminal envelope
+ * (`cost_gate`). Human output and every 'stop' path print here unchanged.
+ */
type CostGateOutcome =
- | { action: 'proceed'; autoDeferEmbeds: boolean }
+ | { action: 'proceed'; autoDeferEmbeds: boolean; notice?: Record<string, unknown> }
| { action: 'stop' };
type ManualDrainReason = 'no_worker_surface' | 'auto_submit_disabled';
@@ -466,15 +471,14 @@ export async function runInlineCostGate(
return { action: 'stop' };
}
if (jsonOut) {
- console.log(JSON.stringify({
+ return { action: 'proceed', autoDeferEmbeds: false, notice: {
status: 'manual_drain_required', mode, gate: 'manual_drain_required',
reason: manualDrainReason, workerSurface: ctx.workerSurface.status, staleChars, staleCostUsd,
capUsd: formatUsdLimit(capUsd), floorUsd: formatUsdLimit(floorUsd),
model: embeddingModelName, manualCommands: commands,
- }));
- } else {
- console.log(manualMsg);
+ } };
}
+ console.log(manualMsg);
return { action: 'proceed', autoDeferEmbeds: false };
}
if (dryRun) {
@@ -487,10 +491,9 @@ export async function runInlineCostGate(
return { action: 'stop' };
}
if (jsonOut) {
- console.log(JSON.stringify({ status: 'deferred', mode, gate: 'deferred_notice', staleChars, staleCostUsd, capUsd: formatUsdLimit(capUsd), floorUsd: formatUsdLimit(floorUsd), queuedBackfills, model: embeddingModelName }));
- } else {
- console.log(deferredMsg);
+ return { action: 'proceed', autoDeferEmbeds: false, notice: { status: 'deferred', mode, gate: 'deferred_notice', staleChars, staleCostUsd, capUsd: formatUsdLimit(capUsd), floorUsd: formatUsdLimit(floorUsd), queuedBackfills, model: embeddingModelName } };
}
+ console.log(deferredMsg);
return { action: 'proceed', autoDeferEmbeds: false };
}
@@ -529,10 +532,9 @@ export async function runInlineCostGate(
// cost isn't the constraint; don't defer).
if (posture === 'tokenmax') {
if (jsonOut) {
- console.log(JSON.stringify({ status: 'proceeding', mode, gate: 'posture_tokenmax', newTokens: inline.tokens, estimateKind: inline.estimateKind, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName, hint: SPEND_HINT }));
- } else {
- console.log(`${previewMsg} spend.posture=tokenmax: proceeding (informational). ${SPEND_HINT}`);
+ return { action: 'proceed', autoDeferEmbeds: false, notice: { status: 'proceeding', mode, gate: 'posture_tokenmax', newTokens: inline.tokens, estimateKind: inline.estimateKind, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName, hint: SPEND_HINT } };
}
+ console.log(`${previewMsg} spend.posture=tokenmax: proceeding (informational). ${SPEND_HINT}`);
return { action: 'proceed', autoDeferEmbeds: false };
}
@@ -567,45 +569,42 @@ export async function runInlineCostGate(
if (manualDrainReason) {
const commands = manualDrainCommands(sources);
if (jsonOut) {
- console.log(JSON.stringify({
+ return { action: 'proceed', autoDeferEmbeds: true, notice: {
status: 'manual_drain_required', mode, gate: 'manual_drain_required',
reason: manualDrainReason, workerSurface: ctx.workerSurface.status, newTokens: inline.tokens,
estimateKind: inline.estimateKind, costUsd,
floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName,
manualCommands: commands, hint: SPEND_HINT,
- }));
- } else {
- const refusal = manualDrainReason === 'no_worker_surface'
- ? 'no persistent worker surface is available'
- : 'automatic backfill submission is disabled by --no-auto-embed';
- console.log(
- `${previewMsg} Exceeds floor $${formatUsdLimit(floorUsd)} in a non-interactive ` +
- `session — importing now without embeddings because ${refusal}. Manual drain required: ` +
- `${commands.map((command) => `\`${command}\``).join(', ')}. ` +
- `Pass --yes to embed inline.\n${SPEND_HINT}`,
- );
+ } };
}
+ const refusal = manualDrainReason === 'no_worker_surface'
+ ? 'no persistent worker surface is available'
+ : 'automatic backfill submission is disabled by --no-auto-embed';
+ console.log(
+ `${previewMsg} Exceeds floor $${formatUsdLimit(floorUsd)} in a non-interactive ` +
+ `session — importing now without embeddings because ${refusal}. Manual drain required: ` +
+ `${commands.map((command) => `\`${command}\``).join(', ')}. ` +
+ `Pass --yes to embed inline.\n${SPEND_HINT}`,
+ );
return { action: 'proceed', autoDeferEmbeds: true };
}
// Worker-backed AUTO-DEFER. NEVER exit 2 (the wedged-cron fix).
if (jsonOut) {
- console.log(JSON.stringify({ status: 'auto_deferred', mode, gate: 'auto_deferred_embeds', newTokens: inline.tokens, estimateKind: inline.estimateKind, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName, hint: SPEND_HINT }));
- } else {
- console.log(
- `${previewMsg} Exceeds floor $${formatUsdLimit(floorUsd)} in a non-interactive ` +
- `session — importing now, deferring embeds to capped backfill jobs. ` +
- `Drain: run the jobs worker or \`gbrain embed --stale\`. Pass --yes to embed inline.\n${SPEND_HINT}`,
- );
+ return { action: 'proceed', autoDeferEmbeds: true, notice: { status: 'auto_deferred', mode, gate: 'auto_deferred_embeds', newTokens: inline.tokens, estimateKind: inline.estimateKind, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName, hint: SPEND_HINT } };
}
+ console.log(
+ `${previewMsg} Exceeds floor $${formatUsdLimit(floorUsd)} in a non-interactive ` +
+ `session — importing now, deferring embeds to capped backfill jobs. ` +
+ `Drain: run the jobs worker or \`gbrain embed --stale\`. Pass --yes to embed inline.\n${SPEND_HINT}`,
+ );
return { action: 'proceed', autoDeferEmbeds: true };
}
// Below floor → proceed without blocking (kills inline-cron noise).
if (jsonOut) {
- console.log(JSON.stringify({ status: 'below_floor', mode, gate: 'below_floor', newTokens: inline.tokens, estimateKind: inline.estimateKind, staleChars, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName }));
- } else {
- console.log(`${previewMsg} Below cost gate floor ($${formatUsdLimit(floorUsd)}), proceeding.`);
+ return { action: 'proceed', autoDeferEmbeds: false, notice: { status: 'below_floor', mode, gate: 'below_floor', newTokens: inline.tokens, estimateKind: inline.estimateKind, staleChars, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName } };
}
+ console.log(`${previewMsg} Below cost gate floor ($${formatUsdLimit(floorUsd)}), proceeding.`);
return { action: 'proceed', autoDeferEmbeds: false };
}
diff --git a/src/core/sync-embed-backfill.ts b/src/core/sync-embed-backfill.ts
index 97df4ae83e..e761db6a88 100644
--- a/src/core/sync-embed-backfill.ts
+++ b/src/core/sync-embed-backfill.ts
@@ -43,12 +43,14 @@ export async function resolveSyncAllEmbedPlan(
autoDeferEmbeds: boolean;
effectiveNoEmbed: boolean;
shouldBackfill: boolean;
+ /** #4684: the gate's --json status object, for the `cost_gate` envelope field. */
+ costGate?: Record<string, unknown>;
}> {
const workerSurface = embedBackfillWorkerSurface(engine);
const deferEligible =
opts.v2Enabled && !opts.serialFlag && workerSurface.status === 'worker_backed';
const fanOutEligible = deferEligible && sources.length > 1;
- const buildPlan = (stop: boolean, autoDeferEmbeds: boolean) => ({
+ const buildPlan = (stop: boolean, autoDeferEmbeds: boolean, costGate?: Record<string, unknown>) => ({
stop,
workerSurface,
deferEligible,
@@ -56,8 +58,8 @@ export async function resolveSyncAllEmbedPlan(
autoDeferEmbeds,
effectiveNoEmbed: deferEligible || opts.noEmbed || autoDeferEmbeds,
shouldBackfill: deferEligible || autoDeferEmbeds || (opts.v2Enabled && opts.noEmbed),
+ costGate,
});
- let autoDeferEmbeds = false;
if (!opts.noEmbed) {
const gate = await runInlineCostGate(engine, {
sources: sources.map((source) => ({ ...source, sourceId: source.id })),
@@ -74,9 +76,9 @@ export async function resolveSyncAllEmbedPlan(
if (gate.action === 'stop') {
return buildPlan(true, false);
}
- autoDeferEmbeds = gate.autoDeferEmbeds;
+ return buildPlan(false, gate.autoDeferEmbeds, gate.notice);
}
- return buildPlan(false, autoDeferEmbeds);
+ return buildPlan(false, false);
}
export async function resolveSingleSyncEmbedPlan(
@@ -87,6 +89,7 @@ export async function resolveSingleSyncEmbedPlan(
stop: boolean;
workerSurface: EmbedBackfillWorkerSurface;
autoDeferEmbeds: boolean;
+ costGate?: Record<string, unknown>;
}> {
const workerSurface = embedBackfillWorkerSurface(engine);
const gate = await runInlineCostGate(engine, {
@@ -103,7 +106,23 @@ export async function resolveSingleSyncEmbedPlan(
});
return gate.action === 'stop'
? { stop: true, workerSurface, autoDeferEmbeds: false }
- : { stop: false, workerSurface, autoDeferEmbeds: gate.autoDeferEmbeds };
+ : { stop: false, workerSurface, autoDeferEmbeds: gate.autoDeferEmbeds, costGate: gate.notice };
+}
+
+/**
+ * Did this sync create anything an embed-backfill could embed? A run whose
+ * only effect is the un-syncable sweep (#4786 soft-deletes) or a plain
+ * deletion reports `synced` but wrote no chunks; minting a backfill for it
+ * starts the per-source cooldown / active-job block in
+ * `submitEmbedBackfill`, so a real import inside that window is skipped and
+ * its NULL-embedded chunks strand until the next tick. Every automatic
+ * submit site (sync --all, single-source autodefer, the jobs sync handler)
+ * gates on this, not on status alone.
+ */
+export function syncProducedEmbeddableContent(
+ result: { chunksCreated: number; added: number; modified: number; renamed: number },
+): boolean {
+ return result.chunksCreated > 0 || result.added + result.modified + result.renamed > 0;
}
export type SyncEmbedBackfillOutcome =
@@ -187,6 +206,7 @@ export function buildSingleSyncJsonEnvelope(
embedded: number;
},
embedBackfill?: SyncEmbedBackfillOutcome,
+ costGate?: Record<string, unknown>,
): Record<string, unknown> {
return {
schema_version: 1,
@@ -198,6 +218,8 @@ export function buildSingleSyncJsonEnvelope(
deleted: result.deleted,
chunks_created: result.chunksCreated,
embedded: result.embedded,
+ // #4684: the cost-gate status object rides inside the ONE envelope.
+ ...(costGate ? { cost_gate: costGate } : {}),
...(embedBackfill ? { embed_backfill: embedBackfill } : {}),
};
}
diff --git a/src/core/sync-policy.ts b/src/core/sync-policy.ts
new file mode 100644
index 0000000000..759ea79f69
--- /dev/null
+++ b/src/core/sync-policy.ts
@@ -0,0 +1,24 @@
+/**
+ * The single predicate for `config.syncEnabled === false` (#4399).
+ *
+ * The flag means "excluded from AUTOMATIC/bulk sync": the `sync --all` fan-out
+ * filter (sync.ts), autopilot's freshness dispatcher (autopilot.ts), the
+ * full-cycle fan-out (autopilot-fanout.ts) and the `sync_enabled` column of
+ * the sources status report (sync-status-report.ts, fed RAW `SELECT config`
+ * rows) all read it here so they cannot drift apart. It deliberately does
+ * NOT gate performSync() itself — an
+ * explicit `gbrain sync --source <id>` naming a disabled source still runs.
+ * (sync-cost-gate.ts keeps its own inline check: it also feeds the explicit
+ * single-source cost preview.)
+ */
+
+import { parseSourceConfig } from './sources-load.ts';
+
+/**
+ * True iff `config` explicitly sets `syncEnabled: false`. parseSourceConfig
+ * unwraps PGLite's JSON-string scalar shape (same pattern as
+ * sourceConfigHasRemoteUrl); absent/undefined is NOT disabled.
+ */
+export function isSyncDisabledConfig(config: unknown): boolean {
+ return parseSourceConfig(config).syncEnabled === false;
+}
diff --git a/src/core/sync-status-report.ts b/src/core/sync-status-report.ts
index 37fb46503e..015f3fea85 100644
--- a/src/core/sync-status-report.ts
+++ b/src/core/sync-status-report.ts
@@ -6,6 +6,7 @@
import type { BrainEngine } from './engine.ts';
import { loadConfig } from './config.ts';
import { unacknowledgedSyncFailures } from './sync.ts';
+import { isSyncDisabledConfig } from './sync-policy.ts';
// lagFromContentMs is the remote/column comparator (buildSyncStatusReport
// backs the get_status_snapshot MCP op — must NOT shell out to git).
import { lagFromContentMs } from './source-health.ts';
@@ -79,7 +80,10 @@ export interface SyncStatusReport {
export async function buildSyncStatusReport(
engine: BrainEngine,
- sources: Array<{ id: string; name: string; local_path: string | null; config: Record<string, unknown> }>,
+ // `config` is the RAW sources.config value (callers pass `SELECT config`
+ // rows straight through; PGLite returns jsonb as a JSON string) — read it
+ // only through the #4399 predicate, never a raw cast.
+ sources: Array<{ id: string; name: string; local_path: string | null; config: unknown }>,
): Promise<SyncStatusReport> {
// Resolve the active embedding column via the registry. Brains pointed
// at Voyage / multimodal / any non-default column get accurate counts
@@ -206,7 +210,6 @@ export async function buildSyncStatusReport(
const now = Date.now();
const out: SyncStatusReportSource[] = sources.map((src) => {
- const cfgEntry = (src.config || {}) as { syncEnabled?: boolean };
const row = sourceMap.get(src.id) || { id: src.id, last_commit: null, last_sync_at: null, newest_content_at: null };
const counts = countMap.get(src.id) || { pages: 0, chunks_total: 0, chunks_unembedded: 0 };
const lastSyncMs = row.last_sync_at
@@ -244,7 +247,7 @@ export async function buildSyncStatusReport(
source_id: src.id,
name: src.name,
local_path: src.local_path,
- sync_enabled: cfgEntry.syncEnabled !== false,
+ sync_enabled: !isSyncDisabledConfig(src.config),
last_sync_at: lastSyncIso,
hours_since_last_sync: hoursSinceLastSync,
staleness_hours: stalenessHours === null ? null : Math.round(stalenessHours * 10) / 10,
diff --git a/src/core/sync.ts b/src/core/sync.ts
index 07b84b0116..1f8bd4e448 100644
--- a/src/core/sync.ts
+++ b/src/core/sync.ts
@@ -11,7 +11,7 @@
* pathToSlug() → convert file paths to page slugs
*/
-import { SLUG_WORD_CHARS } from './cjk.ts';
+import { SLUG_WORD_CHARS, SLUG_VARIATION_SELECTORS_RE } from './cjk.ts';
// v0.37.7.0 #1169 submodule-detection helpers. Bottom-of-file already
// aliases existsSync as `_existsSync` for other purposes; the top-of-file
// import keeps the pruneDir helper's deps near its callsite.
@@ -637,6 +637,10 @@ export function slugifySegment(segment: string): string {
// are already decomposed and their points strip too.
.replace(/[\u0591-\u05c7]/g, '') // Strip Hebrew niqqud + cantillation
.normalize('NFC') // Recompose Hangul Jamo back to Syllables (v0.32.7)
+ // Strip variation selectors (emoji VS16, ideographic IVS): Mn invisibles
+ // that survive \p{M}, so `🗂️ entities` forked a `<U+FE0F>-entities` twin of
+ // the clean-slug page. Shared with normalizeBasename via cjk.ts (#4985).
+ .replace(SLUG_VARIATION_SELECTORS_RE, '')
.toLowerCase()
.replace(SLUGIFY_KEEP_RE, '') // Keep alnum, dots, spaces, _-, and CJK (v0.32.7)
.replace(/[\s]+/g, '-') // Spaces → hyphens
diff --git a/src/core/transcripts/claude-code-jsonl.ts b/src/core/transcripts/claude-code-jsonl.ts
index afeaa7997c..7db5880cf9 100644
--- a/src/core/transcripts/claude-code-jsonl.ts
+++ b/src/core/transcripts/claude-code-jsonl.ts
@@ -163,6 +163,14 @@ function deriveTranslatedProjectsRoot(translated: string, mountRoot: string): st
export interface ParsedTranscript {
/** Conversation turns, oldest → newest (WindowTurn — the IPC window shape). */
turns: WindowTurn[];
+ /**
+ * Turn indexes whose user-role content contains genuine text. Claude records
+ * tool results as user-role messages too, so role alone cannot identify a
+ * human prompt. Kept parallel to `turns` instead of removing placeholders:
+ * archival/corpus consumers still see that tools ran, while prompt-only
+ * consumers can select structurally without matching rendered text.
+ */
+ genuineUserTurnIndexes: number[];
/**
* Context blocks a gbrain hook previously INJECTED this session, oldest →
* newest. Claude Code records a UserPromptSubmit hook's additionalContext
@@ -259,6 +267,7 @@ export function parseTranscript(
const lines = raw.split('\n');
const turns: WindowTurn[] = [];
+ const genuineUserTurnIndexes: number[] = [];
const injectedContextBlocks: string[] = [];
const boundaryTurnIndexes: number[] = [];
const toolCalls: ToolCallWithId[] = [];
@@ -298,8 +307,11 @@ export function parseTranscript(
for (const c of entryToToolCalls(entry)) { toolCalls.push(c); toolCallTurnIndexes.push(turns.length); }
for (const r of entryToToolResults(entry)) toolResults.set(r.tool_use_id, r.ok);
}
- const turn = entryToTurn(entry);
- if (turn) turns.push(turn);
+ const parsedTurn = entryToTurn(entry);
+ if (parsedTurn) {
+ if (parsedTurn.genuineUser) genuineUserTurnIndexes.push(turns.length);
+ turns.push(parsedTurn.turn);
+ }
}
// Join results to calls by tool_use_id, then strip the internal id field so
// the public ToolCallRecord shape (and the receipt JSON derived from it)
@@ -308,7 +320,7 @@ export function parseTranscript(
const ok = c.id !== undefined ? toolResults.get(c.id) : undefined;
return { name: c.name, input: capToolCallInput(c.input), ...(ok !== undefined ? { result: { ok } } : {}) };
});
- return { turns, injectedContextBlocks, bytesRead, parsedLines, skippedLines, compactBoundaries, boundaryTurnIndexes, toolCalls: joinedToolCalls, toolCallTurnIndexes };
+ return { turns, genuineUserTurnIndexes, injectedContextBlocks, bytesRead, parsedLines, skippedLines, compactBoundaries, boundaryTurnIndexes, toolCalls: joinedToolCalls, toolCallTurnIndexes };
}
/** {type:'system', subtype:'compact_boundary'} — Claude Code's on-disk compaction marker (v0.45.7). */
@@ -354,8 +366,19 @@ function entryToInjectedBlock(entry: unknown): string | null {
return GBRAIN_BLOCK_MARKERS.some((m) => text.includes(m)) ? text : null;
}
-/** One transcript line → a WindowTurn, or null for non-turn/skipped shapes. */
-function entryToTurn(entry: unknown): WindowTurn | null {
+/**
+ * Claude Code writes slash-command bookkeeping (`/clear`, its stdout) as
+ * `user` records whose content is ONLY harness tags. They stay in the window
+ * (archival) but are not something the human said, so they never count as a
+ * genuine user prompt for the writeback lane.
+ */
+const HARNESS_TAG_RE = /<(local-command-stdout|local-command-stderr|command-name|command-message|command-args)>[\s\S]*?<\/\1>/g;
+function isGenuineUserText(text: string): boolean {
+ return text.replace(HARNESS_TAG_RE, '').trim().length > 0;
+}
+
+/** One transcript line → a turn plus its structural human-prompt origin. */
+function entryToTurn(entry: unknown): { turn: WindowTurn; genuineUser: boolean } | null {
if (typeof entry !== 'object' || entry === null) return null;
const e = entry as Record<string, unknown>;
if (e.isSidechain === true) return null; // subagent traffic — skipped
@@ -369,8 +392,10 @@ function entryToTurn(entry: unknown): WindowTurn | null {
const content = m.content;
let text = '';
+ let hasGenuineText = false;
if (typeof content === 'string') {
text = content;
+ hasGenuineText = isGenuineUserText(content);
} else if (Array.isArray(content)) {
const parts: string[] = [];
for (const block of content) {
@@ -378,7 +403,10 @@ function entryToTurn(entry: unknown): WindowTurn | null {
const b = block as Record<string, unknown>;
switch (b.type) {
case 'text':
- if (typeof b.text === 'string' && b.text.trim()) parts.push(b.text);
+ if (typeof b.text === 'string' && b.text.trim()) {
+ parts.push(b.text);
+ if (isGenuineUserText(b.text)) hasGenuineText = true;
+ }
break;
case 'tool_use':
parts.push(`[tool: ${typeof b.name === 'string' && b.name ? b.name : 'unknown'}]`);
@@ -400,7 +428,7 @@ function entryToTurn(entry: unknown): WindowTurn | null {
}
text = text.trim();
if (!text) return null;
- return { role, text };
+ return { turn: { role, text }, genuineUser: role === 'user' && hasGenuineText };
}
/**
@@ -530,6 +558,14 @@ export interface ParsedClaudeSession {
turns: TimedTurn[];
bytesRead: number;
skippedLines: number;
+ /**
+ * Records that CLAIM to be importable turns: `type` user/assistant and not
+ * `isSidechain`. Zero of them means the file never had anything to import
+ * (a title/metadata-only stub, or all-subagent traffic) — understood, not
+ * host-format drift. Above zero with `turns` still empty is the real drift
+ * signal: turn records exist but no longer yield text.
+ */
+ turnShapedLines: number;
}
/**
@@ -552,6 +588,7 @@ export function parseClaudeSessionFile(
let sessionId = '';
let cwd: string | undefined;
let skippedLines = 0;
+ let turnShapedLines = 0;
for (const line of raw.split('\n')) {
const t = line.trim();
if (!t) continue;
@@ -565,10 +602,13 @@ export function parseClaudeSessionFile(
const e = entry as Record<string, unknown>;
if (!sessionId && typeof e.sessionId === 'string' && e.sessionId) sessionId = e.sessionId;
if (!cwd && typeof e.cwd === 'string' && e.cwd) cwd = e.cwd;
+ if (e.isSidechain !== true && (e.type === 'user' || e.type === 'assistant')) {
+ turnShapedLines++;
+ }
const turn = entryToTurn(entry);
if (!turn) continue;
const timestamp = typeof e.timestamp === 'string' ? e.timestamp : '';
- turns.push({ role: turn.role, text: turn.text, timestamp });
+ turns.push({ role: turn.turn.role, text: turn.turn.text, timestamp });
}
return {
sessionId,
@@ -577,6 +617,7 @@ export function parseClaudeSessionFile(
turns,
bytesRead: size,
skippedLines,
+ turnShapedLines,
};
}
@@ -591,4 +632,3 @@ export function toCorpusText(turns: WindowTurn[]): string {
if (!turns.length) return '';
return turns.map((t) => `[${t.role}]\n${t.text}`).join('\n\n') + '\n';
}
-
diff --git a/src/core/transcripts/claude-code.ts b/src/core/transcripts/claude-code.ts
index d3a0921137..8a13a5eb24 100644
--- a/src/core/transcripts/claude-code.ts
+++ b/src/core/transcripts/claude-code.ts
@@ -43,13 +43,42 @@ const CLAUDE_CONTROL_TYPES = new Set([
* and carries the PARENT session's id — it is not a session and can never
* import. Discovery and explicit-path expansion both skip these so they stop
* reading as a permanent not-yet-imported backlog + host-format drift (#4796).
- * STRICT shape (parent dir literally `subagents` AND basename `agent-*.jsonl`)
- * so a user project whose slug merely contains "subagents" is never hidden.
+ * STRICT shape (a path segment literally `subagents` AND basename
+ * `agent-*.jsonl`) so a user project whose slug merely contains "subagents" is
+ * never hidden: Claude Code encodes a whole project path as ONE slug segment
+ * (`-Users-me-subagents-thing`), which never equals `subagents` exactly.
+ *
+ * The segment is matched at ANY depth above the file, not just the immediate
+ * parent. Workflow runs nest a second level —
+ * `<session>/subagents/workflows/<wf-id>/agent-<id>.jsonl` — and an
+ * immediate-parent check missed every one of them, so they stayed a permanent
+ * gap-table phantom and re-fired DRIFT WARNING on every ingest: the exact
+ * failure this function exists to prevent.
*/
export function isClaudeCodeSubagentFile(path: string): boolean {
const segs = path.split(/[/\\]/);
const base = segs[segs.length - 1] ?? '';
- return segs[segs.length - 2] === 'subagents' && /^agent-[^/\\]+\.jsonl$/.test(base);
+ if (!/^agent-[^/\\]+\.jsonl$/.test(base)) return false;
+ return segs.slice(0, -1).includes('subagents');
+}
+
+/**
+ * True for a file inside a Claude Code WORKFLOW run directory:
+ * `<session>/subagents/workflows/<wf-id>/...`. The tree holds one
+ * `agent-<id>.jsonl` per fanned-out agent plus a `journal.jsonl` run log —
+ * bookkeeping for a workflow, never a top-level session. The journal is not
+ * a transcript in ANY adapter's format, so leaving it discoverable made every
+ * ingest report `unknown format` and, because an errored file also clears
+ * `cleanScan`, held the `--since last` watermark frozen indefinitely.
+ *
+ * Deliberately narrower than "everything under `subagents/`": a UUID-named
+ * file directly under `subagents/` IS a real session and must stay
+ * discoverable (pinned by transcripts-self-exclusion.test.ts).
+ */
+export function isClaudeCodeWorkflowArtifactFile(path: string): boolean {
+ const segs = path.split(/[/\\]/);
+ const i = segs.lastIndexOf('subagents');
+ return i !== -1 && segs[i + 1] === 'workflows' && segs.length > i + 2;
}
/** Keys that mark a Claude Code project transcript. */
@@ -164,13 +193,27 @@ export const claudeCodeAdapter: TranscriptAdapter = {
})),
};
}
+ // A file with NO turn-shaped records never had anything to import: a
+ // title/metadata-only stub (`last-prompt` + `custom-title` and nothing
+ // else) or all-`isSidechain` subagent traffic. That is understood, not
+ // host-format drift, so it must not freeze the shared watermark — the
+ // same distinction grok draws with expectedEmpty. Turn records that stop
+ // yielding text (`turnShapedLines > 0` with zero turns) still drift, and
+ // so does any file with unparseable lines.
+ const expectedEmpty =
+ sessions === 0 && r.skippedLines === 0 && r.turnShapedLines === 0;
return {
bytesRead: r.bytesRead,
skippedLines: r.skippedLines,
truncated: false,
sessions,
+ expectedEmpty: expectedEmpty || undefined,
zeroSessionsReason:
- sessions === 0 ? 'no user or assistant turns in file' : undefined,
+ sessions === 0
+ ? expectedEmpty
+ ? 'no turn records in file (title/metadata-only or all-subagent)'
+ : 'no user or assistant turns in file'
+ : undefined,
};
},
};
diff --git a/src/core/transcripts/codex-hook-lane.ts b/src/core/transcripts/codex-hook-lane.ts
index 12af423c20..00ae94d0fa 100644
--- a/src/core/transcripts/codex-hook-lane.ts
+++ b/src/core/transcripts/codex-hook-lane.ts
@@ -142,6 +142,7 @@ export function parseCodexHookTranscript(
}
const turns: WindowTurn[] = [];
+ const genuineUserTurnIndexes: number[] = [];
const toolCalls: ToolCallRecord[] = [];
const toolCallTurnIndexes: number[] = [];
const boundaryTurnIndexes: number[] = [];
@@ -164,10 +165,15 @@ export function parseCodexHookTranscript(
const mapped = mapCodexLine(entry);
switch (mapped.kind) {
case 'session':
- if (mapped.sessionId) sessionId = mapped.sessionId;
- if (mapped.cwd) cwd = mapped.cwd;
+ // #4981: first header wins (a forked rollout inherits its parent's header
+ // later in the file); identity is payload.id, the id in the rollout filename.
+ if (!sessionId && mapped.sessionId) sessionId = mapped.sessionId;
+ if (!cwd && mapped.cwd) cwd = mapped.cwd;
break;
case 'user':
+ genuineUserTurnIndexes.push(turns.length);
+ turns.push({ role: mapped.message.role, text: mapped.message.text });
+ break;
case 'assistant':
turns.push({ role: mapped.message.role, text: mapped.message.text });
break;
@@ -193,6 +199,7 @@ export function parseCodexHookTranscript(
return {
turns,
+ genuineUserTurnIndexes,
injectedContextBlocks: [], // codex's injected context is dropped at mapCodexLine, not surfaced
bytesRead,
parsedLines,
diff --git a/src/core/transcripts/codex.ts b/src/core/transcripts/codex.ts
index d94b18b6bb..8a79ad4873 100644
--- a/src/core/transcripts/codex.ts
+++ b/src/core/transcripts/codex.ts
@@ -43,8 +43,9 @@ export const CODEX_SPEC_TARGET: HostSpecTarget = {
],
note:
'One JSON object per line: {timestamp: ISO, type, payload}. type ' +
- "'session_meta' header carries payload.{session_id, cwd, timestamp, " +
- "cli_version}. User turns: type 'event_msg' with payload.type " +
+ "'session_meta' header carries payload.{id, session_id, cwd, timestamp, " +
+ "cli_version}; identity = payload.id (per-thread; session_id is the root " +
+ "session shared by forked/subagent threads), first header wins. User turns: type 'event_msg' with payload.type " +
"'user_message' (payload.message = typed text). Assistant turns: type " +
"'response_item' with payload.{type:'message', role:'assistant', " +
"content:[{type:'output_text', text}]}. response_item rows with role " +
@@ -105,7 +106,14 @@ export function mapCodexLine(entry: unknown): CodexLineResult {
if (e.type === 'session_meta') {
return {
kind: 'session',
- sessionId: typeof payload.session_id === 'string' ? payload.session_id : undefined,
+ // #4981: payload.id is the per-thread identity (present in every real rollout
+ // and embedded in its filename); payload.session_id is the ROOT session shared
+ // by every forked/subagent thread. Keying on session_id collapsed children onto
+ // the parent's page. session_id stays as the legacy/fixture fallback.
+ sessionId:
+ (typeof payload.id === 'string' && payload.id) ||
+ (typeof payload.session_id === 'string' && payload.session_id) ||
+ undefined,
cwd: typeof payload.cwd === 'string' ? payload.cwd : undefined,
startedAt: typeof payload.timestamp === 'string' ? payload.timestamp : lineTs || undefined,
cliVersion: typeof payload.cli_version === 'string' ? payload.cli_version : undefined,
@@ -212,6 +220,9 @@ export const codexAdapter: TranscriptAdapter = {
}
const mapped = mapCodexLine(entry);
if (mapped.kind === 'session') {
+ // #4981: first header wins — a child rollout carries its inherited parent
+ // session_meta later in the file; it must not rewrite identity/cwd/start.
+ if (rawMeta) continue;
if (mapped.sessionId) sessionId = mapped.sessionId;
if (mapped.cwd) cwd = mapped.cwd;
if (mapped.startedAt) startedAt = mapped.startedAt;
diff --git a/src/core/transcripts/discover.ts b/src/core/transcripts/discover.ts
index 76046bac12..97c891561d 100644
--- a/src/core/transcripts/discover.ts
+++ b/src/core/transcripts/discover.ts
@@ -23,7 +23,7 @@ import type { TranscriptFormat } from './types.ts';
import { harnessRoots, type HarnessRoot } from './detect.ts';
import { isOpenclawCheckpointFile } from './openclaw.ts';
import { isGrokChatHistoryFile } from './grok.ts';
-import { isClaudeCodeSubagentFile } from './claude-code.ts';
+import { isClaudeCodeSubagentFile, isClaudeCodeWorkflowArtifactFile } from './claude-code.ts';
import { isClaudeCliSelfTranscriptPath } from '../ai/providers/claude-cli-scratch.ts';
export interface DiscoveredFile {
@@ -98,6 +98,10 @@ export function discoverTranscriptFiles(roots?: HarnessRoot[], opts: DiscoverOpt
// session id, so they can never import. Left in, each one is a
// permanent gap-table phantom + a false DRIFT WARNING every ingest.
if (format === 'claude-code' && isClaudeCodeSubagentFile(p)) continue;
+ // Workflow run bookkeeping (agent logs + a journal.jsonl that matches no
+ // adapter format). Discoverable, it errored every ingest and froze the
+ // shared --since watermark via cleanScan.
+ if (format === 'claude-code' && isClaudeCodeWorkflowArtifactFile(p)) continue;
// #4472: skip gbrain's own claude-cli subprocess sessions (see
// DiscoverOpts.includeSelf) — the scratch-cwd fingerprint survives
// Claude Code's project-dir slugification.
diff --git a/src/core/types.ts b/src/core/types.ts
index 509a5830e7..f13b58ffae 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -166,6 +166,8 @@ export interface Page {
ingested_via?: string | null;
/** Server-stamped first-write audit timestamp; CV12 COALESCE-preserved across edits. */
ingested_at?: Date | null;
+ /** Repo-relative import path (see PageInput.source_path); projected by getPage so the import skip path can compare before writing. */
+ source_path?: string | null;
/**
* v0.40.3.0 (renumbered from v0.40.3.0 v81 to v90 on master merge):
* which contextual retrieval tier the page was last embedded under. One
@@ -1879,6 +1881,11 @@ export interface EvalCaptureFailure {
* otherwise a transitional relaxed-carried row would
* shadow the recovered pipeline for the full TTL
* under the same knobs hash (2026-09 red-team).
+ * safe_index_pending — a remote/untrusted read returned nothing while its
+ * scope still holds markdown pages below the safe-chunk
+ * index version (withheld from remote chunk retrieval
+ * until `gbrain reindex --markdown` seals them); stamped
+ * by the search/query ops' retrieval meta (#5004)
*/
export const DEGRADED_STAGES = [
'embed_unavailable',
@@ -1894,6 +1901,7 @@ export const DEGRADED_STAGES = [
'reranker_skipped',
'rerank_passthrough',
'keyword_relaxed_carried',
+ 'safe_index_pending',
] as const;
export type DegradedStage = (typeof DEGRADED_STAGES)[number];
diff --git a/src/core/utils.ts b/src/core/utils.ts
index b9ae15538c..66934eb675 100644
--- a/src/core/utils.ts
+++ b/src/core/utils.ts
@@ -240,6 +240,9 @@ export function rowToPage(row: Record<string, unknown>): Page {
...(ingestedVia !== undefined && { ingested_via: ingestedVia }),
...(ingestedAt !== undefined && { ingested_at: ingestedAt }),
...(contextualRetrievalMode !== undefined && { contextual_retrieval_mode: contextualRetrievalMode }),
+ // Three-state like the provenance columns: getPage projects it so the import
+ // skip path can compare before issuing the #4588 source_path refresh.
+ ...(row.source_path !== undefined && { source_path: row.source_path as string | null }),
// v0.31.12: propagate source_id so downstream callers (embed, reconcile-links)
// can thread it through getChunks / upsertChunks without defaulting to 'default'.
// v0.32.8: Page.source_id is required. Every SELECT feeding rowToPage now
diff --git a/src/core/write-through.ts b/src/core/write-through.ts
index 7eef1adc4b..fe931b2d98 100644
--- a/src/core/write-through.ts
+++ b/src/core/write-through.ts
@@ -88,6 +88,8 @@ export interface WriteThroughResult {
* writing would silently clobber the OTHER slug's file (#2831) — refused.
*/
skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision';
+ /** Caller-visible advisory when a permitted DB-only outcome is still risky. */
+ warning?: string;
/** Set when the render/write/rename itself threw (EACCES, ENOTDIR, disk full). */
error?: string;
}
@@ -99,6 +101,16 @@ export interface WritePageThroughOpts {
logger?: WriteThroughLogger;
}
+export function withNoRepoWriteThroughWarning<T extends { written: boolean; skipped?: string; warning?: string }>(result: T, sourceId: string): T {
+ if (result.written || result.skipped !== 'no_repo_configured') return result;
+ return {
+ ...result,
+ warning:
+ `put_page wrote only to the database for source '${sourceId}': no repo/local_path is configured, so no durable markdown file was created. ` +
+ 'Bind this MCP server/token to a git-backed source or configure source local_path/sync.repo_path before relying on the write.',
+ } as T;
+}
+
/**
* Vet a `pages.source_path` before it is trusted as a write target.
*
@@ -494,6 +506,13 @@ export interface DeleteThroughResult {
removed: boolean;
/** The path that was removed (or would have been). */
path?: string;
+ /**
+ * True when the removal was also committed (path-limited) because the repo
+ * is durability-hardened — the delete-side twin of
+ * `WriteThroughResult.committed`. Absent on unhardened repos and when the
+ * best-effort commit did not land (the unlink still stands).
+ */
+ committed?: boolean;
/**
* Non-error reasons nothing was removed. Shares the target-resolution skip
* vocabulary (kept in lockstep via the Extract), plus:
@@ -544,7 +563,7 @@ export async function deletePageThrough(
}
const target = opts.target ?? await resolvePageWriteTarget(engine, slug, sourceId);
if (!target.ok) return { removed: false, skipped: target.skipped };
- const { filePath } = target;
+ const { filePath, writeRoot } = target;
if (!hasSourceFilesystemLock(target.writeRoot)) {
return await withSourceFilesystemLock(engine, target.writeRoot, () => deletePageThrough(engine, slug, opts));
}
@@ -555,7 +574,20 @@ export async function deletePageThrough(
assertSourceFilesystemActive();
unlinkSync(filePath);
- return { removed: true, path: filePath };
+ // Mirror writePageThrough (#2426): on a durability-hardened repo, commit
+ // the removal (path-limited) so the post-commit hook pushes it. Pre-fix
+ // the deletion sat in the working tree as an uncommitted ` D` — invisible
+ // to commit-driven sync (the autopilot's own sync then warned "N
+ // uncommitted file(s) invisible to commit-driven sync") until a human
+ // committed it by hand. Best-effort, like the write side: a commit failure
+ // never fails the delete (the DB row + the unlink are the durable state).
+ let committed = false;
+ try {
+ if (isDurabilityHardened(writeRoot)) {
+ committed = commitWriteThroughFile(writeRoot, filePath, slug, 'delete write-through');
+ }
+ } catch { /* best-effort */ }
+ return { removed: true, path: filePath, ...(committed ? { committed } : {}) };
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
opts.logger?.warn(`[write-through] delete failed for ${slug}: ${msg}`);
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index a823214a90..a693ecd295 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.50.0.0 -->
+<!-- gbrain-template-stamp: 0.50.1.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/ai/gateway-chat.test.ts b/test/ai/gateway-chat.test.ts
index 8643b7e99b..fcdb0390de 100644
--- a/test/ai/gateway-chat.test.ts
+++ b/test/ai/gateway-chat.test.ts
@@ -64,7 +64,11 @@ describe('chat touchpoint — recipe registry', () => {
// it is a property of the whole provider. Anything else must declare no
// caching.
const PREDICATE = new Set(['openai', 'openrouter', 'google']);
- const ALWAYS_CACHES = new Set(['anthropic', 'deepseek', 'llama-server']);
+ // claude-cli caches for the whole provider, so it is a boolean, not a
+ // predicate: Claude Code caches automatically on every model it routes,
+ // `--print` runs included. See the recipe for the measurement and
+ // test/ai/recipe-claude-cli-prompt-cache.test.ts for the behavior.
+ const ALWAYS_CACHES = new Set(['anthropic', 'deepseek', 'llama-server', 'claude-cli']);
for (const r of listRecipes()) {
if (!r.touchpoints.chat) continue;
const flag = r.touchpoints.chat.supports_prompt_cache;
diff --git a/test/ai/gateway-thinking-headroom.test.ts b/test/ai/gateway-thinking-headroom.test.ts
index ce8a9e6f4c..ba4ffbb10c 100644
--- a/test/ai/gateway-thinking-headroom.test.ts
+++ b/test/ai/gateway-thinking-headroom.test.ts
@@ -24,6 +24,13 @@ describe('defaultMaxOutputTokens: recipe-declared thinking headroom (#4172)', ()
expect(defaultMaxOutputTokens('deepseek:deepseek-v4-pro')).toBe(THINKING_MODEL_MAX_OUTPUT_TOKENS);
});
+ it('grants headroom to GLM-4.5+/5.x on every recipe that hosts it (#4727)', () => {
+ expect(defaultMaxOutputTokens('zhipu:glm-5.3-flash')).toBe(THINKING_MODEL_MAX_OUTPUT_TOKENS);
+ expect(defaultMaxOutputTokens('ollama:glm-5.3-flash:cloud')).toBe(THINKING_MODEL_MAX_OUTPUT_TOKENS);
+ expect(defaultMaxOutputTokens('openrouter:z-ai/glm-4.6')).toBe(THINKING_MODEL_MAX_OUTPUT_TOKENS);
+ expect(defaultMaxOutputTokens('ollama:glm-4:9b')).toBe(DEFAULT_MAX_OUTPUT_TOKENS);
+ });
+
it('still grants headroom to name-matched Claude 5 models (regex path intact)', () => {
expect(isThinkingByDefaultModel('anthropic:claude-sonnet-5')).toBe(true);
expect(isThinkingModel('anthropic:claude-sonnet-5')).toBe(true);
diff --git a/test/ai/recipe-claude-cli-prompt-cache.test.ts b/test/ai/recipe-claude-cli-prompt-cache.test.ts
new file mode 100644
index 0000000000..4227e3cf39
--- /dev/null
+++ b/test/ai/recipe-claude-cli-prompt-cache.test.ts
@@ -0,0 +1,76 @@
+/**
+ * claude-cli declares prompt caching, because the CLI caches.
+ *
+ * The recipe used to declare `supports_prompt_cache: false` on the grounds
+ * that the CLI "does not surface it via the standard cache_control control
+ * plane" — true, but that is the wrong question. The contract on
+ * `ProviderCapabilities.supportsPromptCaching` (src/core/ai/capabilities.ts)
+ * is explicit that the field means "does it cache", by EITHER mechanism, and
+ * that the `degraded:no_caching` advice "is wrong for a provider that caches
+ * without being asked".
+ *
+ * Claude Code caches automatically, `--print` runs included — the mode this
+ * provider dispatches. Those runs sit in its "main conversation" TTL bucket,
+ * which is one hour on a Claude subscription:
+ * https://code.claude.com/docs/en/prompt-caching
+ *
+ * The user-visible symptom was doctor's `subagent_capability` telling every
+ * claude-cli operator their subagent loop "runs hot" and to switch to
+ * `anthropic:` — advice that trades a subscription-billed path for a metered
+ * one to buy caching the operator already had. Same unclearable-warning class
+ * as #4575, which is pinned in test/doctor-subagent-capability.test.ts.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { getRecipe } from '../../src/core/ai/recipes/index.ts';
+import { getProviderCapabilities, classifyCapabilities } from '../../src/core/ai/capabilities.ts';
+import { checkSubagentCapability } from '../../src/commands/doctor.ts';
+
+function fakeEngine(entries: Record<string, string>) {
+ const config = new Map(Object.entries(entries));
+ return {
+ async getConfig(key: string): Promise<string | null> {
+ return config.get(key) ?? null;
+ },
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ } as any;
+}
+
+// Every chat model the recipe lists — the declaration is a flat boolean, so
+// none of them may classify as uncached.
+const CLAUDE_CLI_MODELS = getRecipe('claude-cli')!.touchpoints.chat!.models ?? [];
+
+describe('recipe: claude-cli prompt cache', () => {
+ test('the capability layer reports caching for every listed model', () => {
+ expect(CLAUDE_CLI_MODELS.length).toBeGreaterThan(0);
+ for (const id of CLAUDE_CLI_MODELS) {
+ expect(getProviderCapabilities(`claude-cli:${id}`).supportsPromptCaching).toBe(true);
+ }
+ });
+
+ test('classifyCapabilities does not grade claude-cli as degraded:no_caching', () => {
+ for (const id of CLAUDE_CLI_MODELS) {
+ const verdict = classifyCapabilities(`claude-cli:${id}`);
+ expect(verdict).not.toBe('degraded:no_caching');
+ // The recipe declares tools + subagent loop, so the only remaining
+ // verdict is a clean one. Asserting the exact value (rather than
+ // "not degraded") keeps this from passing on an 'unknown' regression.
+ expect(verdict).toBe('ok');
+ }
+ });
+
+ test('doctor subagent_capability is OK on a claude-cli subagent tier', async () => {
+ const engine = fakeEngine({
+ 'models.tier.subagent': 'claude-cli:claude-sonnet-5',
+ // Short-circuits the unrelated non-Anthropic chat_model branch below the
+ // capability gate, so this test does not read the host's real config.
+ 'agent.use_gateway_loop': 'true',
+ });
+ const check = await checkSubagentCapability(engine);
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('models.tier.subagent');
+ // The retired advice must not come back.
+ expect(check.message).not.toContain('prompt caching');
+ expect(check.message).not.toContain('runs hot');
+ });
+});
diff --git a/test/ai/recipe-ollama-thinking.test.ts b/test/ai/recipe-ollama-thinking.test.ts
index 6edadec5ad..b271083ab3 100644
--- a/test/ai/recipe-ollama-thinking.test.ts
+++ b/test/ai/recipe-ollama-thinking.test.ts
@@ -80,4 +80,19 @@ describe('recipe: ollama thinking-by-default', () => {
])('%s is thinking-by-default', (model) => {
expect(getProviderCapabilities(model).supportsThinking).toBe(true);
});
+
+ // gbrain#4727: GLM-4.5+/5.x reason by default on every host (the zhipu
+ // recipe already declares it); a reporter hit the 4000 cap on GLM-5.3-flash
+ // via Ollama cloud. Older glm-4 tags keep the conservative cap.
+ test.each([
+ 'ollama:glm-5.3-flash',
+ 'ollama:glm-5.3-flash:cloud',
+ 'ollama:glm-4.6',
+ ])('%s (GLM-4.5+/5.x) is thinking-by-default', (model) => {
+ expect(getProviderCapabilities(model).supportsThinking).toBe(true);
+ });
+
+ test('glm-4:9b (pre-4.5) is not thinking-by-default', () => {
+ expect(getProviderCapabilities('ollama:glm-4:9b').supportsThinking).toBe(false);
+ });
});
diff --git a/test/ai/recipe-openrouter.test.ts b/test/ai/recipe-openrouter.test.ts
index 7092338743..aeda279d8d 100644
--- a/test/ai/recipe-openrouter.test.ts
+++ b/test/ai/recipe-openrouter.test.ts
@@ -18,6 +18,7 @@ import {
openrouterSupportsPromptCache,
} from '../../src/core/ai/recipes/openrouter.ts';
import { defaultResolveAuth } from '../../src/core/ai/gateway.ts';
+import { getProviderCapabilities } from '../../src/core/ai/capabilities.ts';
import { assertTouchpoint, embeddingDimsForModel } from '../../src/core/ai/model-resolver.ts';
import { AIConfigError } from '../../src/core/ai/errors.ts';
@@ -400,3 +401,24 @@ describe('recipe: openrouter', () => {
}
});
});
+
+// gbrain#4727: Z.ai's GLM-4.5+/5.x think by default and OpenRouter bills
+// reasoning as completion tokens (same basis as the deepseek/ route, #4758),
+// so the OR recipe grants the same headroom the zhipu recipe does.
+describe('recipe: openrouter thinking-by-default — z-ai GLM (#4727)', () => {
+ test.each([
+ 'openrouter:z-ai/glm-5',
+ 'openrouter:z-ai/glm-4.6',
+ 'openrouter:z-ai/glm-4.5-air',
+ ])('%s is thinking-by-default', (model) => {
+ expect(getProviderCapabilities(model).supportsThinking).toBe(true);
+ });
+
+ test.each([
+ 'openrouter:z-ai/glm-4',
+ 'openrouter:z-ai/glm-4-32b',
+ 'openrouter:openai/gpt-5.2-chat',
+ ])('%s is not thinking-by-default', (model) => {
+ expect(getProviderCapabilities(model).supportsThinking).toBe(false);
+ });
+});
diff --git a/test/ambient-recall.test.ts b/test/ambient-recall.test.ts
index 27e4f3aa2d..14ac01decd 100644
--- a/test/ambient-recall.test.ts
+++ b/test/ambient-recall.test.ts
@@ -19,6 +19,8 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
import { operations } from '../src/core/operations.ts';
import { MEMORY_VERBS_VERSION, VERB_NAMES } from '../src/core/verbs.ts';
+import { estimateTokens } from '../src/core/search/token-budget.ts';
+import { deltaHeaderCost, renderFactLine, renderPageLine, renderThreadLine } from '../src/core/context/turn-context.ts';
import {
getSessionContextState,
upsertSessionContextState,
@@ -256,7 +258,7 @@ describe('delta cursor lifecycle', () => {
await call(putPage, local, { slug: `notes/${s}`, content: `# ${s}\n\ncontent for ${s}` });
}
// tiny budget: deliver a strict subset, has_more = true, cursor lags
- const r1 = await call(del, local, { session_id: 'alo', budget_tokens: 8 });
+ const r1 = await call(del, local, { session_id: 'alo', budget_tokens: 80 });
expect(r1.has_more).toBe(true);
expect(r1.pages.length).toBeGreaterThan(0);
expect(r1.pages.length).toBeLessThan(3);
@@ -276,7 +278,7 @@ describe('delta cursor lifecycle', () => {
for (const s of ['txt-a', 'txt-b', 'txt-c']) {
await call(putPage, local, { slug: `notes/${s}`, content: `# ${s}\n\ncontent` });
}
- const r = await call(del, local, { session_id: 'txt', budget_tokens: 8 });
+ const r = await call(del, local, { session_id: 'txt', budget_tokens: 80 });
const inText = ['txt-a', 'txt-b', 'txt-c'].filter((s) => (r.text as string).includes(s));
expect(inText.length).toBe(r.pages.length); // text lists exactly the delivered pages
});
@@ -298,7 +300,7 @@ describe('delta cursor lifecycle', () => {
});
// Tiny budget: deliver a strict subset of the tie cluster (all 4 share one
// timestamp — the keyset paginates within it by slug).
- const r1 = await call(del, local, { session_id: 'tie', budget_tokens: 8 });
+ const r1 = await call(del, local, { session_id: 'tie', budget_tokens: 80 });
expect(r1.pages.length).toBeGreaterThan(0);
expect(r1.pages.length).toBeLessThan(4);
expect(r1.has_more).toBe(true);
@@ -401,7 +403,9 @@ describe('delta cursor lifecycle', () => {
// One identical timestamp, earlier than every other fixture cluster.
await engine.executeRaw(`UPDATE pages SET updated_at = '2026-08-09T10:00:00Z' WHERE slug LIKE 'notes/sr-%'`);
// NO session_id anywhere: resume rides next_cursor.since/.slug alone.
- // budget 8 ≈ 2 pages per call, so the 4-page cluster needs ≥2 wakes.
+ // budget 80 ≈ 1 page per call (#4761: ~53 tokens of envelope+headers are
+ // reserved, each rendered page line is ~15), so the 4-page cluster needs
+ // several wakes.
const seen: string[] = [];
let since = '2026-08-09T09:59:00Z';
let sinceSlug: string | undefined;
@@ -410,7 +414,7 @@ describe('delta cursor lifecycle', () => {
const r = await call(del, ctxFor({ remote: false }), {
since,
...(sinceSlug !== undefined ? { since_slug: sinceSlug } : {}),
- budget_tokens: 8,
+ budget_tokens: 80,
});
for (const pg of r.pages as Array<{ slug: string }>) {
if (pg.slug.startsWith('notes/sr-')) seen.push(pg.slug);
@@ -722,6 +726,126 @@ describe('budget packing + drop footer', () => {
expect(r.dropped_count).toBeUndefined();
});
+ // #4761: `text` is what harnesses inject — it must fit budget_tokens, so the
+ // packer prices the RENDERED line (+ envelope/header reserve), not raw fields.
+ test('context_pack text never exceeds budget_tokens (#4761)', async () => {
+ const r = await call(contextPack, ctxFor({ remote: false }), { entities: 'acme-example', budget_tokens: 80 });
+ expect((r.facts as unknown[]).length).toBeGreaterThan(0);
+ expect(r.dropped_count).toBeGreaterThan(0);
+ expect(estimateTokens(r.text as string)).toBeLessThanOrEqual(80);
+ expect(r.budget_used).toBeLessThanOrEqual(80);
+ });
+
+ test('delta text never exceeds budget_tokens (#4761)', async () => {
+ const putPage = operations.find((o) => o.name === 'put_page')!;
+ const local = ctxFor({ remote: false });
+ await call(del, local, { session_id: 'fit' });
+ for (const s of ['fit-a', 'fit-b', 'fit-c', 'fit-d', 'fit-e', 'fit-f']) {
+ await call(putPage, local, { slug: `notes/${s}`, content: `# ${s}\n\ncontent` });
+ }
+ const r = await call(del, local, { session_id: 'fit', budget_tokens: 90 });
+ expect((r.pages as unknown[]).length).toBeGreaterThan(0);
+ expect(r.has_more).toBe(true);
+ expect(estimateTokens(r.text as string)).toBeLessThanOrEqual(90);
+ expect(r.budget_used).toBeLessThanOrEqual(90);
+ });
+
+ // Threads are the commitments a heartbeat must never miss: delta reserves
+ // every thread line ahead of pages/facts and never budget-drops one. Only
+ // pages and facts count toward dropped_count; budget_used reports the real
+ // rendered size (it exceeds the budget only when header + threads alone do).
+ test('delta never budget-drops threads — dropped_count counts only pages/facts', async () => {
+ const putPage = operations.find((o) => o.name === 'put_page')!;
+ const local = ctxFor({ remote: false });
+ await call(putPage, local, { slug: 'people/alice-example', content: '# Alice Example\n\nbody' });
+ for (const tag of ['nt-a', 'nt-b', 'nt-c']) {
+ await call(remember, local, {
+ fact: `${tag} alice-example will send the signed term sheet by Friday`,
+ kind: 'commitment',
+ entity: 'people/alice-example',
+ provenance: 'test',
+ visibility: 'world',
+ });
+ }
+ __resetHotMemoryCacheForTests();
+ const since = '1970-01-01T00:00:00Z';
+ const full = await call(del, local, { since, entities: 'people/alice-example' });
+ const threadText = (r: VerbResult) => (r.threads as Array<{ text: string }>).map((t) => t.text).sort();
+ expect((full.threads as unknown[]).length).toBe(3);
+ expect((full.pages as unknown[]).length + (full.facts as unknown[]).length).toBeGreaterThan(0);
+ // A budget below even the envelope: every page and fact drops, every thread stays.
+ const r = await call(del, local, { since, entities: 'people/alice-example', budget_tokens: 1 });
+ expect(threadText(r)).toEqual(threadText(full));
+ expect(r.pages).toEqual([]);
+ expect(r.facts).toEqual([]);
+ expect(r.dropped_count).toBe((full.pages as unknown[]).length + (full.facts as unknown[]).length);
+ expect(r.has_more).toBe(true);
+ for (const t of threadText(full)) expect(r.text as string).toContain(t);
+ expect(r.budget_used).toBe(estimateTokens(r.text as string));
+ expect(r.budget_used).toBeGreaterThan(1); // documented: threads are never truncated
+ });
+
+ // Cursor semantics are the v1 page keyset alone: facts/threads never move
+ // `next_cursor`, and it carries exactly { since, slug } (no skip list).
+ test('next_cursor is the page keyset — unaffected by delivered or dropped facts/threads', async () => {
+ const putPage = operations.find((o) => o.name === 'put_page')!;
+ const local = ctxFor({ remote: false });
+ await call(putPage, local, { slug: 'people/bob-example', content: '# Bob Example\n\nbody' });
+ await new Promise((r) => setTimeout(r, 5));
+ const since = new Date().toISOString();
+ await new Promise((r) => setTimeout(r, 5));
+ for (const s of ['kc-a', 'kc-b']) {
+ await call(putPage, local, { slug: `notes/${s}`, content: `# ${s}\n\ncontent` });
+ }
+ await new Promise((r) => setTimeout(r, 5));
+ const mid = new Date().toISOString();
+ await new Promise((r) => setTimeout(r, 5));
+ for (let i = 0; i < 3; i++) {
+ await call(remember, local, { fact: `kc-fact-${i} ${'z'.repeat(120)}`, provenance: 'test', visibility: 'world' });
+ }
+ await call(remember, local, {
+ fact: 'bob-example will send the revised partnership deck',
+ kind: 'commitment',
+ entity: 'people/bob-example',
+ provenance: 'test',
+ visibility: 'world',
+ });
+ __resetHotMemoryCacheForTests();
+ const full = await call(del, local, { since, entities: 'people/bob-example' });
+ const pages = full.pages as Parameters<typeof renderPageLine>[0][];
+ expect(pages.map((p) => p.slug)).toEqual(['notes/kc-a', 'notes/kc-b']);
+ expect((full.facts as unknown[]).length).toBeGreaterThanOrEqual(3);
+ expect((full.threads as unknown[]).length).toBeGreaterThan(0);
+ // Unbudgeted: the cursor is the last delivered page, exactly as a
+ // stateless page-only call would report it.
+ expect(full.next_cursor).toEqual({ since: pages[1].updated_at, slug: pages[1].slug });
+ // Budget = header + every thread line + the first page line + a sliver:
+ // one page delivered, every fact dropped — the cursor is still that page.
+ const reserved =
+ deltaHeaderCost(since) +
+ (full.threads as Parameters<typeof renderThreadLine>[0][]).reduce((n, t) => n + estimateTokens(renderThreadLine(t) + '\n'), 0);
+ const r1 = await call(del, local, {
+ since,
+ entities: 'people/bob-example',
+ budget_tokens: reserved + estimateTokens(renderPageLine(pages[0]) + '\n') + 2,
+ });
+ expect((r1.pages as Array<{ slug: string }>).map((p) => p.slug)).toEqual(['notes/kc-a']);
+ expect(r1.facts).toEqual([]);
+ expect((r1.threads as unknown[]).length).toBe((full.threads as unknown[]).length);
+ expect(r1.has_more).toBe(true);
+ expect(r1.next_cursor).toEqual({ since: pages[0].updated_at, slug: pages[0].slug });
+ expect(estimateTokens(r1.text as string)).toBeLessThanOrEqual(r1.budget_tokens);
+ // Page-less wake: facts/threads delivered (and some facts dropped) leave
+ // the time cursor exactly where the caller put it.
+ const oneFact = estimateTokens(renderFactLine((full.facts as Parameters<typeof renderFactLine>[0][])[0]) + '\n');
+ const r2 = await call(del, local, { since: mid, entities: 'people/bob-example', budget_tokens: reserved + oneFact + 2 });
+ expect(r2.pages).toEqual([]);
+ expect((r2.facts as unknown[]).length).toBe(1);
+ expect((r2.threads as unknown[]).length).toBe((full.threads as unknown[]).length);
+ expect(r2.has_more).toBe(true);
+ expect(r2.next_cursor).toEqual({ since: mid, slug: '' });
+ });
+
test('forced overflow: dropped_count > 0 and budget_used stays within budget_tokens (v0.45.7)', async () => {
const local = ctxFor({ remote: false });
// Long facts (~55 tokens each): even ONE cannot fit the 20-token budget,
diff --git a/test/autopilot-fanout-wiring.test.ts b/test/autopilot-fanout-wiring.test.ts
index fb31480e22..51b7f6aa0f 100644
--- a/test/autopilot-fanout-wiring.test.ts
+++ b/test/autopilot-fanout-wiring.test.ts
@@ -126,6 +126,38 @@ describe('autopilot.ts ↔ dispatchPerSource wiring', () => {
expect(freshnessBlock).toContain('sourceLocalPathSkipWarning(src.id, src.local_path, undefined, src.config)');
});
+ test('#4399: freshness sync dispatch skips a syncEnabled:false source BEFORE queuing a job', () => {
+ // Real execution of this loop needs the full runAutopilot() daemon (per
+ // this file's own header comment), so this pins the static shape:
+ // the isSyncDisabledConfig skip must sit between the loop's local_path
+ // guard and the queue.add call this file already pins above, so it can
+ // never fire too late to prevent the enqueue. isSyncDisabledConfig
+ // itself has direct unit coverage in test/sync-policy.test.ts.
+ const loopIdx = AUTOPILOT_SRC.indexOf('for (const src of sources) {');
+ expect(loopIdx).toBeGreaterThan(-1);
+ const queueAddIdx = AUTOPILOT_SRC.indexOf('idempotency_key: `autopilot-sync:');
+ expect(queueAddIdx).toBeGreaterThan(loopIdx);
+ const loopBody = AUTOPILOT_SRC.slice(loopIdx, queueAddIdx);
+ // Exact-literal match on the FULL guard clause (condition + continue),
+ // not just the function-call substring — a mutation that keeps calling
+ // isSyncDisabledConfig() but drops the `if (...) continue` (e.g.
+ // `isSyncDisabledConfig(src.config);` as a no-op statement) restores the
+ // #4399 bug while still containing the bare substring, so a loose
+ // `.toContain('isSyncDisabledConfig')` check alone would not catch it.
+ expect(loopBody).toContain('if (isSyncDisabledConfig(src.config)) continue;');
+ // The predicate comes from the sync-policy module via a STATIC import
+ // (the wave review made sources-load static for the same loop; a dynamic
+ // import here would re-introduce what that review removed), not from
+ // performSync's own enforcement — this dispatcher is meant to stand on
+ // its own regardless of what performSync does internally.
+ expect(AUTOPILOT_SRC).toContain("import { isSyncDisabledConfig } from '../core/sync-policy.ts';");
+ expect(AUTOPILOT_SRC).not.toContain("await import('../core/sync-policy.ts')");
+ const skipIdx = loopBody.indexOf('if (isSyncDisabledConfig(src.config)) continue;');
+ const localPathGuardIdx = loopBody.indexOf("if (!src.local_path) continue;");
+ expect(localPathGuardIdx).toBeGreaterThan(-1);
+ expect(skipIdx).toBeGreaterThan(localPathGuardIdx);
+ });
+
test('#4046: targeted dispatch scopes stable recommendation keys to the interval', () => {
expect(AUTOPILOT_SRC).toContain(
'idempotency_key: autopilotRemediationIdempotencyKey(step.idempotency_key, slot)',
diff --git a/test/autopilot-fanout.test.ts b/test/autopilot-fanout.test.ts
index 96c5707965..b066666dbe 100644
--- a/test/autopilot-fanout.test.ts
+++ b/test/autopilot-fanout.test.ts
@@ -24,6 +24,7 @@ import {
shouldSleepHealthyAutopilot,
} from '../src/commands/autopilot-remediation-policy.ts';
import type { SourceRow, BrainEngine } from '../src/core/engine.ts';
+import { SOURCE_FRESHNESS_PHASES } from '../src/core/cycle.ts';
function src(id: string, last_full_cycle_at?: string | null, extra: Record<string, unknown> = {}): SourceRow {
return {
@@ -396,6 +397,28 @@ describe('dispatchPerSource — integration with stubbed engine + queue', () =>
expect((added[0].data as Record<string, unknown>).pull).toBe(true);
});
+ test('#4399: a syncEnabled:false source keeps its freshness cycle but is never pulled or synced', async () => {
+ // The full-cycle fan-out is autopilot's SECOND automatic sync path (the
+ // freshness dispatcher in autopilot.ts is the first). A source the operator
+ // excluded from automatic sync must still get lint/backlinks/extract and its
+ // last_full_cycle_at stamp — only the sync phase (and the pull that feeds
+ // it) is dropped. normalizeQueuedSourcePhases passes a subset through.
+ const disabled = src('disabled', undefined, { syncEnabled: false, remote_url: 'https://github.com/x/y' });
+ const normal = src('normal', undefined, { remote_url: 'https://github.com/x/y' });
+ const { engine, queue, added, fanoutOpts } = makeStubs([disabled, normal]);
+ await dispatchPerSource(engine, queue, fanoutOpts);
+ const byId = new Map<string, AddedJob>(
+ added.map(j => [(j.data as Record<string, unknown>).source_id as string, j]),
+ );
+ const disabledData = byId.get('disabled')!.data as Record<string, unknown>;
+ expect(disabledData.phases).toEqual(SOURCE_FRESHNESS_PHASES.filter((p) => p !== 'sync'));
+ expect(disabledData.phases).toContain('extract');
+ expect(disabledData.pull).toBe(false);
+ const normalData = byId.get('normal')!.data as Record<string, unknown>;
+ expect(normalData.phases).toEqual(SOURCE_FRESHNESS_PHASES);
+ expect(normalData.pull).toBe(true);
+ });
+
test('fanoutMax cap: 3 sources, fanoutMax=1, 1 dispatched + 2 in skippedCap', async () => {
const { engine, queue, added, fanoutOpts } = makeStubs([src('a'), src('b'), src('c')]);
fanoutOpts.fanoutMax = 1;
diff --git a/test/bootstrap-harness.serial.test.ts b/test/bootstrap-harness.serial.test.ts
index a8c3420406..a9ee4af193 100644
--- a/test/bootstrap-harness.serial.test.ts
+++ b/test/bootstrap-harness.serial.test.ts
@@ -798,8 +798,70 @@ describe('outside-voice hardening (X-batch)', () => {
},
};
const code = await statusHarness(parseHarnessArgs(['--status']), statusDeps);
- expect(f.out.join('\n')).toMatch(/verify unavailable/);
- expect(code).toBe(0); // honest degrade, all targets confirmed
+ const out = f.out.join('\n');
+ expect(out).toMatch(/verify unavailable/);
+ expect(out).not.toContain(TOKEN_B);
+ // #4586: the live registration no longer points at OUR serve — the target
+ // line and the exit code say so instead of replaying the receipt's
+ // apply-time 'confirmed'.
+ expect(out).toMatch(/claude-code\/mcp \(user\): failed — .*127\.0\.0\.1:9999.*--force/);
+ expect(code).toBe(1);
+ });
+
+ test('#4586 --status: a user-scope registration replaced by a stdio serve reads failed (human + --json), receipt untouched', async () => {
+ const f = makeFake();
+ expect(await applyHarness(flags(['--harness', 'claude-code', '--no-hooks']), f.deps)).toBe(0);
+ const deps: HarnessDeps = {
+ ...f.deps,
+ runner: async (argv: string[]) => {
+ if (argv[0] === 'claude' && argv[2] === 'get') {
+ // `bootstrap hooks --scope user` / a manual `claude mcp add` took the
+ // name over at OUR scope with a stdio launch: no URL line at all.
+ return {
+ code: 0,
+ stdout: 'gbrain:\n Scope: User config\n Type: stdio\n Command: /usr/local/bin/gbrain\n Args: serve --surface full\n',
+ stderr: '',
+ };
+ }
+ return { code: 0, stdout: '', stderr: '' };
+ },
+ };
+ expect(await statusHarness(parseHarnessArgs(['--status']), deps)).toBe(1);
+ expect(f.out.join('\n')).toMatch(/claude-code\/mcp \(user\): failed — .*stdio/);
+
+ f.out.length = 0;
+ expect(await statusHarness(parseHarnessArgs(['--status', '--json']), deps)).toBe(1);
+ const payload = JSON.parse(f.out[f.out.length - 1]) as {
+ token_verified: unknown;
+ targets: Array<{ host: string; kind: string; state: string }>;
+ };
+ expect(payload.targets.find((t) => t.host === 'claude-code' && t.kind === 'mcp')?.state).toBe('failed');
+ expect(payload.token_verified).toBe('unavailable');
+ // Status is read-only: the receipt still carries the apply-time state.
+ const state = readHarnessReceiptState(f.home) as { receipt: { targets: HarnessTarget[] } };
+ expect(state.receipt.targets.find((t) => t.host === 'claude-code' && t.kind === 'mcp')?.state).toBe('confirmed');
+ });
+
+ test('#4586 negative control: a PROJECT-scope stdio entry (default `bootstrap hooks` shadow) leaves the user-scope target confirmed, exit 0', async () => {
+ const f = makeFake();
+ expect(await applyHarness(flags(['--harness', 'claude-code', '--no-hooks']), f.deps)).toBe(0);
+ const deps: HarnessDeps = {
+ ...f.deps,
+ runner: async (argv: string[]) => {
+ if (argv[0] === 'claude' && argv[2] === 'get') {
+ return {
+ code: 0,
+ stdout: 'gbrain:\n Scope: Project config (shared via .mcp.json)\n Type: stdio\n Command: /usr/local/bin/gbrain\n Args: serve --surface full\n',
+ stderr: '',
+ };
+ }
+ return { code: 0, stdout: '', stderr: '' };
+ },
+ };
+ // Not positive evidence of replacement at OUR scope — a cwd-dependent
+ // shadow, not a takeover — so the receipt state stands (honest degrade).
+ expect(await statusHarness(parseHarnessArgs(['--status']), deps)).toBe(0);
+ expect(f.out.join('\n')).toMatch(/claude-code\/mcp \(user\): confirmed/);
});
test('canary impostor guard: an endpoint that accepts an INVALID credential fails the apply and the fresh mint is revoked', async () => {
diff --git a/test/brain-allowlist.serial.test.ts b/test/brain-allowlist.serial.test.ts
index 378397abbb..34e6dcede1 100644
--- a/test/brain-allowlist.serial.test.ts
+++ b/test/brain-allowlist.serial.test.ts
@@ -20,6 +20,9 @@ import {
} from '../src/core/minions/tools/brain-allowlist.ts';
import type { GBrainConfig } from '../src/core/config.ts';
import type { ToolCtx } from '../src/core/minions/types.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { loadActivePackForWriteVocabulary } from '../src/core/schema-pack/write-vocabulary.ts';
+import { classifyStoredType } from '../src/core/schema-pack/type-usage.ts';
let engine: PGLiteEngine;
const config: GBrainConfig = { engine: 'pglite' } as GBrainConfig;
@@ -258,3 +261,78 @@ describe('sanitizeToolName', () => {
expect(__testing.sanitizeToolName('foo.bar')).toBe('brain_foo_bar');
});
});
+
+// #4852: trusted-workspace subagents (dream synth agentic lane, patterns,
+// delegated jobs) author page content model-side and mint types no bundled
+// pack declares (`reflection` / `original` / `pattern`); the reverse-write puts
+// that type on disk as explicit frontmatter and every `gbrain sync` warns.
+// The oneshot lane already pins its output to 'note' (F5); the seam extends
+// that rule: an EXPLICIT undeclared type rewrites to 'note' + legacy_type.
+describe('brain_put_page pins undeclared model-authored types (#4852)', () => {
+ const PREFIXES = ['wiki/personal/patterns/*'];
+
+ async function putUnderPack(slug: string, content: string, allowedSlugPrefixes?: readonly string[]) {
+ const ctx: ToolCtx = { engine, jobId: 1, remote: true };
+ await withEnv({ GBRAIN_SCHEMA_PACK: 'gbrain-base-v2' }, async () => {
+ const tools = buildBrainTools({ subagentId: 42, engine, config, allowedSlugPrefixes });
+ const putPage = tools.find(t => t.name === 'brain_put_page');
+ await putPage!.execute({ slug, content }, ctx);
+ });
+ return (await engine.getPage(slug, { sourceId: 'default' }))!;
+ }
+
+ test('explicit undeclared type under a slug allow-list → note + frontmatter.legacy_type', async () => {
+ const page = await putUnderPack(
+ 'wiki/personal/patterns/recurring-theme',
+ '---\ntype: pattern\ntitle: Recurring theme\n---\n\nBody [[wiki/personal/reflections/x]]',
+ PREFIXES,
+ );
+ expect(page.type).toBe('note');
+ expect(page.frontmatter.legacy_type).toBe('pattern');
+ expect(page.title).toBe('Recurring theme');
+ expect(page.compiled_truth).toContain('Body [[wiki/personal/reflections/x]]');
+ // The sync type-warning path has nothing to say about the stored type.
+ const pack = await withEnv({ GBRAIN_SCHEMA_PACK: 'gbrain-base-v2' }, () =>
+ loadActivePackForWriteVocabulary({ engine, remote: true }));
+ expect(classifyStoredType(page.type, pack!.manifest).kind).toBe('canonical');
+ });
+
+ test('declared type is stored untouched (no legacy_type)', async () => {
+ const page = await putUnderPack(
+ 'wiki/personal/patterns/declared',
+ '---\ntype: note\ntitle: Declared\n---\n\nBody',
+ PREFIXES,
+ );
+ expect(page.type).toBe('note');
+ expect(page.frontmatter.legacy_type).toBeUndefined();
+ });
+
+ test('declared alias is stored literally (alias_of stays a sync warning, not a rewrite)', async () => {
+ const page = await putUnderPack(
+ 'wiki/personal/patterns/aliased',
+ '---\ntype: insight\ntitle: Aliased\n---\n\nBody',
+ PREFIXES,
+ );
+ expect(page.type).toBe('insight');
+ expect(page.frontmatter.legacy_type).toBeUndefined();
+ });
+
+ test('no explicit type → pack inference untouched', async () => {
+ const page = await putUnderPack(
+ 'wiki/personal/patterns/inferred',
+ '---\ntitle: Inferred\n---\n\nBody',
+ PREFIXES,
+ );
+ expect(page.type).toBe('concept');
+ expect(page.frontmatter.legacy_type).toBeUndefined();
+ });
+
+ test('same write WITHOUT a slug allow-list (legacy agents namespace) stores the literal type', async () => {
+ const page = await putUnderPack(
+ 'wiki/agents/42/pattern-literal',
+ '---\ntype: pattern\ntitle: Literal\n---\n\nBody',
+ );
+ expect(page.type).toBe('pattern');
+ expect(page.frontmatter.legacy_type).toBeUndefined();
+ });
+});
diff --git a/test/by-mention.test.ts b/test/by-mention.test.ts
index 8669e3692e..e893bea354 100644
--- a/test/by-mention.test.ts
+++ b/test/by-mention.test.ts
@@ -276,6 +276,37 @@ describe('findMentionedEntities — pure cases', () => {
}
});
+ // Slug uniqueness is (source_id, slug): with the cross-source guard lifted,
+ // a foreign page that merely shares the scanning page's slug is a real
+ // target, not a self-link.
+ test('17d. allowCrossSource — foreign namesakes of the scanning page are not self-links', () => {
+ const g = gazetteerFromEntries([
+ { slug: 'entities/shared', source_id: 'team-b', title: 'Beta Entity' },
+ { slug: 'entities/shared', source_id: 'team-c', title: 'Gamma Entity' },
+ ]);
+ const mentions = findMentionedEntities('Beta Entity met Gamma Entity.', g, {
+ fromSlug: 'entities/shared', fromSourceId: 'team-a', allowCrossSource: true,
+ });
+ expect(mentions.map(({ source_id, slug }) => [source_id, slug])).toEqual([
+ ['team-b', 'entities/shared'],
+ ['team-c', 'entities/shared'],
+ ]);
+ });
+
+ test('17e. allowCrossSource — first-mention dedup keys on (source_id, slug), not bare slug', () => {
+ const g = gazetteerFromEntries([
+ { slug: 'entities/shared', source_id: 'team-b', title: 'Beta Entity' },
+ { slug: 'entities/shared', source_id: 'team-c', title: 'Gamma Entity' },
+ ]);
+ const mentions = findMentionedEntities('Beta Entity met Gamma Entity.', g, {
+ fromSlug: 'writing/post-1', fromSourceId: 'team-a', allowCrossSource: true,
+ });
+ expect(mentions.map(({ source_id, slug }) => [source_id, slug])).toEqual([
+ ['team-b', 'entities/shared'],
+ ['team-c', 'entities/shared'],
+ ]);
+ });
+
test('20. code-block + token interaction — body text outside block linked, inside skipped', () => {
const g = gazetteerFromEntries([
{ slug: 'companies/acme', source_id: 'default', title: 'Acme' },
diff --git a/test/claude-code-jsonl.test.ts b/test/claude-code-jsonl.test.ts
index a337834876..7e74bca22b 100644
--- a/test/claude-code-jsonl.test.ts
+++ b/test/claude-code-jsonl.test.ts
@@ -107,6 +107,50 @@ describe('parseTranscript on the fixture [G3, A6]', () => {
expect(r.skippedLines).toBeGreaterThanOrEqual(1);
});
+ test('tracks genuine user turns without dropping archival tool placeholders', () => {
+ const dir = tdir();
+ const p = join(dir, 'origins.jsonl');
+ const line = (o: unknown) => JSON.stringify(o);
+ writeFileSync(p, [
+ line({ type: 'user', message: { role: 'user', content: 'I prefer weekly summaries on Friday afternoons.' } }),
+ line({ type: 'assistant', message: { role: 'assistant', content: [{ type: 'tool_use', id: 't-1', name: 'Read', input: { file_path: '/tmp/a' } }] } }),
+ line({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 't-1', content: 'large private payload' }] } }),
+ line({ type: 'user', message: { role: 'user', content: [
+ { type: 'tool_result', tool_use_id: 't-2', content: 'another private payload' },
+ { type: 'text', text: 'Actually, send those summaries on Thursday afternoons.' },
+ ] } }),
+ ].join('\n') + '\n');
+
+ const r = parseTranscript(p);
+ expect(r.turns.map((turn) => turn.text)).toEqual([
+ 'I prefer weekly summaries on Friday afternoons.',
+ '[tool: Read]',
+ '[tool result]',
+ '[tool result]\nActually, send those summaries on Thursday afternoons.',
+ ]);
+ expect(r.genuineUserTurnIndexes).toEqual([0, 3]);
+ });
+
+ test('slash-command bookkeeping records are not genuine user turns (writeback lane)', () => {
+ // Claude Code writes `/clear`-style commands and their stdout as `user`
+ // records whose content is ONLY harness tags. Nobody said that; feeding
+ // it to the writeback lane as the "user prompt" banks junk.
+ const dir = tdir();
+ const p = join(dir, 'commands.jsonl');
+ const line = (o: unknown) => JSON.stringify(o);
+ writeFileSync(p, [
+ line({ type: 'user', message: { role: 'user', content: 'Please remember I take my coffee black.' } }),
+ line({ type: 'user', message: { role: 'user', content: '<command-name>/clear</command-name>\n<command-message>clear</command-message>\n<command-args></command-args>' } }),
+ line({ type: 'user', message: { role: 'user', content: '<local-command-stdout>Cleared 3 files</local-command-stdout>' } }),
+ line({ type: 'user', message: { role: 'user', content: [{ type: 'text', text: '<local-command-stdout>ok</local-command-stdout>' }] } }),
+ line({ type: 'user', message: { role: 'user', content: '<command-name>/foo</command-name> and also: switch me to dark mode everywhere.' } }),
+ ].join('\n') + '\n');
+
+ const r = parseTranscript(p);
+ expect(r.turns).toHaveLength(5); // archival: the records stay in the window
+ expect(r.genuineUserTurnIndexes).toEqual([0, 4]);
+ });
+
test('defaults exist and are sane', () => {
expect(TRANSCRIPT_MAX_BYTES_DEFAULT).toBeGreaterThan(1024 * 1024);
expect(TRANSCRIPT_HARD_CAP_BYTES).toBeGreaterThan(TRANSCRIPT_MAX_BYTES_DEFAULT);
diff --git a/test/code-edges.test.ts b/test/code-edges.test.ts
index a729adbcba..0eeacf713b 100644
--- a/test/code-edges.test.ts
+++ b/test/code-edges.test.ts
@@ -176,3 +176,85 @@ describe('Layer 5 (A1) — code-edges engine methods', () => {
expect((await engine.getPage('post-edge-batch-smoke'))?.slug).toBe(page.slug);
});
});
+
+// #4670 — `code_callees <bare>` promises "bare or qualified name", but every
+// nested chunk (C#/Java/Ruby/Rust namespaces+classes, TS class methods) stores
+// a QUALIFIED from_symbol_qualified, so the exact-match hot path returns 0 for
+// the bare method name. The engine grows an opt-in `bareFallback` that, on a
+// zero-row exact miss for a delimiter-free input, re-runs the same UNION keyed
+// on content_chunks.symbol_name (the bare name). Off by default so the
+// code_flow/code_blast BFS (which feeds bare leaf names back in) keeps its
+// exact posture — a leaf must never inherit a same-named class method's callees.
+describe('#4670 — getCalleesOf bare-name fallback (opt-in)', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+
+ await engine.putPage('src-order-service-cs', {
+ type: 'code', page_kind: 'code',
+ title: 'src/OrderService.cs (c_sharp)',
+ compiled_truth: 'public async Task SubmitAsync() { ValidateRequest(); }',
+ timeline: '',
+ });
+ await engine.upsertChunks('src-order-service-cs', [{
+ chunk_index: 0,
+ chunk_text: 'public async Task SubmitAsync() { ValidateRequest(); }',
+ chunk_source: 'compiled_truth',
+ language: 'c_sharp',
+ symbol_name: 'SubmitAsync',
+ symbol_type: 'method',
+ symbol_name_qualified: 'MyApp.Services.OrderService.SubmitAsync',
+ }]);
+ const chunks = await engine.getChunks('src-order-service-cs');
+ await engine.addCodeEdges([{
+ from_chunk_id: chunks[0]!.id,
+ to_chunk_id: null,
+ from_symbol_qualified: 'MyApp.Services.OrderService.SubmitAsync',
+ to_symbol_qualified: 'ValidateRequest',
+ edge_type: 'calls',
+ }]);
+ });
+
+ afterAll(async () => {
+ await engine.disconnect();
+ }, 30_000);
+
+ test('qualified input hits the exact path with or without the fallback', async () => {
+ const exact = await engine.getCalleesOf('MyApp.Services.OrderService.SubmitAsync', { allSources: true });
+ expect(exact.map(e => e.to_symbol_qualified)).toEqual(['ValidateRequest']);
+ const withFallback = await engine.getCalleesOf('MyApp.Services.OrderService.SubmitAsync', { allSources: true, bareFallback: true });
+ expect(withFallback.map(e => e.to_symbol_qualified)).toEqual(['ValidateRequest']);
+ });
+
+ test('bare input WITHOUT the fallback stays an exact miss (BFS posture unchanged)', async () => {
+ const rows = await engine.getCalleesOf('SubmitAsync', { allSources: true });
+ expect(rows).toHaveLength(0);
+ });
+
+ test('bare input WITH the fallback resolves via content_chunks.symbol_name', async () => {
+ const rows = await engine.getCalleesOf('SubmitAsync', { allSources: true, bareFallback: true });
+ expect(rows.map(e => e.to_symbol_qualified)).toEqual(['ValidateRequest']);
+ expect(rows[0]!.from_symbol_qualified).toBe('MyApp.Services.OrderService.SubmitAsync');
+ });
+
+ test('the fallback is exact on the bare name — no substring / LIKE leakage', async () => {
+ expect(await engine.getCalleesOf('Async', { allSources: true, bareFallback: true })).toHaveLength(0);
+ expect(await engine.getCalleesOf('Submit', { allSources: true, bareFallback: true })).toHaveLength(0);
+ // Underscore is a LIKE wildcard; the reporter's LIKE sketch would match it.
+ expect(await engine.getCalleesOf('Submit_sync', { allSources: true, bareFallback: true })).toHaveLength(0);
+ });
+
+ test('a delimited input never falls back even when the exact path misses', async () => {
+ expect(await engine.getCalleesOf('Other.SubmitAsync', { allSources: true, bareFallback: true })).toHaveLength(0);
+ expect(await engine.getCalleesOf('Foo#SubmitAsync', { allSources: true, bareFallback: true })).toHaveLength(0);
+ });
+
+ test('source scoping still applies on the fallback path', async () => {
+ // The chunk's page + edge live in source 'default'; a foreign scope sees nothing.
+ expect(await engine.getCalleesOf('SubmitAsync', { sourceId: 'some-other-source', bareFallback: true })).toHaveLength(0);
+ expect(await engine.getCalleesOf('SubmitAsync', { sourceId: 'default', bareFallback: true })).toHaveLength(1);
+ });
+});
diff --git a/test/codex-hook-lane.test.ts b/test/codex-hook-lane.test.ts
index f9550af3f9..f470d0d032 100644
--- a/test/codex-hook-lane.test.ts
+++ b/test/codex-hook-lane.test.ts
@@ -44,7 +44,7 @@ describe('parseCodexHookTranscript', () => {
const p = join(dir, 'rollout-1.jsonl');
writeFileSync(p, [meta, injected, user('fix the failing order tests'), customCall, callOutput, assistant('done — pushed the fix'), '{torn'].join('\n') + '\n');
const parsed = parseCodexHookTranscript(p, { collectToolCalls: true });
- expect(parsed.sessionId).toBe('cdx-sess-1');
+ expect(parsed.sessionId).toBe('r-1'); // payload.id, the id codex embeds in the rollout filename (#4981)
expect(parsed.cwd).toBe('/repo');
expect(parsed.turns.map((t) => t.text)).toEqual(['fix the failing order tests', 'done — pushed the fix']);
// custom_tool_call args key is `input` (fixture-verified), a JSON string → parsed.
@@ -93,13 +93,31 @@ describe('parseCodexHookTranscript', () => {
expect(parsed.turns).toHaveLength(3);
});
+ // #4981: a forked/subagent rollout carries its own payload.id plus the ROOT
+ // session_id and an inherited parent session_meta later in the file. The
+ // hook fallback id must be the child's own (first header, payload.id) so it
+ // matches the rollout filename discoverNewestCodexRollout substring-matches.
+ test('forked rollout keeps its own payload.id; an inherited parent header does not overwrite it (#4981)', () => {
+ const p = join(dir, 'rollout-child.jsonl');
+ const inheritedParent = JSON.stringify({
+ timestamp: 't0',
+ type: 'session_meta',
+ payload: { id: 'r-parent', session_id: 'cdx-sess-1', timestamp: 't0', cwd: '/repo-parent', cli_version: '0.147.0' },
+ });
+ writeFileSync(p, [meta, inheritedParent, user('child turn'), assistant('child reply')].join('\n') + '\n');
+ const parsed = parseCodexHookTranscript(p);
+ expect(parsed.sessionId).toBe('r-1');
+ expect(parsed.cwd).toBe('/repo');
+ expect(parsed.turns.map((t) => t.text)).toEqual(['child turn', 'child reply']);
+ });
+
test('over-budget read keeps session_meta identity (head) and the newest turns (tail)', () => {
const p = join(dir, 'rollout-big.jsonl');
const lines = [meta];
for (let i = 0; i < 2000; i++) lines.push(user(`turn-${i} ${'x'.repeat(400)}`));
writeFileSync(p, lines.join('\n') + '\n');
const parsed = parseCodexHookTranscript(p, { maxBytes: 128 * 1024 });
- expect(parsed.sessionId).toBe('cdx-sess-1'); // head window preserved identity
+ expect(parsed.sessionId).toBe('r-1'); // head window preserved identity
expect(parsed.turns[parsed.turns.length - 1]!.text).toContain('turn-1999'); // newest tail kept
expect(parsed.bytesRead).toBeLessThanOrEqual(128 * 1024);
});
diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.ts
new file mode 100644
index 0000000000..7cb3d6f1bd
--- /dev/null
+++ b/test/config-search-registry.test.ts
@@ -0,0 +1,74 @@
+// #4605 — the `search.*` rows in KNOWN_CONFIG_KEYS were a hand-copied list
+// that drifted from the keys mode.ts actually reads: three registered
+// spellings (`search.token_budget`, `search.intent_weighting`,
+// `search.limit_default`) had no reader, while 20 live knobs (the camelCase
+// `search.tokenBudget` / `search.intentWeighting` / `search.searchLimit` the
+// code and every hint print, the reranker.*, cross_modal.*, relational_*
+// keys…) were accepted only through the `search.` prefix. Because the prefix
+// swallows both spellings silently, neither the Levenshtein suggestion nor
+// the --force "Nothing in gbrain reads this" warning could ever fire for a
+// search.* key. These pins keep the registry and the read path in lockstep
+// without config.ts importing mode.ts (config.ts is deliberately lean: its
+// import closure serves engine-free hook children).
+import { describe, expect, test } from 'bun:test';
+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';
+import { KNOB_CONFIG_KEY, SEARCH_MODE_CONFIG_KEYS, SEARCH_MODE_KEY } from '../src/core/search/mode.ts';
+import { REMOTE_PRIVATE_PAGES_KEY } from '../src/core/search/private-visibility.ts';
+
+/** search.* keys read directly via engine.getConfig (not mode-bundle knobs). */
+const DIRECTLY_READ_SINGLETONS = [
+ SEARCH_MODE_KEY,
+ 'search.mode_upgrade_notice_shown', // commands/upgrade.ts
+ 'search.image_query.max_bytes', // ops/image.ts
+ 'search.image_query.daily_budget_usd_per_client', // ops/image.ts
+ 'search.image_query.remote_max_bytes', // ops/image.ts
+ 'search.mcp_keyword_only', // ops/search.ts
+ REMOTE_PRIVATE_PAGES_KEY, // search/private-visibility.ts
+ 'search.track_retrieval', // last-retrieved.ts
+ 'search.intent_patterns', // search/query-intent.ts
+ 'search.adaptive_return', // return-policy.ts via loadConfigWithEngine
+ 'search.adaptive_return_entity_max',
+ 'search.adaptive_return_other_max',
+ 'search.adaptive_return_min_keep',
+ 'search.crag_escalation', // ops/search.ts
+ 'search.crag_think', // ops/search.ts
+];
+
+describe('KNOWN_CONFIG_KEYS search.* rows mirror what the code reads (#4605)', () => {
+ test('the three dead snake_case spellings are gone', () => {
+ for (const k of ['search.token_budget', 'search.intent_weighting', 'search.limit_default']) {
+ expect(KNOWN_CONFIG_KEYS, `${k} has no reader`).not.toContain(k);
+ }
+ });
+
+ test('every key mode.ts reads is registered', () => {
+ const missing = SEARCH_MODE_CONFIG_KEYS.filter((k) => !KNOWN_CONFIG_KEYS.includes(k));
+ expect(missing).toEqual([]);
+ });
+
+ test('every directly-read search.* singleton is registered', () => {
+ const missing = DIRECTLY_READ_SINGLETONS.filter((k) => !KNOWN_CONFIG_KEYS.includes(k));
+ expect(missing).toEqual([]);
+ });
+
+ test('every registered search.* key has a reader (mode knob or listed singleton)', () => {
+ const readers = new Set<string>([...SEARCH_MODE_CONFIG_KEYS, ...DIRECTLY_READ_SINGLETONS]);
+ const dead = KNOWN_CONFIG_KEYS.filter((k) => k.startsWith('search.') && !readers.has(k));
+ expect(dead).toEqual([]);
+ });
+
+ test('no duplicate search.* rows', () => {
+ const rows = KNOWN_CONFIG_KEYS.filter((k) => k.startsWith('search.'));
+ expect(new Set(rows).size).toBe(rows.length);
+ });
+});
+
+describe('KNOB_CONFIG_KEY is the single knob→config-key map', () => {
+ test('SEARCH_MODE_CONFIG_KEYS is derived from it, 1:1, all under search.', () => {
+ const keys = Object.values(KNOB_CONFIG_KEY);
+ expect([...SEARCH_MODE_CONFIG_KEYS].sort()).toEqual([...keys].sort());
+ expect(new Set(keys).size).toBe(keys.length);
+ for (const k of keys) expect(k.startsWith('search.')).toBe(true);
+ expect(keys).not.toContain(SEARCH_MODE_KEY);
+ });
+});
diff --git a/test/config-set.test.ts b/test/config-set.test.ts
index 8f24481bc3..6924c7bee2 100644
--- a/test/config-set.test.ts
+++ b/test/config-set.test.ts
@@ -22,6 +22,7 @@ describe('KNOWN_CONFIG_KEYS', () => {
expect(KNOWN_CONFIG_KEYS).toContain('embedding_model');
expect(KNOWN_CONFIG_KEYS).toContain('embedding_dimensions');
expect(KNOWN_CONFIG_KEYS).toContain('embedding_disabled'); // v0.37 D9
+ expect(KNOWN_CONFIG_KEYS).toContain('auto_timeline'); // #4987 off switch
expect(KNOWN_CONFIG_KEYS).toContain('expansion_model');
expect(KNOWN_CONFIG_KEYS).toContain('chat_model');
expect(KNOWN_CONFIG_KEYS).toContain('openrouter_api_key');
diff --git a/test/context-audit-skill.test.ts b/test/context-audit-skill.test.ts
new file mode 100644
index 0000000000..b19cf8698a
--- /dev/null
+++ b/test/context-audit-skill.test.ts
@@ -0,0 +1,34 @@
+import { describe, test, expect } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+// #4988: the skill's bash pre-pass divided byte counts by 4 and labelled the
+// result "measured"; on Claude-loaded markdown (backticks, paths, punctuation)
+// that undercounts 25-35%. The skill must state the divisor it uses in the
+// report and defer to the host client's exact context breakdown when one exists.
+const skill = readFileSync(join(import.meta.dir, '..', 'skills/context-audit/SKILL.md'), 'utf8');
+
+describe('#4988 context-audit skill states its token-estimate basis', () => {
+ test('pre-pass no longer hard-codes a bare chars/4 divisor', () => {
+ expect(skill).not.toMatch(/\/ 4 \)\)/);
+ expect(skill).not.toContain('chars/4');
+ });
+
+ test('report header carries the estimate basis and defers to the host figure', () => {
+ expect(skill).toContain('Estimate basis');
+ // Anchor to the deferral clause itself — a bare /\/context/ is satisfied by
+ // the `/tmp/context-audit-draft.md` scratch path on the pre-fix file.
+ expect(skill).toContain('Claude Code `/context`');
+ expect(skill).toContain('host-reported exact total (e.g. `/context`)');
+ });
+
+ // #5009: the divisor is the one the issue measured (2.65-3.03 bytes/token on
+ // always-loaded markdown). 3.5 was the top of the range, i.e. still a ~13-24%
+ // undercount; the pre-pass rounds UP so integer math never adds to it.
+ test('divisor is the calibrated bytes/2.8 with ceil arithmetic, not the 3.5 floor', () => {
+ expect(skill).toContain('bytes/2.8');
+ expect(skill).not.toContain('bytes/3.5');
+ expect(skill).not.toContain('* 2 / 7');
+ expect(skill).toContain('* 10 + 27 ) / 28');
+ });
+});
diff --git a/test/contextual-retrieval-doctor.serial.test.ts b/test/contextual-retrieval-doctor.serial.test.ts
index 6010a6d106..080c18d72d 100644
--- a/test/contextual-retrieval-doctor.serial.test.ts
+++ b/test/contextual-retrieval-doctor.serial.test.ts
@@ -69,6 +69,10 @@ describe('contextual_retrieval_coverage doctor check', () => {
expect(result.status).toBe('warn');
expect(result.message).toContain('older chunker_version');
expect(result.message).toContain('gbrain reindex --markdown');
+ // #5004: name the consequence — pages below the safe-chunk index version
+ // are withheld from every remote/MCP chunk read until reindexed.
+ expect(result.message).toContain('1 page(s) below the safe-chunk index version');
+ expect(result.message).toContain('withheld from remote/MCP chunk retrieval');
});
test('NULL mode column is flagged separately', async () => {
diff --git a/test/conversation-parser-cli.test.ts b/test/conversation-parser-cli.test.ts
index 22a638207d..4ad5bd0c0c 100644
--- a/test/conversation-parser-cli.test.ts
+++ b/test/conversation-parser-cli.test.ts
@@ -16,6 +16,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { runConversationParser } from '../src/commands/conversation-parser.ts';
import { BUILTIN_PATTERNS } from '../src/core/conversation-parser/builtins.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
// Capture process.stdout.write + process.stderr.write + process.exit.
function captureStdio() {
@@ -182,6 +183,41 @@ describe('runConversationParser — scan', () => {
});
});
+describe('runConversationParser — scan diagnostics', () => {
+ // A telegram anchor with a non-English month can't rebuild its ISO date;
+ // parse() opens the message anyway and counts it in date_fallback_count.
+ // That count MUST surface in both scan outputs or the operator has no way
+ // to see that timestamps in the page were inherited rather than parsed.
+ const body = [
+ 'Alice Doe, [Mar 15, 2024 at 6:37:00 PM]', 'hello',
+ 'Bob Roe, [Xyz 15, 2024 at 6:38:00 PM]', 'bad month',
+ 'Alice Doe, [Mar 15, 2024 at 6:39:00 PM]', 'bye',
+ ].join('\n');
+ const page = { slug: 'chats/alice-bob', title: 'chat', type: 'conversation', compiled_truth: body, timeline: '', frontmatter: {} };
+ const engine = { getPage: async () => page } as unknown as BrainEngine;
+
+ test('--json carries date_fallback_count', async () => {
+ const cap = captureStdio();
+ try {
+ await runConversationParser(engine, ['scan', 'chats/alice-bob', '--json']);
+ } finally {
+ cap.restore();
+ }
+ const parsed = JSON.parse(cap.out.join('')) as { date_fallback_count?: number };
+ expect(parsed.date_fallback_count).toBe(1);
+ });
+
+ test('human output carries date_fallbacks', async () => {
+ const cap = captureStdio();
+ try {
+ await runConversationParser(engine, ['scan', 'chats/alice-bob']);
+ } finally {
+ cap.restore();
+ }
+ expect(cap.out.join('')).toContain('date_fallbacks: 1');
+ });
+});
+
describe('runConversationParser — unknown subcommand', () => {
test('exits 2 with hint', async () => {
const cap = captureStdio();
diff --git a/test/conversation-parser/parse.test.ts b/test/conversation-parser/parse.test.ts
index 3c7d2c7aa8..f85a1b35d7 100644
--- a/test/conversation-parser/parse.test.ts
+++ b/test/conversation-parser/parse.test.ts
@@ -1338,3 +1338,62 @@ describe('unrecognized_headings — folded speaker headings surface (#4136)', ()
expect(messages.length).toBe(2);
});
});
+
+// ---------------------------------------------------------------------------
+// Date-fallback anchoring (#4681 narrow cut): an anchor whose date cannot be
+// reconstructed still opens its own message instead of being dropped and
+// folding its body into the previous speaker.
+// ---------------------------------------------------------------------------
+
+describe('date-fallback anchoring applies to every pattern (#4681)', () => {
+ test('a telegram anchor with an unknown month opens a fallback-dated message instead of folding', () => {
+ // buildIso() returning null used to drop the anchor; on a multi_line
+ // pattern the body then folded into the PREVIOUS speaker while the parse
+ // still returned regex_match (silent misattribution). Reachable on
+ // telegram-text-export with any non-English 3-letter month.
+ const body = [
+ 'Alice Doe, [Mar 15, 2024 at 6:37:00 PM]',
+ 'hello',
+ 'Bob Roe, [Xyz 15, 2024 at 6:38:00 PM]',
+ 'bad month',
+ 'Alice Doe, [Mar 15, 2024 at 6:39:00 PM]',
+ 'bye',
+ ].join('\n');
+ const r = parseConversation(body, { fallbackDate: '2024-03-15' });
+ expect(r.matched_pattern_id).toBe('telegram-text-export');
+ expect(r.messages).toHaveLength(3);
+ expect(r.messages[0].text).toBe('hello');
+ expect(r.messages[1].speaker).toContain('Bob');
+ expect(r.messages[1].text).toBe('bad month');
+ // Inherits the previous anchor's timestamp (NOT midnight): a midnight
+ // stamp mid-page would open a new too-short segment downstream in
+ // extract-conversation-facts and lose the following message.
+ expect(r.messages[1].timestamp).toBe('2024-03-15T18:37:00Z');
+ expect(r.messages[2].text).toBe('bye');
+ expect(r.date_fallback_count).toBe(1);
+ });
+
+ test('a first-anchor date failure anchors at midnight of the page fallback date', () => {
+ const body = [
+ 'Bob Roe, [Xyz 15, 2024 at 6:38:00 PM]',
+ 'bad month',
+ 'Alice Doe, [Mar 15, 2024 at 6:39:00 PM]',
+ 'bye',
+ ].join('\n');
+ const r = parseConversation(body, { fallbackDate: '2024-03-15' });
+ expect(r.matched_pattern_id).toBe('telegram-text-export');
+ expect(r.messages).toHaveLength(2);
+ expect(r.messages[0].speaker).toContain('Bob');
+ expect(r.messages[0].text).toBe('bad month');
+ expect(r.messages[0].timestamp).toBe('2024-03-15T00:00:00Z');
+ expect(r.date_fallback_count).toBe(1);
+ });
+
+ test('healthy pages carry no date_fallback_count (JSON stays byte-identical)', () => {
+ const body = ['Alice Doe, [Mar 15, 2024 at 6:37:00 PM]', 'hello', 'Bob Roe, [Mar 15, 2024 at 6:38:00 PM]', 'hi'].join('\n');
+ const r = parseConversation(body, { fallbackDate: '2024-03-15' });
+ expect(r.messages).toHaveLength(2);
+ expect(r.date_fallback_count).toBeUndefined();
+ expect('date_fallback_count' in JSON.parse(JSON.stringify(r))).toBe(false);
+ });
+});
diff --git a/test/core/base-phase.test.ts b/test/core/base-phase.test.ts
index 254548e2fc..a4c5e4c8fe 100644
--- a/test/core/base-phase.test.ts
+++ b/test/core/base-phase.test.ts
@@ -190,12 +190,27 @@ describe('BaseCyclePhase', () => {
});
describe('dry-run propagation', () => {
- test('opts.dryRun is forwarded through to process()', async () => {
+ // #4823: no subclass has a dry-run path (they bill LLM calls + INSERT rows),
+ // so run() skips process() entirely under dry-run — from either channel.
+ test('opts.dryRun skips process() with no_dry_run_support', async () => {
captured.length = 0;
const phase = new TestPhase();
const ctx = buildCtx({ sourceId: 'tenant-a' });
- await phase.run(ctx, { dryRun: true });
- expect(captured[0]!.dryRun).toBe(true);
+ const r = await phase.run(ctx, { dryRun: true });
+ expect(captured.length).toBe(0);
+ expect(r.status).toBe('skipped');
+ expect(r.details.reason).toBe('no_dry_run_support');
+ expect(r.details.dryRun).toBe(true);
+ });
+
+ test('ctx.dryRun === true skips process() even when opts omit dryRun', async () => {
+ captured.length = 0;
+ const phase = new TestPhase();
+ const ctx = { ...buildCtx({ sourceId: 'tenant-a' }), dryRun: true };
+ const r = await phase.run(ctx);
+ expect(captured.length).toBe(0);
+ expect(r.status).toBe('skipped');
+ expect(r.details.reason).toBe('no_dry_run_support');
});
test('omitting opts.dryRun leaves it undefined (not coerced)', async () => {
diff --git a/test/core/budget/expand-records-budget.test.ts b/test/core/budget/expand-records-budget.test.ts
index 3bbd244b11..6725b1f8a2 100644
--- a/test/core/budget/expand-records-budget.test.ts
+++ b/test/core/budget/expand-records-budget.test.ts
@@ -188,10 +188,11 @@ describe('expand() budget accounting — openai-compatible schemaless (viaText)
});
describe('expand() budget accounting — openai-compatible structured-output (generateObject) path', () => {
- // No built-in recipe currently opts into supports_structured_outputs (it's
- // an opt-in per-backend capability declared in ChatTouchpoint — see
- // recipeSupportsStructuredOutputs()'s own unit test in gateway-chat.test.ts
- // for the same "no shipped recipe exercises this today" situation). Rather
+ // supports_structured_outputs is an opt-in per-backend capability declared
+ // in ChatTouchpoint; ollama is the one built-in recipe that declares it
+ // (server-side json_schema, #4863), and the hosted openai-compat recipes
+ // (deepseek/groq/together) stay opted out — see recipeSupportsStructuredOutputs()'s
+ // own unit test in gateway-chat.test.ts. Rather
// than mutating a shipped recipe singleton, use the established synthetic-
// recipe seam (__setTestRecipesForTests, already used by
// no-batch-cap-suppression.serial.test.ts / adaptive-embed-batch.test.ts):
diff --git a/test/core/cycle.serial.test.ts b/test/core/cycle.serial.test.ts
index c359b2d07e..89e25156ca 100644
--- a/test/core/cycle.serial.test.ts
+++ b/test/core/cycle.serial.test.ts
@@ -20,6 +20,8 @@ let backlinksCalls: Array<{ action: string; dir: string; dryRun: boolean | undef
let syncCalls: Array<{ dryRun: boolean | undefined; noPull: boolean | undefined; noExtract: boolean | undefined; sourceId: string | undefined }> = [];
let extractCalls: Array<{ mode: string; dir: string; slugs: string[] | undefined }> = [];
let embedCalls: Array<{ stale: boolean | undefined; dryRun: boolean | undefined }> = [];
+// #4599: per-test overrides spread onto the mock's EmbedResult (e.g. reason: 'stall_timeout').
+let embedResultOverride: Record<string, unknown> = {};
let orphansCalls: number = 0;
let orphansOpts: Array<{ sourceId?: string } | undefined> = [];
let schemaSuggestOpts: Array<{ sourceId?: string; dryRun?: boolean } | undefined> = [];
@@ -93,6 +95,7 @@ mock.module('../../src/commands/embed.ts', () => ({
total_chunks: 10,
pages_processed: 3,
dryRun: !!opts.dryRun,
+ ...embedResultOverride,
};
},
runEmbed: async () => {},
@@ -158,6 +161,7 @@ beforeEach(() => {
syncCalls = [];
extractCalls = [];
embedCalls = [];
+ embedResultOverride = {};
orphansCalls = 0;
orphansOpts = [];
schemaSuggestOpts = [];
@@ -201,6 +205,15 @@ describe('runCycle — dryRun propagates to every phase', () => {
expect(extractPhase?.status).toBe('skipped');
expect(extractPhase?.details.reason).toBe('no_dry_run_support');
});
+
+ test('dryRun skips the calibration trio — no LLM calls, no take_proposals/grade/profile writes (#4823)', async () => {
+ const report = await runCycle(sharedEngine,{ brainDir: '/tmp/brain', dryRun: true });
+ for (const name of ['propose_takes', 'grade_takes', 'calibration_profile'] as const) {
+ const phase = report.phases.find(p => p.phase === name);
+ expect(phase?.status).toBe('skipped');
+ expect(phase?.details.reason).toBe('no_dry_run_support');
+ }
+ });
});
// ─── Phase selection ──────────────────────────────────────────────
@@ -688,3 +701,28 @@ describe('runCycle — onceForPhase bypasses only the named phase (issue #2860)'
expect(await sharedEngine.getConfig('dream.patterns.enabled')).toBe('false');
});
});
+
+// ─── #4599: embed phase honours the stall watchdog's X6 contract ────
+// runEmbedCore never throws on a stall; it returns reason:'stall_timeout'
+// (embed-stall.ts). Every non-CLI consumer must convert that to a failure,
+// otherwise a nightly drain the watchdog aborted is reported as a healthy
+// embed phase and the dream/autopilot verdict never notices.
+
+describe('runCycle — embed phase fails on stall_timeout (#4599)', () => {
+ beforeEach(async () => {
+ await truncateCycleLocks(sharedEngine);
+ });
+
+ test("reason:'stall_timeout' from runEmbedCore yields a failed embed phase", async () => {
+ embedResultOverride = { reason: 'stall_timeout', failures: 1 };
+ const report = await runCycle(sharedEngine, { brainDir: '/tmp/brain' });
+ const embedPhase = report.phases.find(p => p.phase === 'embed');
+ expect(embedPhase?.status).toBe('fail');
+ expect(String(embedPhase?.error?.message)).toMatch(/stall_timeout/);
+ });
+
+ test('a normal result is still an ok embed phase', async () => {
+ const report = await runCycle(sharedEngine, { brainDir: '/tmp/brain' });
+ expect(report.phases.find(p => p.phase === 'embed')?.status).toBe('ok');
+ });
+});
diff --git a/test/cycle-patterns-evidence-gate.serial.test.ts b/test/cycle-patterns-evidence-gate.serial.test.ts
new file mode 100644
index 0000000000..891d41ab55
--- /dev/null
+++ b/test/cycle-patterns-evidence-gate.serial.test.ts
@@ -0,0 +1,147 @@
+// #4879: the patterns phase re-ran a paid subagent on the same unchanged
+// reflections every autopilot tick (no completion stamp, unlike synthesize /
+// auto_think). The fix is a knob-free evidence watermark: a completed run
+// stamps `dream.patterns.last_evidence_ts` = max reflection updated_at, and
+// the phase skips (`no_new_evidence`) while nothing is newer than that.
+import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+const STAMP_KEY = 'dream.patterns.last_evidence_ts';
+
+// Mutable so T4 can drive the child to a non-completed outcome.
+let childStatus = 'completed';
+
+mock.module('../src/core/ai/gateway.ts', () => ({
+ probeChatModel: () => ({ ok: true }),
+}));
+
+mock.module('../src/core/cycle/synthesize.ts', () => ({
+ loadAllowedSlugPrefixes: async () => ['wiki/personal/patterns/*'],
+ loadOutputRoot: async () => 'wiki',
+ runSubagentsInline: async () => undefined,
+}));
+
+mock.module('../src/core/minions/wait-for-completion.ts', () => ({
+ TimeoutError: class TimeoutError extends Error {},
+ waitForCompletion: async (_queue: unknown, jobId: number) => ({
+ id: jobId,
+ status: childStatus,
+ }),
+ // A module mock replaces the WHOLE module, so it must export every named
+ // import its consumers reach for (a missing one is a load-time SyntaxError).
+ waitForCompletionRenewing: async (
+ _queue: unknown,
+ jobId: number,
+ opts?: { renew?: () => Promise<void> },
+ ) => {
+ if (opts?.renew) await opts.renew();
+ return { id: jobId, status: childStatus };
+ },
+}));
+
+const { runPhasePatterns } = await import('../src/core/cycle/patterns.ts');
+
+let engine: PGLiteEngine;
+let schemaVersion: string;
+let brainDir: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ schemaVersion = (await engine.getConfig('version')) ?? '7';
+ brainDir = mkdtempSync(join(tmpdir(), 'gbrain-patterns-evidence-'));
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(brainDir, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ childStatus = 'completed';
+ await resetPgliteState(engine);
+ await engine.setConfig('version', schemaVersion);
+ await engine.setConfig('models.dream.patterns', 'anthropic:claude-sonnet-4-6');
+ await seedReflections();
+});
+
+const reflectionSlug = (i: number) => `wiki/personal/reflections/2026-08-0${i + 1}-reflection`;
+
+async function seedReflections(): Promise<void> {
+ for (let i = 0; i < 3; i++) {
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, type, title, compiled_truth)
+ VALUES ($1, 'note', $2, $3)`,
+ [reflectionSlug(i), `Reflection ${i + 1}`, `Recurring theme fixture number ${i + 1}.`],
+ );
+ }
+}
+
+async function maxReflectionUpdatedAt(): Promise<string> {
+ const rows = await engine.executeRaw<{ m: string | Date }>(
+ `SELECT max(updated_at) AS m FROM pages WHERE slug LIKE 'wiki/personal/reflections/%'`,
+ );
+ return new Date(rows[0].m).toISOString();
+}
+
+describe('runPhasePatterns evidence watermark (#4879)', () => {
+ test('T1: completed run stamps max reflection updated_at; identical re-run skips no_new_evidence', async () => {
+ const first = await runPhasePatterns(engine, { brainDir, dryRun: false });
+ expect(first.status).toBe('ok');
+ expect(first.details.child_outcome).toBe('completed');
+
+ expect(await engine.getConfig(STAMP_KEY)).toBe(await maxReflectionUpdatedAt());
+
+ const second = await runPhasePatterns(engine, { brainDir, dryRun: false });
+ expect(second.status).toBe('skipped');
+ expect(second.details.reason).toBe('no_new_evidence');
+ expect(second.summary).toContain('--once');
+ });
+
+ test('T2: an edited reflection re-arms the phase and advances the stamp', async () => {
+ const first = await runPhasePatterns(engine, { brainDir, dryRun: false });
+ expect(first.status).toBe('ok');
+ const stampBefore = await engine.getConfig(STAMP_KEY);
+ expect(stampBefore).toBeTruthy();
+
+ const later = new Date(Date.parse(stampBefore!) + 5_000).toISOString();
+ await engine.executeRaw(
+ `UPDATE pages SET compiled_truth = 'edited', updated_at = $2::timestamptz WHERE slug = $1`,
+ [reflectionSlug(1), later],
+ );
+
+ const second = await runPhasePatterns(engine, { brainDir, dryRun: false });
+ expect(second.status).toBe('ok');
+ expect(await engine.getConfig(STAMP_KEY)).toBe(later);
+ });
+
+ test('T3: --once bypasses the gate and still stamps the consumed evidence', async () => {
+ // A stamp in the future would gate every normal run.
+ await engine.setConfig(STAMP_KEY, new Date(Date.now() + 60_000).toISOString());
+
+ const forced = await runPhasePatterns(engine, { brainDir, dryRun: false, once: true });
+ expect(forced.status).toBe('ok');
+ // A manually consumed evidence set must not be re-paid by the next tick.
+ expect(await engine.getConfig(STAMP_KEY)).toBe(await maxReflectionUpdatedAt());
+ });
+
+ test('T4: a non-completed child does not stamp (retried next tick)', async () => {
+ childStatus = 'timeout';
+ const result = await runPhasePatterns(engine, { brainDir, dryRun: false });
+ expect(result.status).toBe('fail');
+ expect(result.error?.code).toBe('PATTERNS_CHILD_TIMEOUT');
+ expect(await engine.getConfig(STAMP_KEY)).toBeNull();
+ });
+
+ test('T5: dry-run reports the skip honestly when nothing is newer', async () => {
+ await engine.setConfig(STAMP_KEY, await maxReflectionUpdatedAt());
+ const result = await runPhasePatterns(engine, { brainDir, dryRun: true });
+ expect(result.status).toBe('skipped');
+ expect(result.details.reason).toBe('no_new_evidence');
+ });
+});
diff --git a/test/delete-write-through-commit.serial.test.ts b/test/delete-write-through-commit.serial.test.ts
new file mode 100644
index 0000000000..814766058e
--- /dev/null
+++ b/test/delete-write-through-commit.serial.test.ts
@@ -0,0 +1,143 @@
+/**
+ * deletePageThrough reaches git on durability-hardened repos.
+ *
+ * Bug class (the delete-side twin of #2426): `delete_page` unlinked the
+ * write-through `.md` in `sync.repo_path` but NOTHING ever committed the
+ * removal. The post-commit hook only fires after a commit, so the deletion sat
+ * in the working tree as an uncommitted ` D` — invisible to commit-driven
+ * sync, which then warned "N uncommitted file(s) invisible to commit-driven
+ * sync" every tick until a human committed it by hand.
+ *
+ * Fix: `deletePageThrough` best-effort commits the removal (path-limited) when
+ * the repo carries the gbrain durability post-commit hook, exactly as
+ * `writePageThrough` does for writes. Unhardened repos keep the old
+ * unlink-only behavior.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, writeFileSync, rmSync, mkdirSync, chmodSync, existsSync } from 'fs';
+import { execSync, execFileSync } from 'child_process';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { writePageThrough, deletePageThrough } from '../src/core/write-through.ts';
+
+let engine: PGLiteEngine;
+let repo: string;
+
+function git(cwd: string, ...args: string[]): string {
+ return execFileSync('git', ['-C', cwd, ...args], {
+ stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8',
+ }).trim();
+}
+
+/** Hook file carrying the gbrain durability banner (what `isDurabilityHardened`
+ * looks for) with a no-op body so tests never attempt a real push. */
+function installFakeDurabilityHook(repoPath: string): void {
+ const hooksDir = join(repoPath, '.git', 'hooks');
+ mkdirSync(hooksDir, { recursive: true });
+ const hookPath = join(hooksDir, 'post-commit');
+ writeFileSync(hookPath, [
+ '#!/usr/bin/env bash',
+ '# gbrain brain-durability post-commit hook (v0.42.44+)',
+ 'exit 0',
+ '',
+ ].join('\n'));
+ chmodSync(hookPath, 0o755);
+}
+
+async function seedPage(slug: string): Promise<void> {
+ await engine.putPage(slug, {
+ type: 'concept',
+ title: 'Page that will be deleted',
+ compiled_truth: 'Content whose removal must reach git.',
+ timeline: '',
+ frontmatter: { type: 'concept' },
+ });
+}
+
+describe('deletePageThrough auto-commit on durability-hardened repos', () => {
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 60_000);
+
+ afterAll(async () => {
+ if (engine) await engine.disconnect();
+ }, 60_000);
+
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ repo = mkdtempSync(join(tmpdir(), 'gbrain-dwt-'));
+ execSync('git init', { cwd: repo, stdio: 'pipe' });
+ execSync('git config user.email "[email protected]"', { cwd: repo, stdio: 'pipe' });
+ execSync('git config user.name "T"', { cwd: repo, stdio: 'pipe' });
+ writeFileSync(join(repo, 'seed.md'), 'seed\n');
+ execSync('git add -A && git commit -m init', { cwd: repo, stdio: 'pipe' });
+ await engine.setConfig('sync.repo_path', repo);
+ });
+
+ afterEach(() => {
+ if (repo) rmSync(repo, { recursive: true, force: true });
+ });
+
+ test('on a hardened repo, the removal is committed (path-limited)', async () => {
+ installFakeDurabilityHook(repo);
+ await seedPage('notes/hello');
+ const written = await writePageThrough(engine, 'notes/hello');
+ expect(written.committed).toBe(true);
+ // Unrelated dirty edit — must NOT be swept into the delete commit.
+ writeFileSync(join(repo, 'seed.md'), 'dirty unrelated edit\n');
+
+ const result = await deletePageThrough(engine, 'notes/hello');
+
+ expect(result.removed).toBe(true);
+ expect(result.committed).toBe(true);
+ expect(existsSync(join(repo, 'notes', 'hello.md'))).toBe(false);
+ // The removal is committed…
+ expect(git(repo, 'log', '-1', '--format=%s')).toBe('gbrain: delete write-through notes/hello');
+ expect(git(repo, 'log', '-1', '--name-only', '--format=')).toBe('notes/hello.md');
+ expect(git(repo, 'status', '--porcelain', 'notes/hello.md')).toBe('');
+ // …and the unrelated edit stays uncommitted (explicit-path discipline).
+ expect(git(repo, 'status', '--porcelain', 'seed.md')).not.toBe('');
+ }, 60_000);
+
+ test('on an unhardened repo, the file is unlinked but NOT committed (no behavior change)', async () => {
+ await seedPage('notes/plain');
+ await writePageThrough(engine, 'notes/plain');
+ // Track the page so the unlink shows up as a working-tree deletion.
+ execSync('git add -A && git commit -m seed-page', { cwd: repo, stdio: 'pipe' });
+
+ const result = await deletePageThrough(engine, 'notes/plain');
+
+ expect(result.removed).toBe(true);
+ expect(result.committed).toBeUndefined();
+ expect(existsSync(join(repo, 'notes', 'plain.md'))).toBe(false);
+ // Deleted in the working tree, uncommitted — the pre-existing contract.
+ // (`git()` trims, so porcelain's leading worktree-column space is gone.)
+ expect(git(repo, 'status', '--porcelain', 'notes/plain.md')).toMatch(/^ ?D notes\/plain\.md$/);
+ expect(git(repo, 'log', '-1', '--format=%s')).toBe('seed-page');
+ }, 60_000);
+
+ test('hardened AFTER the write: the never-committed page is unlinked with nothing to commit (no empty commit)', async () => {
+ // Written while unhardened → the artifact is untracked (pre-#2426 contract).
+ await seedPage('notes/late');
+ const written = await writePageThrough(engine, 'notes/late');
+ expect(written.committed).toBeUndefined();
+ expect(git(repo, 'status', '--porcelain', 'notes/late.md')).toContain('?? notes/late.md');
+ // Harden between the write and the delete.
+ installFakeDurabilityHook(repo);
+
+ const result = await deletePageThrough(engine, 'notes/late');
+
+ expect(result.removed).toBe(true);
+ expect(existsSync(join(repo, 'notes', 'late.md'))).toBe(false);
+ // `git add -- <vanished untracked path>` fails → the best-effort commit
+ // reports false → no `committed`, no empty commit, and nothing left behind.
+ expect(result.committed).toBeUndefined();
+ expect(git(repo, 'status', '--porcelain')).toBe('');
+ expect(git(repo, 'log', '-1', '--format=%s')).toBe('init');
+ }, 60_000);
+});
diff --git a/test/docs-bootstrap-persistence-table.test.ts b/test/docs-bootstrap-persistence-table.test.ts
new file mode 100644
index 0000000000..081dc30d5d
--- /dev/null
+++ b/test/docs-bootstrap-persistence-table.test.ts
@@ -0,0 +1,26 @@
+import { describe, test, expect } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+// #4986: three code paths in src/commands/hook.ts spawn the workspace push —
+// stopPushIfDue (Stop), hookSessionEnd (SessionEnd) and dirtyTreePush (the
+// SessionStart crash-recovery push). Only the Stop path reads GBRAIN_STOP_PUSH
+// and hooks.stop_push_debounce_min. The operator-facing table must say so and
+// list the recovery push, or an operator tuning the debounce expects it to slow
+// commits that the other two paths keep landing.
+const rows = readFileSync(join(import.meta.dir, '..', 'docs/guides/bootstrap.md'), 'utf8').split('\n');
+
+describe('#4986 bootstrap.md scopes the Stop-push knobs and lists every push path', () => {
+ test('per-turn row says the switch + debounce govern the Stop path only', () => {
+ const row = rows.find((l) => l.startsWith('| Per-turn persistence'));
+ expect(row).toBeDefined();
+ expect(row).toMatch(/Stop path only/);
+ });
+
+ test('session-end row names no switch/debounce; crash-recovery push has its own row', () => {
+ const sessionEnd = rows.find((l) => l.startsWith('| Session persistence'));
+ expect(sessionEnd).toBeDefined();
+ expect(sessionEnd).toMatch(/no per-path switch or debounce/);
+ expect(rows.some((l) => l.startsWith('| Crash recovery'))).toBe(true);
+ });
+});
diff --git a/test/docs-mcp-deploy.test.ts b/test/docs-mcp-deploy.test.ts
new file mode 100644
index 0000000000..520b3ab08c
--- /dev/null
+++ b/test/docs-mcp-deploy.test.ts
@@ -0,0 +1,88 @@
+/**
+ * #4500: docs/mcp/DEPLOY.md + ALTERNATIVES.md must document the tailnet/LAN-only
+ * `serve --http` shape and the MCP SDK's "Issuer URL must be HTTPS" exit.
+ *
+ * The HTTPS-issuer check lives in @modelcontextprotocol/sdk (checkIssuerUrl), so
+ * gbrain cannot soften it; the only fix is telling operators which shapes work
+ * (Tailscale Serve, plain-HTTP bearer-only without --public-url) and naming the
+ * SDK's own opt-in. Doc-text pins, same precedent as docs-cli-commands.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'fs';
+import { dirname, join } from 'path';
+
+const ROOT = dirname(import.meta.dir);
+const deploy = readFileSync(join(ROOT, 'docs/mcp/DEPLOY.md'), 'utf8');
+const alternatives = readFileSync(join(ROOT, 'docs/mcp/ALTERNATIVES.md'), 'utf8');
+
+describe('DEPLOY.md documents the tailnet/LAN-only serve --http shape (#4500)', () => {
+ test('troubleshooting names the SDK issuer error and its opt-in', () => {
+ const troubleshooting = deploy.slice(deploy.indexOf('## Troubleshooting'));
+ expect(troubleshooting).toContain('Issuer URL must be HTTPS');
+ expect(troubleshooting).toContain('MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL');
+ });
+
+ test('HTTP section states --source-guard is stdio-only and points at the CORS allowlist', () => {
+ expect(deploy).toContain('--source-guard');
+ expect(deploy).toContain('GBRAIN_HTTP_CORS_ORIGIN');
+ });
+
+ test('ALTERNATIVES.md distinguishes tailnet-only Serve from public Funnel', () => {
+ expect(alternatives).toContain('tailscale serve');
+ expect(alternatives).toContain('tailscale funnel');
+ });
+});
+
+describe('DEPLOY.md documents dual-mode /mcp auth (#4893)', () => {
+ // The anonymous 401 + resource_metadata challenge is spec discovery, not
+ // proof the configured bearer failed; client status probes that omit the
+ // header report needsAuth while authenticated tool calls succeed.
+ test('troubleshooting covers "needsAuth while tool calls succeed"', () => {
+ const troubleshooting = deploy.slice(deploy.indexOf('## Troubleshooting'));
+ expect(troubleshooting).toContain('needsAuth');
+ expect(troubleshooting).toContain('whoami');
+ });
+});
+
+describe('DEPLOY.md documents the owner magic-link flow (#5007)', () => {
+ // The admin login page tells owners to ask their agent for a login link; the
+ // mint endpoint already exists, so the only fix is documenting it where the
+ // agent looks (DEPLOY.md + `gbrain auth --help`). Source reads below pin the
+ // help text and anchor the documented route to the real registration.
+ // test-reads-source-ok: AUTH_USAGE is a help-text template literal; pinning its spelling IS the contract
+ const auth = readFileSync(join(ROOT, 'src/commands/auth.ts'), 'utf8');
+ // test-reads-source-ok: anchors the documented route to the existing app.post registration
+ const server = readFileSync(join(ROOT, 'src/commands/serve-http.ts'), 'utf8');
+
+ test('documents the owner request and the existing mint endpoint', () => {
+ expect(deploy).toContain('Give me the GBrain admin login link');
+ expect(deploy).toContain('POST /admin/api/issue-magic-link');
+ expect(server).toContain("app.post('/admin/api/issue-magic-link'");
+ });
+
+ test('auth help points at the owner login flow without inventing a CLI command', () => {
+ expect(auth).toContain('Admin dashboard login (running HTTP server):');
+ expect(auth).toContain('POST /admin/api/issue-magic-link');
+ expect(auth).toContain('See docs/mcp/DEPLOY.md.');
+ });
+
+ test('warns against consuming the single-use nonce during verification', () => {
+ expect(deploy).toContain('Do not GET or fetch the generated login URL');
+ expect(auth).toContain('do not GET the generated link');
+ });
+
+ test('preserves private delivery and protected-bootstrap requirements', () => {
+ expect(deploy).toContain('GBRAIN_ADMIN_BOOTSTRAP_TOKEN');
+ expect(deploy).toContain('only to the requesting owner in');
+ expect(deploy).toContain('Never expose its value in chat, logs, shell arguments,');
+ expect(deploy).toContain('An MCP client bearer token or client secret is not the');
+ });
+
+ test('distinguishes login from client creation and states lifecycle limits', () => {
+ expect(deploy).toContain('does not create, reveal, or rotate');
+ expect(deploy).toContain('expires after five minutes');
+ expect(deploy).toContain('cannot be replayed');
+ expect(deploy).toContain('invalidated by a server restart');
+ expect(deploy).toContain("server's configured `--public-url`");
+ });
+});
diff --git a/test/docs-timeline-extraction-guide.test.ts b/test/docs-timeline-extraction-guide.test.ts
new file mode 100644
index 0000000000..3b17bfbcbb
--- /dev/null
+++ b/test/docs-timeline-extraction-guide.test.ts
@@ -0,0 +1,27 @@
+import { describe, test, expect } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+// #4987: timeline extraction scans the WHOLE page (parseTimelineEntries +
+// parseInlineCitationTimelineEntries — behavior pinned in test/extract.test.ts);
+// the `<!-- timeline -->` sentinel only splits compiled_truth from timeline for
+// storage. The docs must not tell operators the sentinel scopes extraction,
+// because a `[Source: ..., YYYY-MM-DD]` citation under a compiled-truth bullet
+// mints a permanent timeline row and no removal op exists.
+const repoRoot = join(import.meta.dir, '..');
+
+describe('#4987 timeline extraction docs describe the real trigger', () => {
+ test('system-of-record.md Timeline row names dated markers anywhere in the page', () => {
+ const doc = readFileSync(join(repoRoot, 'docs/architecture/system-of-record.md'), 'utf8');
+ const row = doc.split('\n').find((l) => l.startsWith('| **Timeline**'));
+ expect(row).toBeDefined();
+ expect(row).not.toMatch(/section after/);
+ expect(row).toContain('[Source:');
+ });
+
+ test('compiled-truth.md warns that compiled-truth citations mint timeline rows', () => {
+ const doc = readFileSync(join(repoRoot, 'docs/guides/compiled-truth.md'), 'utf8');
+ expect(doc).toContain('auto_timeline');
+ expect(doc).toMatch(/blank line above and\s+below/);
+ });
+});
diff --git a/test/doctor-fts-reindex-incomplete.test.ts b/test/doctor-fts-reindex-incomplete.test.ts
new file mode 100644
index 0000000000..3ddc7d86ed
--- /dev/null
+++ b/test/doctor-fts-reindex-incomplete.test.ts
@@ -0,0 +1,33 @@
+/**
+ * fts_reindex_incomplete doctor check (#4795).
+ *
+ * `gbrain reindex-search-vector` stamps `fts.reindex_in_progress` (= target
+ * language) in the config table before flipping the trigger functions and
+ * clears it only after both backfills finish. While the marker is set the
+ * brain's keyword index is split across two tokenizers, so doctor must
+ * FAIL (exit 1) and name the resume command; healthy brains push nothing.
+ */
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { ftsReindexIncompleteCheck } from '../src/commands/doctor/checks/fts-reindex.ts';
+
+function engineWith(config: Record<string, string>): BrainEngine {
+ return {
+ getConfig: async (key: string) => config[key] ?? null,
+ } as unknown as BrainEngine;
+}
+
+describe('ftsReindexIncompleteCheck', () => {
+ test('marker set → fail naming the language and the resume command', async () => {
+ const check = await ftsReindexIncompleteCheck(engineWith({ 'fts.reindex_in_progress': 'dutch' }));
+ expect(check).not.toBeNull();
+ expect(check!.name).toBe('fts_reindex_incomplete');
+ expect(check!.status).toBe('fail');
+ expect(check!.message).toContain('dutch');
+ expect(check!.message).toContain('GBRAIN_FTS_LANGUAGE=dutch gbrain reindex-search-vector --yes');
+ });
+
+ test('marker absent → null (nothing pushed)', async () => {
+ expect(await ftsReindexIncompleteCheck(engineWith({}))).toBeNull();
+ });
+});
diff --git a/test/doctor-image-assets-remote.test.ts b/test/doctor-image-assets-remote.test.ts
new file mode 100644
index 0000000000..c882e38300
--- /dev/null
+++ b/test/doctor-image-assets-remote.test.ts
@@ -0,0 +1,103 @@
+/**
+ * #4910 — doctor `image_assets`: files rows whose metadata stamps a non-git
+ * storage lane (`storage: 'supabase' | 's3' | 'local'`) hold bucket keys,
+ * not source-relative paths. Doctor must not stat them under the source root
+ * and report "missing from disk … restore from git"; it classifies them as
+ * storage-backend objects, points at the backend-aware `gbrain files verify`,
+ * and keeps detecting genuinely vanished local/git assets.
+ *
+ * Behavioral test through the master-existing `buildChecks` seam (mirrors
+ * test/doctor-image-assets-wsl.test.ts).
+ */
+import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { executeRawJsonb } from '../src/core/sql-query.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { buildChecks, type Check } from '../src/commands/doctor.ts';
+
+let engine: PGLiteEngine;
+let repoRoot: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ repoRoot = mkdtempSync(join(tmpdir(), 'gbrain-4910-'));
+ await engine.setConfig('sync.repo_path', repoRoot);
+});
+
+async function insertImage(storagePath: string, hash: string, metadata: Record<string, unknown> | null): Promise<void> {
+ if (metadata === null) {
+ await engine.executeRaw(
+ `INSERT INTO files (source_id, filename, storage_path, mime_type, content_hash)
+ VALUES ('default', 'img.png', $1, 'image/png', $2)`,
+ [storagePath, hash],
+ );
+ return;
+ }
+ await executeRawJsonb(
+ engine,
+ `INSERT INTO files (source_id, filename, storage_path, mime_type, content_hash, metadata)
+ VALUES ('default', 'img.png', $1, 'image/png', $2, $3::jsonb)`,
+ [storagePath, hash],
+ [metadata],
+ );
+}
+
+async function imageAssetsCheck(): Promise<Check> {
+ const checks = await buildChecks(engine, []);
+ const check = checks.find((c) => c.name === 'image_assets');
+ expect(check).toBeDefined();
+ return check!;
+}
+
+describe('doctor image_assets — storage-backend objects (#4910)', () => {
+ test('a supabase-lane object key is not reported missing from disk', async () => {
+ await insertImage('cloud/example.png', 'h1', { storage: 'supabase' });
+ const check = await imageAssetsCheck();
+ expect(check.status).toBe('ok');
+ expect(check.message).not.toMatch(/missing from disk/);
+ expect(check.message).not.toContain('restore from git');
+ expect(check.message).toContain('files verify');
+ });
+
+ test('only storage-backend objects: says so instead of "0 image(s) all present"', async () => {
+ await insertImage('cloud/a.png', 'h2', { storage: 's3' });
+ await insertImage('cloud/b.png', 'h3', { storage: 'local' });
+ const check = await imageAssetsCheck();
+ expect(check.status).toBe('ok');
+ expect(check.message).not.toContain('all present on disk');
+ expect(check.message).toContain('2 storage-backend object(s)');
+ });
+
+ test('backend objects are excluded from the denominator; a vanished unmarked asset still warns', async () => {
+ await insertImage('cloud/example.png', 'h4', { storage: 'supabase' });
+ await insertImage('images/gone.jpg', 'h5', null);
+ const check = await imageAssetsCheck();
+ expect(check.status).toBe('warn');
+ expect(check.message).toMatch(/1 of 1 image\(s\) missing/);
+ expect(check.message).toContain('images/gone.jpg');
+ expect(check.message).toContain('1 storage-backend object(s)');
+ });
+
+ test('an explicit git-lane row is a local asset and is still checked (regression guard)', async () => {
+ await insertImage('assets/tracked-gone.png', 'h6', { storage: 'git' });
+ writeFileSync(join(repoRoot, 'here.png'), 'x');
+ await insertImage('here.png', 'h7', { storage: 'git' });
+ const check = await imageAssetsCheck();
+ expect(check.status).toBe('warn');
+ expect(check.message).toMatch(/1 of 2 image\(s\) missing/);
+ expect(check.message).toContain('assets/tracked-gone.png');
+ });
+});
diff --git a/test/doctor-report-remote.serial.test.ts b/test/doctor-report-remote.serial.test.ts
index a456c87b1d..c157b37e57 100644
--- a/test/doctor-report-remote.serial.test.ts
+++ b/test/doctor-report-remote.serial.test.ts
@@ -183,6 +183,22 @@ describe('doctorReportRemote — source scope (#4592)', () => {
expect(message(after, 'brain_score')).toBe(message(before, 'brain_score'));
});
+ test('contextual_retrieval_coverage counts only the granted source (#5004 unsealed pages, #4592 class)', async () => {
+ // putPage caps chunker_version below the safe-chunk fence, so every page
+ // here is "unsealed" and the check reports a count. A caller granted only
+ // SRCA must read SRCA's count: adding an unsealed page to SRCB moves nothing.
+ const ctx = {
+ engine,
+ remote: true,
+ auth: { token: 't', clientId: 'c', scopes: ['admin'], allowedSources: [SRCA] },
+ } as unknown as OperationContext;
+ const before = await operationsByName.run_doctor.handler(ctx, {}) as DoctorReport;
+ expect(message(before, 'contextual_retrieval_coverage')).toContain('below the safe-chunk index version');
+ await put(SRCB, 'notes/epsilon');
+ const after = await operationsByName.run_doctor.handler(ctx, {}) as DoctorReport;
+ expect(message(after, 'contextual_retrieval_coverage')).toBe(message(before, 'contextual_retrieval_coverage'));
+ });
+
test('extract_atoms_backlog / drift / orphan probes never name or count an excluded source (wave review)', async () => {
// 12 eligible-but-unextracted pages in the EXCLUDED source: brain-wide the
// backlog is >= 12 (and the drain hint may name the source); a caller
diff --git a/test/doctor-source-config-shape.test.ts b/test/doctor-source-config-shape.test.ts
index 57fd599f4e..52bf602602 100644
--- a/test/doctor-source-config-shape.test.ts
+++ b/test/doctor-source-config-shape.test.ts
@@ -41,6 +41,12 @@ describe('checkSourceConfigShape (#2829)', () => {
expect(result.message).toContain('UPDATE sources SET config');
expect(result.message).toContain('jsonb_array_elements');
expect(result.message).toContain('IS JSON');
+ // #5002: name commands that actually rewrite the config column — never the
+ // "any 'gbrain sources' config write" category (set-cr-mode writes another
+ // column and leaves the check red).
+ expect(result.message).toContain("gbrain sources federate <id>");
+ expect(result.message).toContain('set-cr-mode');
+ expect(result.message).not.toMatch(/any 'gbrain sources' config write/);
});
test('detection query targets the exact jsonb_typeof predicate', async () => {
diff --git a/test/doctor.test.ts b/test/doctor.test.ts
index 6ae40cf3d8..85b2b2e110 100644
--- a/test/doctor.test.ts
+++ b/test/doctor.test.ts
@@ -376,6 +376,8 @@ describe('doctor command', () => {
const source = doctorSource();
expect(source).toContain('jsonb_integrity');
expect(source).toContain('markdown_body_completeness');
+ // 0.48.5.1: the truncated-page hint must not name a flag `gbrain sync` does not have.
+ expect(source).not.toContain('gbrain sync --force');
expect(source).toContain('gbrain repair-jsonb');
});
diff --git a/test/e2e/brainstorm-resume.test.ts b/test/e2e/brainstorm-resume.test.ts
index a1719b09af..308e1a620d 100644
--- a/test/e2e/brainstorm-resume.test.ts
+++ b/test/e2e/brainstorm-resume.test.ts
@@ -33,6 +33,8 @@ import {
loadCheckpoint,
} from '../../src/core/brainstorm/checkpoint.ts';
import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';
+import { persistSavedIdea } from '../../src/commands/brainstorm.ts';
+import { serializeMarkdown } from '../../src/core/markdown.ts';
let engine: PGLiteEngine;
let tmp: string;
@@ -117,7 +119,7 @@ afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
-function makeChatFnMixed(failOnCrossCallN: number) {
+function makeChatFnMixed(failOnCrossCallN: number, judgeOpts: { garbage?: boolean } = {}) {
let crossCalls = 0;
let judgeCalls = 0;
const fn = async (opts: ChatOpts): Promise<ChatResult> => {
@@ -129,6 +131,18 @@ function makeChatFnMixed(failOnCrossCallN: number) {
const isJudge = /\(close=.* × far=.*\)/.test(content);
if (isJudge) {
judgeCalls++;
+ if (judgeOpts.garbage) {
+ // #4766: a single malformed judge response (parseJudgeJSON throws).
+ const text = 'not json at all';
+ return {
+ text,
+ blocks: [{ type: 'text', text }],
+ stopReason: 'end',
+ model: 'claude-sonnet-4-6',
+ providerId: 'fake',
+ usage: { input_tokens: 200, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ };
+ }
const ideaIds = Array.from(content.matchAll(/## Idea (\S+)/g)).map((m) => m[1] as string);
const json = {
ideas: ideaIds.map((id) => ({
@@ -323,3 +337,141 @@ describe('brainstorm --max-cost pre-flight refusal (F2 smoke)', () => {
expect(chat.judgeCalls).toBe(0);
});
});
+
+// #4766: a judge failure must NOT destroy the paid cross results, and the
+// remediation it prints must be a flag that exists. Pre-fix the cleanup
+// branch keyed on failed_crosses only, so all-crosses-green + judge-failed
+// marked judge_done and unlinked the checkpoint, while the advice named a
+// `--retry-judge` flag that no parser handled. `--resume <run_id>` already IS
+// the judge-only retry: completed crosses short-circuit from disk and Phase 4
+// always runs.
+describe('brainstorm judge failure keeps the checkpoint; --resume re-scores (#4766)', () => {
+ test('judge parse failure → checkpoint retained (judge_done=false, every cross on disk), stderr names --resume', async () => {
+ const chat = makeChatFnMixed(99999, { garbage: true });
+ const stderrChunks: string[] = [];
+ const result = await runBrainstorm(engine, {}, {
+ question: 'judge failure keeps checkpoint question',
+ profile: tinyProfile,
+ skipCostPreview: true,
+ maxCostUsd: 100,
+ chatFn: chat.fn,
+ embedQueryFn: async () => basisEmbedding(0),
+ stderrWrite: (s) => { stderrChunks.push(s); },
+ });
+ expect(result.judge_failed).toBe(true);
+ expect(chat.judgeCalls).toBeGreaterThanOrEqual(1);
+
+ const dir = join(tmp, '.gbrain', 'brainstorm');
+ const files = existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith('.json')) : [];
+ expect(files.length).toBe(1);
+ const runId = files[0].replace(/\.json$/, '');
+ const cp = loadCheckpoint(runId);
+ expect(cp).not.toBeNull();
+ expect(cp!.judge_done).toBe(false);
+ // k_close=2 × m_far=4 = 8 crosses, all paid for, all still on disk.
+ expect(cp!.completed_crosses.length).toBe(chat.crossCalls);
+ expect(cp!.failed_crosses.length).toBe(0);
+
+ const stderr = stderrChunks.join('');
+ expect(stderr).toContain(`--resume ${runId}`);
+ expect(stderr).not.toContain('--retry-judge');
+ });
+
+ test('second run with resumeRunId + healthy judge re-scores WITHOUT re-paying any cross', async () => {
+ const bad = makeChatFnMixed(99999, { garbage: true });
+ await runBrainstorm(engine, {}, {
+ question: 'judge failure then resume question',
+ profile: tinyProfile,
+ skipCostPreview: true,
+ maxCostUsd: 100,
+ chatFn: bad.fn,
+ embedQueryFn: async () => basisEmbedding(0),
+ stderrWrite: () => {},
+ });
+ const dir = join(tmp, '.gbrain', 'brainstorm');
+ const files = readdirSync(dir).filter((f) => f.endsWith('.json'));
+ expect(files.length).toBe(1);
+ const runId = files[0].replace(/\.json$/, '');
+
+ const good = makeChatFnMixed(99999);
+ const result = await runBrainstorm(engine, {}, {
+ question: 'judge failure then resume question',
+ profile: tinyProfile,
+ skipCostPreview: true,
+ maxCostUsd: 100,
+ chatFn: good.fn,
+ embedQueryFn: async () => basisEmbedding(0),
+ stderrWrite: () => {},
+ resumeRunId: runId,
+ });
+ expect(good.crossCalls).toBe(0);
+ expect(good.judgeCalls).toBe(1);
+ expect(result.judge_failed).toBe(false);
+ expect(result.ideas.length).toBe(8);
+ expect(result.ideas.every((i) => i.judge !== undefined)).toBe(true);
+ // Clean completion clears the checkpoint as before.
+ expect(readdirSync(dir).filter((f) => f.endsWith('.json')).length).toBe(0);
+ });
+
+ // Pre-landing review: the CLI's save slug carries a random nonce, so a
+ // `--resume` after a judge failure saved a SECOND idea page under a fresh
+ // slug (and the saved-page comment promised a re-score path that did not
+ // exist). The slug now rides in the checkpoint (`ideaSlug` in → `idea_slug`
+ // out) so the re-scored run overwrites the page the failed run saved.
+ test('resume returns the idea_slug the judge-failed run saved under, so exactly ONE idea page exists after re-score', async () => {
+ const question = 'judge failure slug question';
+ const pageFor = (slug: string) =>
+ serializeMarkdown({ mode: 'brainstorm', question, saved_as: slug }, `# Brainstorm: ${question}\n\nbody`, '', {
+ type: 'note',
+ title: `Brainstorm: ${question}`,
+ tags: [],
+ });
+ const firstSlug = 'wiki/ideas/2026-01-01-brainstorm-judge-failure-slug-question-aaaaaa';
+ const bad = makeChatFnMixed(99999, { garbage: true });
+ const first = await runBrainstorm(engine, {}, {
+ question,
+ profile: tinyProfile,
+ skipCostPreview: true,
+ maxCostUsd: 100,
+ chatFn: bad.fn,
+ embedQueryFn: async () => basisEmbedding(0),
+ stderrWrite: () => {},
+ ideaSlug: firstSlug,
+ });
+ expect(first.judge_failed).toBe(true);
+ expect(first.idea_slug).toBe(firstSlug);
+ const dir = join(tmp, '.gbrain', 'brainstorm');
+ const runId = readdirSync(dir).filter((f) => f.endsWith('.json'))[0]!.replace(/\.json$/, '');
+ expect(loadCheckpoint(runId)?.idea_slug).toBe(firstSlug);
+
+ // The CLI mints a fresh (random-nonce, next-day) slug on every invocation;
+ // the checkpoint's slug must win over it.
+ const secondSlug = 'wiki/ideas/2026-01-02-brainstorm-judge-failure-slug-question-bbbbbb';
+ const good = makeChatFnMixed(99999);
+ const second = await runBrainstorm(engine, {}, {
+ question,
+ profile: tinyProfile,
+ skipCostPreview: true,
+ maxCostUsd: 100,
+ chatFn: good.fn,
+ embedQueryFn: async () => basisEmbedding(0),
+ stderrWrite: () => {},
+ resumeRunId: runId,
+ ideaSlug: secondSlug,
+ });
+ expect(second.judge_failed).toBe(false);
+ expect(second.idea_slug).toBe(firstSlug);
+
+ // What the CLI does with each result: save it under `result.idea_slug ??
+ // <fresh slug>`. Both saves run after the two brainstorms so the saved
+ // page does not join the close/far candidate pool and shift the run_id.
+ await persistSavedIdea(engine, { slug: first.idea_slug ?? firstSlug, content: pageFor(firstSlug), provenanceVia: 'brainstorm' });
+ await persistSavedIdea(engine, { slug: second.idea_slug ?? secondSlug, content: pageFor(secondSlug), provenanceVia: 'brainstorm' });
+ try {
+ const ideaPages = (await engine.listPages()).filter((p) => p.slug.startsWith('wiki/ideas/'));
+ expect(ideaPages.map((p) => p.slug)).toEqual([firstSlug]);
+ } finally {
+ for (const slug of [firstSlug, secondSlug]) await engine.deletePage(slug).catch(() => {});
+ }
+ });
+});
diff --git a/test/e2e/code-intel-mcp-ops-pglite.test.ts b/test/e2e/code-intel-mcp-ops-pglite.test.ts
index 1f2fceef81..1679a08b22 100644
--- a/test/e2e/code-intel-mcp-ops-pglite.test.ts
+++ b/test/e2e/code-intel-mcp-ops-pglite.test.ts
@@ -111,6 +111,29 @@ describe('v0.34 W3 — code_callers / code_callees route to the engine', () => {
const toNames = result.callees.map((c) => c.to_symbol_qualified);
expect(toNames).toContain('parseMarkdown');
});
+
+ // #4670: the op promises "bare or qualified name". Nested chunks (C# namespace
+ // + class, TS class methods, ...) carry a QUALIFIED from_symbol_qualified, so
+ // the bare method name used to return count 0 while the qualified form and
+ // code_callers on the bare callee both worked.
+ test('code_callees honors the documented bare-name contract for a qualified chunk (#4670)', async () => {
+ await seedQualifiedMethodGraph(engine);
+ const ctx = makeCtx(engine, 'source-a');
+ const op = operationsByName.code_callees!;
+ const bare = (await op.handler(ctx, { symbol: 'SubmitAsync' })) as {
+ count: number;
+ callees: Array<{ from_symbol_qualified: string; to_symbol_qualified: string }>;
+ };
+ expect(bare.count).toBe(1);
+ expect(bare.callees[0]!.from_symbol_qualified).toBe('MyApp.Services.OrderService.SubmitAsync');
+ expect(bare.callees[0]!.to_symbol_qualified).toBe('ValidateRequest');
+ // Qualified input is unchanged.
+ const qualified = (await op.handler(ctx, { symbol: 'MyApp.Services.OrderService.SubmitAsync' })) as { count: number };
+ expect(qualified.count).toBe(1);
+ // No substring leakage.
+ const partial = (await op.handler(ctx, { symbol: 'Async' })) as { count: number };
+ expect(partial.count).toBe(0);
+ });
});
describe('v0.34 W3 — code_callers source scoping', () => {
@@ -261,6 +284,20 @@ async function seedTwoFileGraph(engine: PGLiteEngine): Promise<void> {
await insertUnresolvedEdge(engine, callerChunk, 'callerInA', 'parseMarkdown', 'source-a');
}
+// #4670: one C#-shaped chunk whose identity is namespace-qualified while its
+// only call edge is emitted bare (edge-extractor keeps the trailing identifier).
+async function seedQualifiedMethodGraph(engine: PGLiteEngine): Promise<void> {
+ await registerSource(engine, 'source-a');
+ const page = await insertCodePage(engine, 'source-a', 'src/Services/OrderService.cs');
+ const rows = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, language, symbol_name, symbol_name_qualified, symbol_type)
+ VALUES ($1, 0, 'public async Task SubmitAsync() { ValidateRequest(); }', 'compiled_truth', 'c_sharp', 'SubmitAsync', 'MyApp.Services.OrderService.SubmitAsync', 'method')
+ RETURNING id`,
+ [page],
+ );
+ await insertUnresolvedEdge(engine, rows[0]!.id, 'MyApp.Services.OrderService.SubmitAsync', 'ValidateRequest', 'source-a');
+}
+
async function seedCrossSourceGraph(engine: PGLiteEngine): Promise<void> {
await registerSource(engine, 'source-a');
await registerSource(engine, 'source-b');
diff --git a/test/e2e/engine-parity-salience.test.ts b/test/e2e/engine-parity-salience.test.ts
index 95e888c64b..fe7927b2e6 100644
--- a/test/e2e/engine-parity-salience.test.ts
+++ b/test/e2e/engine-parity-salience.test.ts
@@ -95,12 +95,13 @@ describeBoth('v0.29 engine parity — getRecentSalience', () => {
// Pinned engine shapes (src/core/{pglite,postgres}-engine/salience.ts +
// the getSalienceScores methods on both engine classes):
// - setEmotionalWeightBatch(rows: {slug, source_id, weight}[]) → number of
-// MATCHED pages (composite (slug, source_id) join against unnest;
-// RETURNING 1 counts a match even when the weight value is unchanged;
-// rows whose (slug, source_id) matches no page are silently dropped).
-// - salience_touched_at = now() ONLY on the
-// `pages.emotional_weight IS DISTINCT FROM u.weight` branch; a same-value
-// write leaves the old timestamp untouched.
+// CHANGED pages (composite (slug, source_id) join against unnest filtered
+// by `pages.emotional_weight IS DISTINCT FROM u.weight`; a same-value row
+// is NOT rewritten — no new tuple version, no BEFORE UPDATE trigger
+// fan-out (#4797) — and is not counted; rows whose (slug, source_id)
+// matches no page are silently dropped).
+// - salience_touched_at = now() on every rewritten row (only changed rows
+// are rewritten); a same-value write leaves the old timestamp untouched.
// - getSalienceScores(refs: {slug, source_id}[]) → Map keyed
// `${source_id}::${slug}`, score = COALESCE(emotional_weight,0)*5
// + ln(1 + COUNT(DISTINCT active takes)); unmatched refs are absent.
@@ -122,6 +123,16 @@ interface D5Snapshot {
before: Map<string, number>; // slug → EXTRACT(EPOCH FROM salience_touched_at)
after: Map<string, number>;
weights: Map<string, number>; // slug → stored emotional_weight
+ xminBefore: Map<string, string>; // slug → xmin::text before the mixed batch
+ xminAfter: Map<string, string>;
+}
+
+async function readXmins(engine: BrainEngine): Promise<Map<string, string>> {
+ const rows = await engine.executeRaw<{ slug: string; row_xmin: string | number }>(
+ `SELECT slug, xmin::text AS row_xmin
+ FROM pages WHERE slug LIKE 'salience/batch-%'`
+ );
+ return new Map(rows.map(r => [String(r.slug), String(r.row_xmin)]));
}
async function readTouchedEpochs(engine: BrainEngine): Promise<Map<string, number>> {
@@ -168,6 +179,7 @@ async function runD5Fixture(engine: BrainEngine): Promise<D5Snapshot> {
WHERE slug LIKE 'salience/batch-%'`
);
const before = await readTouchedEpochs(engine);
+ const xminBefore = await readXmins(engine);
// The MIXED batch: one changing row, two same-value rows, one row changing
// from the column default, one missing slug, one wrong-source ref.
@@ -180,8 +192,9 @@ async function runD5Fixture(engine: BrainEngine): Promise<D5Snapshot> {
{ slug: 'salience/batch-changed', source_id: 'no-such-source', weight: 0.99 },
]);
const after = await readTouchedEpochs(engine);
+ const xminAfter = await readXmins(engine);
const weights = await readStoredWeights(engine);
- return { firstCount, mixedCount, before, after, weights };
+ return { firstCount, mixedCount, before, after, weights, xminBefore, xminAfter };
}
describeBoth('D5 engine parity — setEmotionalWeightBatch + getSalienceScores', () => {
@@ -205,14 +218,26 @@ describeBoth('D5 engine parity — setEmotionalWeightBatch + getSalienceScores',
await teardownDB();
});
- test('mixed batch: identical matched-row counts on both engines', () => {
- // First write matched all 3 existing targets.
+ test('mixed batch: identical changed-row counts on both engines', () => {
+ // First write changed all 3 existing targets (0.0 default → new value).
expect(pgliteSnap.firstCount).toBe(3);
expect(postgresSnap.firstCount).toBe(3);
- // Mixed batch: 4 matched pages (same-value writes still match + count);
- // the missing slug and the wrong-source ref match nothing.
- expect(pgliteSnap.mixedCount).toBe(4);
- expect(postgresSnap.mixedCount).toBe(4);
+ // Mixed batch: 2 CHANGED pages (batch-changed + batch-fresh); the two
+ // same-value rows are filtered out before the write (#4797); the missing
+ // slug and the wrong-source ref match nothing.
+ expect(pgliteSnap.mixedCount).toBe(2);
+ expect(postgresSnap.mixedCount).toBe(2);
+ });
+
+ test('mixed batch: same-value rows are not rewritten on either engine (#4797)', () => {
+ for (const snap of [pgliteSnap, postgresSnap]) {
+ // No new tuple version → the per-row BEFORE UPDATE triggers never fired.
+ expect(snap.xminAfter.get('salience/batch-same')).toBe(snap.xminBefore.get('salience/batch-same')!);
+ expect(snap.xminAfter.get('salience/batch-same-2')).toBe(snap.xminBefore.get('salience/batch-same-2')!);
+ // The changed rows were rewritten.
+ expect(snap.xminAfter.get('salience/batch-changed')).not.toBe(snap.xminBefore.get('salience/batch-changed')!);
+ expect(snap.xminAfter.get('salience/batch-fresh')).not.toBe(snap.xminBefore.get('salience/batch-fresh')!);
+ }
});
test('mixed batch: identical stored weights on both engines', () => {
diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.ts
index b19e843962..3661433e12 100644
--- a/test/e2e/engine-parity.test.ts
+++ b/test/e2e/engine-parity.test.ts
@@ -639,6 +639,7 @@ describeBoth('Engine parity — Postgres vs PGLite', () => {
source_kind: 'capture-cli',
source_uri: 'file:///tmp/parity.md',
ingested_via: 'put_page',
+ source_path: 'wiki/provenance-parity.md',
};
await pgEngine.putPage(slug, input);
await pgliteEngine.putPage(slug, input);
@@ -649,6 +650,11 @@ describeBoth('Engine parity — Postgres vs PGLite', () => {
expect(pgPage).not.toBeNull();
expect(pglitePage).not.toBeNull();
+ // getPage projects source_path on both engines (the import skip path
+ // compares it before issuing the #4588 refresh UPDATE).
+ expect(pgPage!.source_path).toBe('wiki/provenance-parity.md');
+ expect(pglitePage!.source_path).toBe('wiki/provenance-parity.md');
+
// All 4 provenance fields must match across engines.
expect(pgPage!.source_kind).toBe('capture-cli');
expect(pglitePage!.source_kind).toBe('capture-cli');
@@ -2458,3 +2464,58 @@ describeBoth('Engine parity — facts TTL read-time validity (WP5)', () => {
expect(pg.backlog).toBe(4);
});
});
+
+// #4670 — getCalleesOf `bareFallback` must behave identically on both engines:
+// exact match first; on a zero-row miss for a delimiter-free input, re-key on
+// content_chunks.symbol_name (bare); never for delimited inputs; source scoping
+// intact on the fallback path.
+describeBoth('Engine parity — getCalleesOf bare-name fallback (#4670)', () => {
+ let pgEngine: BrainEngine;
+ let pgliteEngine: PGLiteEngine;
+
+ beforeAll(async () => {
+ pgEngine = await setupDB();
+ pgliteEngine = new PGLiteEngine();
+ await pgliteEngine.connect({});
+ await pgliteEngine.initSchema();
+ for (const eng of [pgEngine, pgliteEngine]) {
+ const slug = 'parity/order-service-cs';
+ await eng.putPage(slug, {
+ type: 'code', page_kind: 'code', title: 'src/OrderService.cs (c_sharp)',
+ compiled_truth: 'public async Task SubmitAsync() { ValidateRequest(); }', timeline: '',
+ });
+ await eng.upsertChunks(slug, [{
+ chunk_index: 0,
+ chunk_text: 'public async Task SubmitAsync() { ValidateRequest(); }',
+ chunk_source: 'compiled_truth',
+ language: 'c_sharp',
+ symbol_name: 'SubmitAsync',
+ symbol_type: 'method',
+ symbol_name_qualified: 'MyApp.Services.OrderService.SubmitAsync',
+ }]);
+ const chunk = (await eng.getChunks(slug))[0]!;
+ await eng.addCodeEdges([{
+ from_chunk_id: chunk.id, to_chunk_id: null,
+ from_symbol_qualified: 'MyApp.Services.OrderService.SubmitAsync',
+ to_symbol_qualified: 'ValidateRequest', edge_type: 'calls',
+ }]);
+ }
+ }, 90_000);
+
+ afterAll(async () => {
+ await pgliteEngine.disconnect();
+ await teardownDB();
+ }, 30_000);
+
+ test('bare input: exact miss without the opt, one row with it; qualified + delimited unchanged', async () => {
+ for (const eng of [pgEngine, pgliteEngine]) {
+ expect(await eng.getCalleesOf('SubmitAsync', { allSources: true })).toHaveLength(0);
+ const rows = await eng.getCalleesOf('SubmitAsync', { allSources: true, bareFallback: true });
+ expect(rows.map(r => r.to_symbol_qualified)).toEqual(['ValidateRequest']);
+ expect(await eng.getCalleesOf('MyApp.Services.OrderService.SubmitAsync', { allSources: true, bareFallback: true })).toHaveLength(1);
+ expect(await eng.getCalleesOf('Other.SubmitAsync', { allSources: true, bareFallback: true })).toHaveLength(0);
+ expect(await eng.getCalleesOf('Submit_sync', { allSources: true, bareFallback: true })).toHaveLength(0);
+ expect(await eng.getCalleesOf('SubmitAsync', { sourceId: 'not-a-source', bareFallback: true })).toHaveLength(0);
+ }
+ });
+});
diff --git a/test/e2e/legacy-chunk-privacy.test.ts b/test/e2e/legacy-chunk-privacy.test.ts
index 27975f2e06..941891f0a2 100644
--- a/test/e2e/legacy-chunk-privacy.test.ts
+++ b/test/e2e/legacy-chunk-privacy.test.ts
@@ -11,6 +11,7 @@ import { readPolicyOpts } from '../../src/core/ops/context.ts';
import { importFromContent } from '../../src/core/import-file.ts';
import { serializeMarkdown } from '../../src/core/markdown.ts';
import { runReindex } from '../../src/commands/reindex.ts';
+import { buildEmptyRetrievalBlock } from '../../src/mcp/dispatch.ts';
import { MARKDOWN_CHUNKER_VERSION } from '../../src/core/chunkers/recursive.ts';
import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, renderFactsTable } from '../../src/core/facts-fence.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../../src/core/takes-fence.ts';
@@ -73,10 +74,15 @@ for (const kind of ['pglite', 'postgres'] as const) {
resetGateway();
}, 60_000);
+ // Response-meta side channel captured per call (the `retrieval` block MCP reads).
+ let meta: Record<string, unknown> = {};
+ const degradedStages = () => ((meta.retrieval as { degraded?: Array<{ stage: string }> } | undefined)?.degraded ?? []).map(d => d.stage);
+
function context(remote: boolean | undefined, sourceId = A, allowedSources?: string[]): OperationContext {
return {
engine, config: { engine: 'pglite' }, dryRun: false, remote: remote as boolean, sourceId,
logger: { info: () => {}, warn: () => {}, error: () => {} },
+ emitResponseMeta: (key: string, value: unknown) => { meta[key] = value; },
...(allowedSources !== undefined ? { auth: {
token: 'fixture', clientId: 'chunk-reader-example', scopes: ['read'], allowedSources,
} } : {}),
@@ -205,6 +211,31 @@ for (const kind of ['pglite', 'postgres'] as const) {
expect((await engine.searchVector(vector, { sourceId: A, limit: 1 }))[0].page_id).toBe(unsafe);
}, 60_000);
+ test('a remote read emptied by the safe-chunk fence reports safe_index_pending, never a clean miss (#5004)', async () => {
+ // Only unsealed (pre-fence) pages match QUERY in source A; B holds one sealed page.
+ await legacy('notes/legacy-only', A, `${QUERY} OLD_PUBLIC_CHUNK`, `${QUERY} OLD_PUBLIC_CHUNK`);
+ await safe('notes/current-clean-b', B, 'Sealed page without the marker.');
+ for (const keywordOnly of ['true', 'false']) {
+ await engine.setConfig('search.mcp_keyword_only', keywordOnly);
+ for (const name of ['search', 'query']) {
+ meta = {};
+ expect(await call(context(true), name, { query: QUERY, expand: false, limit: 5 })).toEqual([]);
+ expect(degradedStages()).toContain('safe_index_pending');
+ const block = buildEmptyRetrievalBlock(meta.retrieval) ?? '';
+ expect(block).toContain('safe_index_pending');
+ expect(block).not.toContain('clean miss');
+ // Trusted local reads still see the legacy page and carry no stamp.
+ meta = {};
+ expect((await call(context(false), name, { query: QUERY, expand: false, limit: 5 }) as SearchResult[]).length).toBeGreaterThan(0);
+ expect(degradedStages()).not.toContain('safe_index_pending');
+ // A scope holding only sealed pages is a genuine miss: the probe is source-scoped.
+ meta = {};
+ expect(await call(context(true, FOREIGN, [B]), name, { query: 'nosuchtokenanywhere', expand: false, limit: 5 })).toEqual([]);
+ expect(degradedStages()).not.toContain('safe_index_pending');
+ }
+ }
+ }, 60_000);
+
test('direct page rewrites cannot bless unsafe chunks even after protected markers are removed', async () => {
const slug = 'notes/rewrite-cannot-bless';
const id = await legacy(slug, A, `Original public context.\n${takes(PRIVATE)}`, `${QUERY} ${PRIVATE}`);
diff --git a/test/e2e/link-source-check-repair-postgres.test.ts b/test/e2e/link-source-check-repair-postgres.test.ts
new file mode 100644
index 0000000000..1015f51aeb
--- /dev/null
+++ b/test/e2e/link-source-check-repair-postgres.test.ts
@@ -0,0 +1,131 @@
+/**
+ * Postgres-only pin for the links_link_source_check self-heal's DDL shape (#4613).
+ *
+ * On real Postgres a plain `ADD CONSTRAINT ... CHECK` takes ACCESS EXCLUSIVE
+ * plus a full validation scan on `links`. The repair must use migration
+ * v114's two-phase form — DROP + `ADD ... NOT VALID` in one transaction, then
+ * `VALIDATE CONSTRAINT` as a separate statement outside it — validate-only
+ * when the definition is right but NOT VALID, and never attempt DDL while
+ * violating rows exist. PGLite cannot observe lock semantics (and keeps the
+ * one-shot form), so this is DATABASE_URL-gated per the engine-parity
+ * convention.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { setupDB, teardownDB, hasDatabase } from './helpers.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import {
+ LINK_SOURCE_KEBAB_RE,
+ checkLinkSourceCheck,
+ repairLinkSourceCheck,
+} from '../../src/core/link-source-check-repair.ts';
+import { recordingEngine } from '../helpers/recording-engine.ts';
+
+const skip = !hasDatabase();
+const describeIfDB = skip ? describe.skip : describe;
+
+let engine: PostgresEngine;
+
+const KEBAB_CHECK =
+ `CHECK (link_source IS NULL OR (link_source ~ '${LINK_SOURCE_KEBAB_RE}' AND char_length(link_source) <= 64))`;
+
+const ddlCalls = (calls: string[]) => calls.filter(c => /^(transaction:|runMigration:)/.test(c));
+
+async function dropConstraint(): Promise<void> {
+ await engine.executeRaw(`ALTER TABLE links DROP CONSTRAINT IF EXISTS links_link_source_check`);
+}
+
+async function constraintRow(): Promise<{ def: string; convalidated: boolean } | undefined> {
+ const rows = await engine.executeRaw<{ def: string; convalidated: boolean }>(
+ `SELECT pg_get_constraintdef(oid) AS def, convalidated FROM pg_constraint
+ WHERE conrelid = to_regclass('links') AND conname = 'links_link_source_check'`,
+ );
+ return rows[0];
+}
+
+beforeAll(async () => {
+ if (skip) return;
+ engine = await setupDB();
+ for (const slug of ['notes/alpha-example', 'notes/beta-example']) {
+ await engine.putPage(slug, {
+ title: slug, type: 'concept', frontmatter: {}, compiled_truth: `body ${slug}`, timeline: '',
+ });
+ }
+});
+
+afterAll(async () => {
+ if (skip) return;
+ await teardownDB();
+});
+
+beforeEach(async () => {
+ if (skip) return;
+ await engine.executeRaw(`DELETE FROM links`);
+ await repairLinkSourceCheck(engine); // restore the canonical gate before each case
+});
+
+describeIfDB('repairLinkSourceCheck on Postgres (#4613)', () => {
+ test('wrong_def: DROP + ADD ... NOT VALID in one transaction, VALIDATE CONSTRAINT outside it', async () => {
+ await dropConstraint();
+ await engine.executeRaw(
+ `ALTER TABLE links ADD CONSTRAINT links_link_source_check CHECK (link_source IS NULL OR link_source IN ('markdown'))`,
+ );
+ expect((await checkLinkSourceCheck(engine)).drift).toBe('wrong_def');
+
+ const rec = recordingEngine(engine);
+ const r = await repairLinkSourceCheck(rec.engine);
+ expect(r.reason).toBe('restored');
+
+ const ddl = ddlCalls(rec.calls);
+ expect(ddl.length).toBe(3);
+ expect(ddl[0]).toBe('transaction:');
+ expect(ddl[1]).toMatch(/^runMigration:ALTER TABLE links DROP CONSTRAINT IF EXISTS links_link_source_check; ALTER TABLE links ADD CONSTRAINT links_link_source_check CHECK .* NOT VALID;$/);
+ expect(ddl[1]).not.toContain('VALIDATE');
+ expect(ddl[2]).toBe('runMigration:ALTER TABLE links VALIDATE CONSTRAINT links_link_source_check');
+
+ const row = await constraintRow();
+ expect(row?.def).toContain(LINK_SOURCE_KEBAB_RE);
+ expect(row?.convalidated).toBe(true);
+ });
+
+ test('absent: same two-phase form, ends validated', async () => {
+ await dropConstraint();
+ const rec = recordingEngine(engine);
+ const r = await repairLinkSourceCheck(rec.engine);
+ expect(r.reason).toBe('restored');
+ const ddl = ddlCalls(rec.calls);
+ expect(ddl[0]).toBe('transaction:');
+ expect(ddl[1]).toContain('NOT VALID');
+ expect(ddl[2]).toContain('VALIDATE CONSTRAINT');
+ expect((await constraintRow())?.convalidated).toBe(true);
+ });
+
+ test('not_validated: VALIDATE CONSTRAINT only — no DROP, no transaction', async () => {
+ await dropConstraint();
+ await engine.executeRaw(`ALTER TABLE links ADD CONSTRAINT links_link_source_check ${KEBAB_CHECK} NOT VALID`);
+ expect((await checkLinkSourceCheck(engine)).drift).toBe('not_validated');
+
+ const rec = recordingEngine(engine);
+ const r = await repairLinkSourceCheck(rec.engine);
+ expect(r.reason).toBe('restored');
+ expect(ddlCalls(rec.calls)).toEqual(['runMigration:ALTER TABLE links VALIDATE CONSTRAINT links_link_source_check']);
+ expect((await constraintRow())?.convalidated).toBe(true);
+ });
+
+ test('violating rows: reported, no DDL attempted, prior constraint untouched', async () => {
+ await dropConstraint();
+ await engine.executeRaw(
+ `ALTER TABLE links ADD CONSTRAINT links_link_source_check CHECK (link_source IS NULL OR link_source IN ('markdown', 'BAD_TAG'))`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source)
+ SELECT a.id, b.id, '', '', 'BAD_TAG' FROM pages a, pages b
+ WHERE a.slug = 'notes/alpha-example' AND b.slug = 'notes/beta-example'`,
+ );
+ const rec = recordingEngine(engine);
+ const r = await repairLinkSourceCheck(rec.engine);
+ expect(r).toEqual({ repaired: false, violations: 1, reason: 'violations' });
+ expect(ddlCalls(rec.calls)).toEqual([]);
+ expect(rec.calls.some(c => c.includes('ALTER TABLE'))).toBe(false);
+ expect((await constraintRow())?.def).toContain('BAD_TAG');
+ });
+});
diff --git a/test/e2e/multi-source-emotional-weight-pglite.test.ts b/test/e2e/multi-source-emotional-weight-pglite.test.ts
index bf7de83660..ddc001382c 100644
--- a/test/e2e/multi-source-emotional-weight-pglite.test.ts
+++ b/test/e2e/multi-source-emotional-weight-pglite.test.ts
@@ -88,6 +88,25 @@ describe('v0.29 E2E — setEmotionalWeightBatch is multi-source safe', () => {
expect(updated).toBe(1);
});
+ // #4797: a first full-brain pass recomputes almost every page to the value
+ // already stored (0.0 default). Rewriting those rows fires the per-row
+ // BEFORE UPDATE triggers (generation bump + search_vector) for nothing.
+ // Same-value rows must be left alone: not rewritten, not counted.
+ test('same-value rows are not rewritten and are not counted (#4797)', async () => {
+ const readXmin = () => engine.executeRaw<{ source_id: string; row_xmin: string }>(
+ `SELECT source_id, xmin::text AS row_xmin FROM pages WHERE slug = 'shared/page' ORDER BY source_id`
+ );
+ const before = Object.fromEntries((await readXmin()).map(r => [r.source_id, r.row_xmin]));
+ const updated = await engine.setEmotionalWeightBatch([
+ { slug: 'shared/page', source_id: 'default', weight: 0.50 }, // unchanged (set above)
+ { slug: 'shared/page', source_id: 'src-b', weight: 0.30 }, // 0.20 → 0.30
+ ]);
+ expect(updated).toBe(1);
+ const after = Object.fromEntries((await readXmin()).map(r => [r.source_id, r.row_xmin]));
+ expect(after.default).toBe(before.default); // no new tuple version
+ expect(after['src-b']).not.toBe(before['src-b']); // the changed row was rewritten
+ });
+
test('empty batch returns 0', async () => {
const updated = await engine.setEmotionalWeightBatch([]);
expect(updated).toBe(0);
diff --git a/test/e2e/phantom-redirect.test.ts b/test/e2e/phantom-redirect.test.ts
index 50f8fa98f6..d7a5489fd4 100644
--- a/test/e2e/phantom-redirect.test.ts
+++ b/test/e2e/phantom-redirect.test.ts
@@ -207,15 +207,22 @@ describeMaybe('phantom-redirect E2E (Postgres)', () => {
// through postgres-js's text representation per round 12).
// Build a 1536-d vector (canonical OpenAI embedding shape) of small
// values so we can verify the parse doesn't mangle.
+ // The row mirrors the fence row above cell-for-cell, visibility and
+ // notability included: since #4870 the reconcile compares those two
+ // cells too, so a seed left on the column defaults (private/medium)
+ // would read as a fence edit and take the wipe+reinsert path — which
+ // drops the embedding on a keyless run and defeats the pin below.
const vec = Array(1536).fill(0).map((_, i) => i / 1536).map((v) => v.toFixed(6)).join(',');
await engine.executeRaw(
`INSERT INTO facts (
source_id, entity_slug, fact, kind, valid_from,
source, source_markdown_slug, row_num,
+ visibility, notability,
embedding
) VALUES (
'default', 'alice', 'Founded Acme', 'fact', '2017-01-01'::date,
'linkedin', 'alice', 1,
+ 'world', 'high',
('[' || $1 || ']')::vector
)`,
[vec],
diff --git a/test/e2e/skillopt-loop.serial.test.ts b/test/e2e/skillopt-loop.serial.test.ts
index 72cf6ae425..8da89dad2a 100644
--- a/test/e2e/skillopt-loop.serial.test.ts
+++ b/test/e2e/skillopt-loop.serial.test.ts
@@ -43,6 +43,11 @@ import {
skillPath,
} from '../../src/core/skillopt/version-store.ts';
import { loadRejectedBuffer } from '../../src/core/skillopt/rejected-buffer.ts';
+import {
+ _resetAuditWriterForTests,
+ currentAuditFilename,
+ resolveAuditDir,
+} from '../../src/core/skillopt/audit.ts';
import type { EditOp } from '../../src/core/skillopt/types.ts';
let engine: PGLiteEngine;
@@ -441,13 +446,25 @@ describe('skillopt full-loop E2E (happy path + broken cases)', () => {
}
});
- test('broken: malformed reflect JSON (no edits parsed, no acceptance)', async () => {
+ test('broken: malformed reflect JSON (no edits parsed, no acceptance, zero-candidate step is SAID on stderr)', async () => {
// The optimizer returns syntactically broken JSON. The reflect module's
// forgiving parser yields zero valid edits; applyEditBatch sees an empty
- // batch; the orchestrator hits the "no_edits_applied" branch; the sel
+ // batch; the orchestrator hits the zero-candidate branch; the sel
// gate is never invoked. SKILL.md stays untouched. Critically: the run
// does NOT crash on malformed optimizer output (graceful degradation).
+ //
+ // #4741: a step where the optimizer proposed NOTHING must be
+ // distinguishable from "gated N candidates and rejected all" — both used
+ // to log reason 'no_edits_applied' and print nothing, so a whole run of
+ // zero candidates read as a real `no_improvement` measurement. Now the
+ // step says so on stderr and logs reason 'no_edits_proposed'.
const fixture = setupFixture(SKILL_PEOPLE_ONLY);
+ const stderrLines: string[] = [];
+ const realWrite = process.stderr.write.bind(process.stderr);
+ process.stderr.write = ((chunk: string | Uint8Array) => {
+ stderrLines.push(String(chunk));
+ return true;
+ }) as typeof process.stderr.write;
try {
installStub({
// Adversarial: looks like JSON but isn't. Different broken shapes
@@ -456,6 +473,7 @@ describe('skillopt full-loop E2E (happy path + broken cases)', () => {
});
try {
await withEnv({ GBRAIN_AUDIT_DIR: fixture.skillsDir }, async () => {
+ _resetAuditWriterForTests();
const result = await runOnce(fixture);
expect(result.outcome).toBe('no_improvement');
@@ -464,11 +482,23 @@ describe('skillopt full-loop E2E (happy path + broken cases)', () => {
.toBe(SKILL_PEOPLE_ONLY);
expect(loadHistory(fixture.skillsDir, SKILL).filter((r) => r.status === 'committed'))
.toHaveLength(0);
+
+ // #4741: the operator is told, per step, that no candidate existed.
+ expect(stderrLines.join('')).toMatch(/optimizer proposed no edits/);
+ // …and the audit step carries a reason distinct from apply-rejected.
+ const auditFile = path.join(resolveAuditDir(), currentAuditFilename());
+ const steps = fs.readFileSync(auditFile, 'utf8').trim().split('\n')
+ .map((l) => JSON.parse(l) as { kind: string; reason?: string })
+ .filter((e) => e.kind === 'step');
+ expect(steps.length).toBeGreaterThan(0);
+ for (const st of steps) expect(st.reason).toMatch(/^no_edits_proposed/);
});
} finally {
uninstallStub();
}
} finally {
+ process.stderr.write = realWrite;
+ _resetAuditWriterForTests();
fixture.cleanup();
}
});
diff --git a/test/e2e/transcripts-ingest-pglite.test.ts b/test/e2e/transcripts-ingest-pglite.test.ts
index 1bbac79957..bb9f676ec4 100644
--- a/test/e2e/transcripts-ingest-pglite.test.ts
+++ b/test/e2e/transcripts-ingest-pglite.test.ts
@@ -28,7 +28,7 @@ import { buildTranscriptSlug } from '../../src/core/transcripts/types.ts';
import { buildHermesFixture } from '../fixtures/transcripts/hermes-fixture-builder.ts';
const CODEX_SLUG = buildTranscriptSlug('codex', '2026-08-02T09:00:00.000Z', {
- sessionId: 'codex-fixture-session-1',
+ sessionId: 'rollout-1', // payload.id — the per-thread id (#4981)
});
const AGENT_SLUG = buildTranscriptSlug('openclaw', '2026-08-03T14:00:00.000Z', {
sessionId: 'agent-fixture-session-1',
diff --git a/test/embedding-pricing.test.ts b/test/embedding-pricing.test.ts
index 731ea9c12b..bdf044a2aa 100644
--- a/test/embedding-pricing.test.ts
+++ b/test/embedding-pricing.test.ts
@@ -48,6 +48,18 @@ describe('lookupEmbeddingPrice — first-class providers', () => {
expect(r.kind).toBe('known');
if (r.kind === 'known') expect(r.pricePerMTok).toBe(0.05);
});
+
+ test('Google gemini-embedding-001 at $0.15/MTok', () => {
+ const r = lookupEmbeddingPrice('google:gemini-embedding-001');
+ expect(r.kind).toBe('known');
+ if (r.kind === 'known') expect(r.pricePerMTok).toBe(0.15);
+ });
+
+ test('Google gemini-embedding-2 at $0.20/MTok (text rate, not shared with -001)', () => {
+ const r = lookupEmbeddingPrice('google:gemini-embedding-2');
+ expect(r.kind).toBe('known');
+ if (r.kind === 'known') expect(r.pricePerMTok).toBe(0.20);
+ });
});
describe('lookupEmbeddingPrice — fall-through behavior', () => {
@@ -114,6 +126,7 @@ describe('lookupEmbeddingPrice — nested gateway ids (#2504)', () => {
['openrouter:openai/text-embedding-3-large', 0.13, 'openai:text-embedding-3-large'],
['openrouter:voyage/voyage-4', 0.06, 'voyage:voyage-4'],
['openrouter:mistral/mistral-embed', 0.10, 'mistral:mistral-embed'],
+ ['openrouter:google/gemini-embedding-001', 0.15, 'google:gemini-embedding-001'],
])('%s falls back to the nested vendor row', (model, expected, key) => {
const r = lookupEmbeddingPrice(model as string);
expect(r.kind).toBe('known');
@@ -210,3 +223,19 @@ describe('#4344 — every hosted voyage recipe model has a pricing entry', () =>
if (r.kind === 'known') expect(r.pricePerMTok).toBe(expected);
});
});
+
+// Same coverage gate as #4344, for the `google` recipe: every embedding model
+// the recipe offers as HOSTED must have a pricing row, so the class (#4953 —
+// gemini-embedding-001 / gemini-embedding-2 shipped in the recipe with no
+// rows, every cost surface read "unavailable") cannot recur when Google ships
+// the next generation. Folded from #4989 (credit: dov-kela).
+describe('every hosted google recipe model has a pricing entry', () => {
+ test('recipe models ⊆ pricing table', async () => {
+ const { google } = await import('../src/core/ai/recipes/google.ts');
+ const models: string[] = (google as any).touchpoints.embedding.models;
+ expect(models).toContain('gemini-embedding-001');
+ expect(models).toContain('gemini-embedding-2');
+ const missing = models.filter((m) => lookupEmbeddingPrice(`google:${m}`).kind !== 'known');
+ expect(missing).toEqual([]);
+ });
+});
diff --git a/test/extract-atoms-drain.test.ts b/test/extract-atoms-drain.test.ts
index accc154595..28808a6948 100644
--- a/test/extract-atoms-drain.test.ts
+++ b/test/extract-atoms-drain.test.ts
@@ -205,6 +205,18 @@ describe('shared wiring helper holds the cycle lock (5A)', () => {
});
});
+// The register comment is the only place an operator learns how a PROTECTED
+// name gets submitted from the CLI. `jobs submit` sets allowProtectedSubmit
+// itself for protected names; there is no `--allow-protected` flag, and a
+// comment advertising one sends operators to a flag that exits "unknown".
+describe('protected-names register comment names the real trust mechanism', () => {
+ const src = readFileSync(join(import.meta.dir, '../src/core/minions/protected-names.ts'), 'utf8');
+ it('does not advertise the non-existent --allow-protected flag', () => {
+ expect(src).not.toContain('--allow-protected');
+ expect(src).toContain('allowProtectedSubmit');
+ });
+});
+
// issue #3218 — the Minion handler must throw (not complete) when the drain
// reports status='provider_failure', so the worker's ordinary failJob path
// (attempt+backoff / dead-letter) retries the durable job instead of the
diff --git a/test/extract-by-mention-resume.test.ts b/test/extract-by-mention-resume.test.ts
index cdbf9cc668..bb3a33b0c3 100644
--- a/test/extract-by-mention-resume.test.ts
+++ b/test/extract-by-mention-resume.test.ts
@@ -18,7 +18,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { runExtract } from '../src/commands/extract.ts';
import { setCliOptions } from '../src/core/cli-options.ts';
import { loadOpCheckpoint, mentionsFingerprint } from '../src/core/op-checkpoint.ts';
-import { createHash } from 'crypto';
+import { buildGazetteer, hashGazetteer } from '../src/core/by-mention.ts';
let engine: PGLiteEngine;
@@ -80,13 +80,9 @@ async function runByMention(args: string[]): Promise<void> {
}
}
-/** Compute the canonical gazetteer hash the way the production code does. */
+/** The production gazetteer hash (cross_source is off here, so no ':xs' suffix). */
async function expectedGazetteerHash(): Promise<string> {
- // The gazetteer is built from entity pages by buildGazetteer; for tests
- // we just build it the same way the prod code does and hash sorted keys.
- const { buildGazetteer } = await import('../src/core/by-mention.ts');
- const gz = await buildGazetteer(engine);
- return createHash('sha256').update([...gz.keys()].sort().join('|')).digest('hex').slice(0, 8);
+ return hashGazetteer(await buildGazetteer(engine));
}
describe('by-mention checkpoint/resume (T5)', () => {
@@ -150,14 +146,12 @@ describe('by-mention checkpoint/resume (T5)', () => {
await seedEntities();
await seedContentPage('writing/post-1', 'Acme Corp.');
await runByMention([]);
+ const oldHash = await expectedGazetteerHash();
// Now add a new entity. The gazetteer hash changes → different
// fingerprint → fresh checkpoint state (codex fix #3 regression guard).
await engine.putPage('people/charlie', { type: 'person', title: 'Charlie Example', compiled_truth: 'body', timeline: '', frontmatter: {} });
- const oldHash = createHash('sha256').update(
- ['acme corp', 'alice example'].sort().join('|'),
- ).digest('hex').slice(0, 8);
const newHash = await expectedGazetteerHash();
expect(newHash).not.toBe(oldHash);
@@ -166,6 +160,33 @@ describe('by-mention checkpoint/resume (T5)', () => {
expect(oldFp).not.toBe(newFp);
});
+ test('same-bucket gazetteer change ("Acme Labs" beside "Acme Corp") invalidates the checkpoint — page re-scanned', async () => {
+ await seedEntities();
+ await seedContentPage('writing/post-1', 'Acme Corp and Acme Labs.');
+ // A checkpoint from a run that finished before Acme Labs existed.
+ const oldHash = await expectedGazetteerHash();
+ const oldFp = mentionsFingerprint({ source: undefined, type: undefined, since: undefined, gazetteerHash: oldHash });
+ await engine.executeRaw(
+ `INSERT INTO op_checkpoints (op, fingerprint, completed_keys, updated_at)
+ VALUES ('extract-by-mention', $1, $2::text::jsonb, NOW())`,
+ [oldFp, JSON.stringify(['default::writing/post-1'])],
+ );
+ // The new entity shares the 'acme' first-token bucket, so the bucket KEY
+ // set is unchanged — the fingerprint must still move.
+ await engine.putPage('companies/acme-labs', { type: 'company', title: 'Acme Labs', compiled_truth: 'labs body', timeline: '', frontmatter: {} });
+ expect(await expectedGazetteerHash()).not.toBe(oldHash);
+
+ await runByMention([]);
+ const labsLinks = await engine.executeRaw<{ c: string }>(
+ `SELECT COUNT(*)::text AS c FROM links l
+ JOIN pages fp ON fp.id = l.from_page_id
+ JOIN pages tp ON tp.id = l.to_page_id
+ WHERE fp.slug = 'writing/post-1' AND tp.slug = 'companies/acme-labs' AND l.link_source = 'mentions'`,
+ [],
+ );
+ expect(Number(labsLinks[0]!.c)).toBe(1);
+ });
+
test('filtered pages (--type miss) DO get checkpointed (codex fix #4)', async () => {
await seedEntities();
// Two pages: one matches --type filter, one doesn't
diff --git a/test/extract-facts-phase.test.ts b/test/extract-facts-phase.test.ts
index 4d5664f057..133aa8e2ae 100644
--- a/test/extract-facts-phase.test.ts
+++ b/test/extract-facts-phase.test.ts
@@ -533,6 +533,61 @@ describe('runExtractFacts — happy path', () => {
expect(rows.rows[0].fact).toBe('A');
});
+ // #4870 — visibility / notability are fence cells (parsed + validated as
+ // mandatory enums, transported by the wipe+reinsert), but the reconcile
+ // never read them back from the DB, so editing one on an existing row was
+ // a silent no-op: identical content key + row_num + struck-state -> the
+ // short-circuit `continue`. The DB must follow the fence; a third run
+ // after the re-heal must NOT churn.
+ test('visibility edit on an existing fence row re-heals the DB row (#4870)', async () => {
+ await putPage('people/alice', FACT_FENCE(
+ `| 1 | Alice likes tea | preference | 0.9 | world | medium | | | fence | |`,
+ ));
+ await runExtractFacts(engine, { slugs: ['people/alice'] });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ let rows = await (engine as any).db.query(
+ `SELECT visibility, notability FROM facts WHERE source_markdown_slug = 'people/alice'`,
+ );
+ expect(rows.rows).toEqual([{ visibility: 'world', notability: 'medium' }]);
+
+ await putPage('people/alice', FACT_FENCE(
+ `| 1 | Alice likes tea | preference | 0.9 | private | medium | | | fence | |`,
+ ));
+ const second = await runExtractFacts(engine, { slugs: ['people/alice'] });
+ expect(second.factsInserted).toBe(1);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ rows = await (engine as any).db.query(
+ `SELECT visibility, notability FROM facts WHERE source_markdown_slug = 'people/alice'`,
+ );
+ expect(rows.rows).toEqual([{ visibility: 'private', notability: 'medium' }]);
+
+ const third = await runExtractFacts(engine, { slugs: ['people/alice'] });
+ expect(third.factsInserted).toBe(0);
+ expect(third.factsDeleted).toBe(0);
+ });
+
+ test('notability edit on an existing fence row re-heals the DB row (#4870)', async () => {
+ await putPage('people/alice', FACT_FENCE(
+ `| 1 | Alice likes tea | preference | 0.9 | world | medium | | | fence | |`,
+ ));
+ await runExtractFacts(engine, { slugs: ['people/alice'] });
+
+ await putPage('people/alice', FACT_FENCE(
+ `| 1 | Alice likes tea | preference | 0.9 | world | high | | | fence | |`,
+ ));
+ const second = await runExtractFacts(engine, { slugs: ['people/alice'] });
+ expect(second.factsInserted).toBe(1);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const rows = await (engine as any).db.query(
+ `SELECT visibility, notability FROM facts WHERE source_markdown_slug = 'people/alice'`,
+ );
+ expect(rows.rows).toEqual([{ visibility: 'world', notability: 'high' }]);
+
+ const third = await runExtractFacts(engine, { slugs: ['people/alice'] });
+ expect(third.factsInserted).toBe(0);
+ expect(third.factsDeleted).toBe(0);
+ });
+
test('malformed fence rows make the page non-authoritative and preserve its indexed facts', async () => {
await putPage('people/alice', FACT_FENCE(
`| 1 | A | fact | 1.0 | world | medium | 2026-01-01 | | s | |
diff --git a/test/extract-include-frontmatter-config.serial.test.ts b/test/extract-include-frontmatter-config.serial.test.ts
new file mode 100644
index 0000000000..50bbb55eb6
--- /dev/null
+++ b/test/extract-include-frontmatter-config.serial.test.ts
@@ -0,0 +1,167 @@
+/**
+ * `resolveIncludeFrontmatter` is the single answer every extraction path uses
+ * for "should `related:` frontmatter become link edges" (#4997 / #4999).
+ *
+ * The regression this pins: v0.42 added
+ * `autopilot.incremental_extract_include_frontmatter`, but only the autopilot
+ * cycle read it. performSync's inline extract, the GitHub/Google source inline
+ * extracts, the `extract_stale` minion and `gbrain maintain` extracted body
+ * links only AND then stamped `links_extracted_at`, so with the knob on a page
+ * came out of an unattended sync marked fresh without its frontmatter edges,
+ * and the cycle's stale drain never revisited it.
+ *
+ * Serial: points GBRAIN_HOME (via withEnv) at a hermetic config dir so the
+ * machine's real file-plane config cannot leak into the file/DB precedence
+ * assertions.
+ */
+
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { withEnv } from './helpers/with-env.ts';
+import { resolveIncludeFrontmatter, INCLUDE_FRONTMATTER_KEY } from '../src/core/extract-frontmatter.ts';
+
+let home: string;
+
+/** Minimal engine stub: only getConfig is consulted. */
+function engineWith(values: Record<string, string | null>) {
+ const seen: string[] = [];
+ return {
+ seen,
+ getConfig: async (key: string): Promise<string | null> => {
+ seen.push(key);
+ return key in values ? values[key] : null;
+ },
+ };
+}
+
+function writeConfigFile(cfg: Record<string, unknown>) {
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(cfg, null, 2) + '\n');
+}
+
+const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home }, fn);
+
+beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-extract-fm-'));
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+});
+
+afterEach(() => {
+ try { rmSync(home, { recursive: true, force: true }); } catch {}
+});
+
+describe('resolveIncludeFrontmatter', () => {
+ test('defaults to false with no config, no engine, or an engine without the key', () => inHome(async () => {
+ expect(await resolveIncludeFrontmatter(null)).toBe(false);
+ expect(await resolveIncludeFrontmatter(undefined)).toBe(false);
+ expect(await resolveIncludeFrontmatter(engineWith({}))).toBe(false);
+ }));
+
+ test('an explicit value wins over every config plane, in both directions', () => inHome(async () => {
+ writeConfigFile({ autopilot: { incremental_extract_include_frontmatter: false } });
+ expect(await resolveIncludeFrontmatter(engineWith({ [INCLUDE_FRONTMATTER_KEY]: 'false' }), true)).toBe(true);
+
+ writeConfigFile({ autopilot: { incremental_extract_include_frontmatter: true } });
+ expect(await resolveIncludeFrontmatter(engineWith({ [INCLUDE_FRONTMATTER_KEY]: 'true' }), false)).toBe(false);
+ }));
+
+ test('the file plane is honoured and wins over the DB plane (engine never consulted)', () => inHome(async () => {
+ writeConfigFile({ autopilot: { incremental_extract_include_frontmatter: true } });
+ expect(await resolveIncludeFrontmatter(null)).toBe(true);
+
+ const eng = engineWith({ [INCLUDE_FRONTMATTER_KEY]: 'false' });
+ expect(await resolveIncludeFrontmatter(eng)).toBe(true);
+ expect(eng.seen).toHaveLength(0);
+ }));
+
+ test('the DB plane accepts every canonical truthy spelling, unlike the old === "true" compare', () => inHome(async () => {
+ for (const raw of ['true', 'TRUE', ' 1 ', 'yes', 'on']) {
+ expect(await resolveIncludeFrontmatter(engineWith({ [INCLUDE_FRONTMATTER_KEY]: raw }))).toBe(true);
+ }
+ for (const raw of ['false', '0', 'no', 'off', '', 'maybe']) {
+ expect(await resolveIncludeFrontmatter(engineWith({ [INCLUDE_FRONTMATTER_KEY]: raw }))).toBe(false);
+ }
+ }));
+
+ test('a non-boolean file-plane value falls through to the DB plane instead of winning as false (#2120 class)', () => inHome(async () => {
+ // A hand-edited config.json with "true" (string) or 1 used to short-circuit
+ // to false AND shadow the DB plane — so `gbrain config set <key> true` was
+ // a silent no-op. Only a real boolean is a file-plane answer.
+ for (const garbled of ['true', 1, 'yes']) {
+ writeConfigFile({ autopilot: { incremental_extract_include_frontmatter: garbled } });
+ expect(await resolveIncludeFrontmatter(engineWith({ [INCLUDE_FRONTMATTER_KEY]: 'true' }))).toBe(true);
+ expect(await resolveIncludeFrontmatter(engineWith({}))).toBe(false);
+ }
+ }));
+
+ test('fails closed when the config table is unreadable', () => inHome(async () => {
+ const throwing = { getConfig: async (): Promise<string | null> => { throw new Error('no config table'); } };
+ expect(await resolveIncludeFrontmatter(throwing)).toBe(false);
+ }));
+});
+
+/**
+ * Source-text guard (the doctor-source pattern): no extraction path decides
+ * this for itself. A literal `includeFrontmatter: false` at a call site is the
+ * exact shape of the bug, and the resolver's own unit tests cannot see it
+ * come back. The shared helpers (`extractLinksForSlugs`, `extractStaleFromDB`)
+ * must resolve the default themselves so every caller — including the
+ * GitHub/Google source inline extracts that pass `{ sourceId }` only — is
+ * covered without per-caller threading.
+ */
+describe('no extraction path hardcodes includeFrontmatter', () => {
+ test('call sites do not literalise false; the shared helpers resolve the default', () => {
+ // test-reads-source-ok: the bug is a literal at the call sites; only a source-text pin can see it come back.
+ const read = (rel: string) => readFileSync(new URL(`../${rel}`, import.meta.url), 'utf-8');
+ for (const rel of ['src/commands/jobs.ts', 'src/commands/maintain.ts', 'src/core/cycle.ts']) {
+ expect(read(rel)).not.toMatch(/includeFrontmatter:\s*false/);
+ }
+ expect(read('src/core/cycle.ts')).toContain('resolveIncludeFrontmatter');
+ expect(read('src/commands/extract.ts')).toMatch(/resolveIncludeFrontmatter\(engine/);
+ });
+});
+
+/**
+ * Behavioural pin on the shared seam: the sync inline hook, called exactly the
+ * way sync / GitHub-source / Google-source call it (no includeFrontmatter
+ * option), builds a `related:` frontmatter edge once the knob is on.
+ */
+describe('extractLinksForSlugs honours the knob with no per-call option', () => {
+ test('a related: frontmatter edge appears only once the DB-plane key is set', () => inHome(async () => {
+ const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');
+ const { extractLinksForSlugs } = await import('../src/commands/extract.ts');
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-extract-fm-repo-'));
+ try {
+ mkdirSync(join(dir, 'people'), { recursive: true });
+ mkdirSync(join(dir, 'companies'), { recursive: true });
+ // No body link — the ONLY edge is in frontmatter.
+ writeFileSync(join(dir, 'people/alice.md'), [
+ '---', 'type: person', 'title: Alice', 'related:', ' - companies/acme', '---', '', 'Alice is a founder.',
+ ].join('\n'));
+ writeFileSync(join(dir, 'companies/acme.md'), [
+ '---', 'type: company', 'title: Acme', '---', '', 'Acme is a company.',
+ ].join('\n'));
+ const page = (type: 'person' | 'company', title: string) =>
+ ({ type, title, compiled_truth: title, timeline: '', frontmatter: {}, content_hash: 'h' });
+ await engine.putPage('people/alice', page('person', 'Alice'));
+ await engine.putPage('companies/acme', page('company', 'Acme'));
+
+ // Control: knob off → body-only extraction, no frontmatter edge.
+ await extractLinksForSlugs(engine, dir, ['people/alice']);
+ expect((await engine.getLinks('people/alice')).some(l => l.to_slug === 'companies/acme')).toBe(false);
+
+ await engine.setConfig(INCLUDE_FRONTMATTER_KEY, 'true');
+ const result = await extractLinksForSlugs(engine, dir, ['people/alice']);
+ expect(result.processed).toEqual(['people/alice']);
+ expect((await engine.getLinks('people/alice')).some(l => l.to_slug === 'companies/acme')).toBe(true);
+ } finally {
+ await engine.disconnect();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }), 60_000);
+});
diff --git a/test/extract-incremental.test.ts b/test/extract-incremental.test.ts
index b87a433fab..3258c78b43 100644
--- a/test/extract-incremental.test.ts
+++ b/test/extract-incremental.test.ts
@@ -306,4 +306,40 @@ describe('runExtractCore — quiet vs jsonMode on the incremental path', () => {
}
expect(out.lines.some((l) => l.startsWith('Incremental extract: created'))).toBe(true);
});
+
+ test('a filename that does not round-trip through slugification is still read', async () => {
+ // `Widget Co.md` slugs to `companies/widget-co` — the space becomes a
+ // hyphen and the capitals drop. Rebuilding the disk path from the slug
+ // looks for `companies/widget-co.md`, which is not there, so the page was
+ // treated as deleted and skipped without a word.
+ await engine.putPage('companies/widget-co', {
+ type: 'company', title: 'Widget Co',
+ compiled_truth: 'Widget Co knows [[companies/acme]].',
+ timeline: '', frontmatter: {}, content_hash: 'h',
+ });
+ writeFileSync(join(tempDir, 'companies/Widget Co.md'), 'Widget Co knows [[companies/acme]].');
+ await seedPage('companies/acme', '# acme');
+
+ const result = await runExtractCore(engine as unknown as BrainEngine, {
+ mode: 'all', dir: tempDir, slugs: ['companies/widget-co'],
+ });
+ expect(result.pages_processed).toBe(1);
+ const links = await engine.getLinks('companies/widget-co');
+ expect(links.some(l => l.to_slug === 'companies/acme')).toBe(true);
+ });
+
+ test('when two filenames slug the same, the file named exactly the slug wins', async () => {
+ const { buildSlugPathIndex } = await import('../src/commands/extract.ts');
+ // `Acme!.md` and `acme.md` both slug to `companies/acme` (the `!` is not a
+ // legal slug char). The walker does not sort, so a plain last-one-wins map
+ // would resolve the slug differently depending on directory-read order —
+ // and thus differently across filesystems. The exact-slug spelling is what
+ // the old reconstructed path found, so it stays the winner either way.
+ const files = [
+ { relPath: 'companies/acme.md' },
+ { relPath: 'companies/Acme!.md' },
+ ];
+ expect(buildSlugPathIndex(files).get('companies/acme')).toBe('companies/acme.md');
+ expect(buildSlugPathIndex([...files].reverse()).get('companies/acme')).toBe('companies/acme.md');
+ });
});
diff --git a/test/extract.test.ts b/test/extract.test.ts
index e272e66cab..068f0ce84e 100644
--- a/test/extract.test.ts
+++ b/test/extract.test.ts
@@ -402,3 +402,23 @@ describe('extractLinksFromFile — slug normalization (T-OBS-1 regression)', ()
expect(links[0].from_slug).toBe('decisions/0001-living-repo-pattern');
});
});
+
+// #4995: the FS walker's mdPattern required `.md)` to be adjacent, so an
+// anchored link (`[B](b.md#section)`) produced no edge — while its own doc
+// comment promised anchors are stripped.
+describe('#4995 — anchored markdown links on the FS path', () => {
+ it('extractMarkdownLinks strips the #anchor', () => {
+ const links = extractMarkdownLinks('[see](b.md#section) and [D](../registry/tally.md#a b)');
+ expect(links).toHaveLength(2);
+ expect(links[0].relTarget).toBe('b.md');
+ expect(links[1].relTarget).toBe('../registry/tally.md');
+ });
+
+ it('extractLinksFromFile links an anchored sibling', async () => {
+ const allSlugs = new Set(['a', 'b']);
+ const links = await extractLinksFromFile('See [B](b.md#section).', 'a.md', allSlugs);
+ expect(links).toHaveLength(1);
+ expect(links[0].from_slug).toBe('a');
+ expect(links[0].to_slug).toBe('b');
+ });
+});
diff --git a/test/facts-extract-structured-output.test.ts b/test/facts-extract-structured-output.test.ts
new file mode 100644
index 0000000000..594f71fe19
--- /dev/null
+++ b/test/facts-extract-structured-output.test.ts
@@ -0,0 +1,251 @@
+/**
+ * #4863 — facts extraction asks openai-compatible backends that honor
+ * json_schema (Ollama) for schema-constrained output.
+ *
+ * Small local models emit malformed JSON a fraction of the time on a
+ * prompt-only extraction. Ollama enforces `response_format: json_schema`
+ * server-side (grammar-constrained decoding, model-independent), so the
+ * extractor threads its schema through `ChatOpts.responseSchema` and chat()
+ * attaches it as the AI SDK `output` for recipes that declare
+ * `supports_structured_outputs` under the openai-compatible implementation.
+ *
+ * Pinned through the generateText transport seam — the chat transport
+ * short-circuits before the SDK call, so it cannot observe `output`:
+ * - ollama: `output` is attached, its responseFormat is the facts schema,
+ * and the reply text still flows through the extractor's own parser.
+ * - the Output spec is TOLERANT: parseCompleteOutput hands the raw text
+ * back instead of throwing NoObjectGeneratedError (generateText parses
+ * eagerly on finishReason 'stop'), so a malformed reply stays a
+ * recoverable malformed_output for the extractor's retry lane.
+ * - the #2113 truncation retry re-sends at 2x with `output` still attached.
+ * - native anthropic and an openai-compatible recipe WITHOUT the flag get
+ * no `output` at all (lanes byte-identical to before).
+ */
+import { afterAll, afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import {
+ configureGateway,
+ resetGateway,
+ __setGenerateTextTransportForTests,
+} from '../src/core/ai/gateway.ts';
+import { extractFactsFromTurnWithOutcome } from '../src/core/facts/extract.ts';
+
+const OLLAMA = 'ollama:gemma3:4b';
+const GOOD_JSON = '{"facts":[{"fact":"user gave up alcohol","kind":"commitment",' +
+ '"entity":null,"confidence":1.0,"notability":"high",' +
+ '"metric":null,"value":null,"unit":null,"period":null}]}';
+
+function sdkResult(text: string, finishReason: 'stop' | 'length' = 'stop'): any {
+ return { content: [{ type: 'text', text }], finishReason, usage: { inputTokens: 5, outputTokens: 5 } };
+}
+
+function extract(model: string) {
+ return extractFactsFromTurnWithOutcome({ turnText: 'I gave up alcohol.', source: 'test:structured', model });
+}
+
+beforeEach(() => {
+ resetGateway();
+ __setGenerateTextTransportForTests(null);
+});
+
+afterEach(() => {
+ __setGenerateTextTransportForTests(null);
+ resetGateway();
+});
+
+// Shard hygiene (same rationale as facts-extract-truncation.test.ts): restore
+// the legacy 1536-d embedding pin so later fresh-schema files in this shard
+// don't inherit a dimensionless gateway.
+afterAll(() => {
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { ...process.env },
+ });
+});
+
+describe('facts extraction — structured output on ollama (#4863)', () => {
+ test('chat() attaches the facts schema as the SDK `output`; facts still parse from the reply text', async () => {
+ configureGateway({ chat_model: OLLAMA, env: {} });
+ const calls: any[] = [];
+ __setGenerateTextTransportForTests(async (args: any) => { calls.push(args); return sdkResult(GOOD_JSON); });
+
+ const outcome = await extract(OLLAMA);
+
+ expect(calls).toHaveLength(1);
+ expect(calls[0].output).toBeDefined();
+ const rf = await calls[0].output.responseFormat;
+ expect(rf.type).toBe('json');
+ expect(rf.name).toBe('facts_extraction');
+ expect(rf.schema.required).toEqual(['facts']);
+ expect(rf.schema.additionalProperties).toBe(false);
+ const item = rf.schema.properties.facts.items;
+ // Strict-safe: every listed property is required (nullable via type unions), so an
+ // openai-compatible proxy that honors `strict: true` (the SDK default) accepts it too.
+ expect(item.required).toEqual(Object.keys(item.properties));
+ expect(rf.schema.required).toEqual(Object.keys(rf.schema.properties));
+ expect(item.additionalProperties).toBe(false);
+ expect(item.properties.kind.enum).toContain('commitment');
+ expect(item.properties.notability.enum).toEqual(['high', 'medium', 'low']);
+
+ expect(outcome.ok).toBe(true);
+ if (outcome.ok) {
+ expect(outcome.facts).toHaveLength(1);
+ expect(outcome.facts[0]!.kind).toBe('commitment');
+ }
+ });
+
+ test('the Output spec is tolerant: malformed text is handed back, not thrown, so the extractor retry lane runs', async () => {
+ configureGateway({ chat_model: OLLAMA, env: {} });
+ const calls: any[] = [];
+ __setGenerateTextTransportForTests(async (args: any) => {
+ calls.push(args);
+ return sdkResult(calls.length === 1 ? 'not json' : GOOD_JSON);
+ });
+
+ const outcome = await extract(OLLAMA);
+
+ // Output.object would throw NoObjectGeneratedError inside generateText on
+ // the first reply; the tolerant spec returns the text untouched.
+ await expect(calls[0].output.parseCompleteOutput({ text: 'not json' }, {} as any)).resolves.toBe('not json');
+ expect(calls).toHaveLength(2);
+ expect(calls[1].output).toBeDefined();
+ expect(outcome.ok).toBe(true);
+ if (outcome.ok) expect(outcome.facts).toHaveLength(1);
+ });
+
+ test('#2113 truncation retry re-sends at double the cap with `output` still attached', async () => {
+ configureGateway({ chat_model: OLLAMA, env: {} });
+ const calls: any[] = [];
+ __setGenerateTextTransportForTests(async (args: any) => {
+ calls.push(args);
+ return calls.length === 1
+ ? sdkResult('{"facts":[{"fact":"user gave up alco', 'length')
+ : sdkResult(GOOD_JSON);
+ });
+
+ const outcome = await extract(OLLAMA);
+
+ expect(calls).toHaveLength(2);
+ expect(calls[1].maxOutputTokens).toBe(calls[0].maxOutputTokens * 2);
+ expect(calls[1].output).toBeDefined();
+ expect(outcome.ok).toBe(true);
+ });
+});
+
+describe('facts extraction — every other lane is unchanged', () => {
+ test('native anthropic: no `output` on the SDK call', async () => {
+ const model = 'anthropic:claude-sonnet-4-6';
+ configureGateway({ chat_model: model, env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });
+ const calls: any[] = [];
+ __setGenerateTextTransportForTests(async (args: any) => { calls.push(args); return sdkResult(GOOD_JSON); });
+
+ const outcome = await extract(model);
+
+ expect(calls).toHaveLength(1);
+ expect(calls[0].output).toBeUndefined();
+ expect(outcome.ok).toBe(true);
+ });
+
+ test('openai-compatible recipe that does NOT declare structured outputs: no `output` either', async () => {
+ const model = 'deepseek:deepseek-chat';
+ configureGateway({ chat_model: model, env: { DEEPSEEK_API_KEY: 'sk-fake' } });
+ const calls: any[] = [];
+ __setGenerateTextTransportForTests(async (args: any) => { calls.push(args); return sdkResult(GOOD_JSON); });
+
+ const outcome = await extract(model);
+
+ expect(calls).toHaveLength(1);
+ expect(calls[0].output).toBeUndefined();
+ expect(outcome.ok).toBe(true);
+ });
+});
+
+// Pre-landing review (#4968 adoption): a recipe that DECLARES structured
+// outputs but whose backend rejects `response_format: json_schema` at call
+// time (an older Ollama build, a strict proxy) must not turn every facts
+// extraction into a permanent provider_error. chat() retries ONCE without the
+// schema and remembers the recipe for the process lifetime — the same
+// `_structuredOutputRejectedRecipes` memory expand() already keeps.
+describe('facts extraction — json_schema rejected at call time falls back schemaless', () => {
+ function apiError(statusCode: number, message: string): Error {
+ return Object.assign(new Error(message), {
+ name: 'AI_APICallError',
+ statusCode,
+ responseBody: JSON.stringify({ error: { message, type: 'invalid_request_error' } }),
+ });
+ }
+
+ let warns: string[] = [];
+ const origWarn = console.warn;
+ beforeEach(() => {
+ warns = [];
+ console.warn = (...args: unknown[]) => { warns.push(args.map(String).join(' ')); };
+ });
+ afterEach(() => { console.warn = origWarn; });
+
+ test('a 400 naming json_schema → one schemaless retry succeeds; later extractions skip the schema with no failing call', async () => {
+ configureGateway({ chat_model: OLLAMA, env: {} });
+ const calls: any[] = [];
+ __setGenerateTextTransportForTests(async (args: any) => {
+ calls.push(args);
+ if (args.output) throw apiError(400, 'response_format json_schema is not supported by this model');
+ return sdkResult(GOOD_JSON);
+ });
+
+ const first = await extract(OLLAMA);
+
+ expect(first.ok).toBe(true);
+ expect(calls).toHaveLength(2);
+ expect(calls[0].output).toBeDefined();
+ expect(calls[1].output).toBeUndefined();
+ expect(warns.filter(w => /json_schema/.test(w))).toHaveLength(1);
+
+ const second = await extract(OLLAMA);
+
+ expect(second.ok).toBe(true);
+ expect(calls).toHaveLength(3);
+ expect(calls[2].output).toBeUndefined();
+ expect(warns.filter(w => /json_schema/.test(w))).toHaveLength(1); // remembered: no second rejection, no second warn
+ });
+
+ test('an unrelated 500 is NOT a schema rejection: no retry, provider_error, schema still sent next time', async () => {
+ configureGateway({ chat_model: OLLAMA, env: {} });
+ const calls: any[] = [];
+ let failing = true;
+ __setGenerateTextTransportForTests(async (args: any) => {
+ calls.push(args);
+ if (failing) throw apiError(500, 'internal server error: upstream timeout');
+ return sdkResult(GOOD_JSON);
+ });
+
+ const failed = await extract(OLLAMA);
+
+ expect(failed.ok).toBe(false);
+ if (!failed.ok) expect(failed.reason).toBe('provider_error');
+ expect(calls).toHaveLength(1);
+
+ failing = false;
+ const recovered = await extract(OLLAMA);
+
+ expect(recovered.ok).toBe(true);
+ expect(calls).toHaveLength(2);
+ expect(calls[1].output).toBeDefined();
+ expect(warns.filter(w => /json_schema/.test(w))).toHaveLength(0);
+ });
+
+ test('a 400 that does not name the schema (context length) is NOT a schema rejection', async () => {
+ configureGateway({ chat_model: OLLAMA, env: {} });
+ const calls: any[] = [];
+ __setGenerateTextTransportForTests(async (args: any) => {
+ calls.push(args);
+ throw apiError(400, "this model's maximum context length is 8192 tokens");
+ });
+
+ const failed = await extract(OLLAMA);
+
+ expect(failed.ok).toBe(false);
+ if (!failed.ok) expect(failed.reason).toBe('provider_error');
+ expect(calls).toHaveLength(1);
+ expect(calls[0].output).toBeDefined();
+ });
+});
diff --git a/test/file-upload-fail-closed.test.ts b/test/file-upload-fail-closed.test.ts
index 6e0ad7558e..7cd782de8f 100644
--- a/test/file-upload-fail-closed.test.ts
+++ b/test/file-upload-fail-closed.test.ts
@@ -13,7 +13,7 @@
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
-import { existsSync, mkdtempSync, realpathSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -82,6 +82,74 @@ describe('file_upload fail-closed (#4302)', () => {
expect(existsSync(join(storageDir, 'notes/real/real.txt'))).toBe(true);
});
+ // #4910: the files row must say WHICH lane holds the bytes so readers
+ // (doctor image_assets, files verify) never stat a bucket key as a local
+ // path. Legacy rows with `{}` metadata heal on the next content change
+ // because the upsert merges metadata instead of leaving it untouched.
+ test('upload stamps metadata.storage with the configured backend and heals legacy rows on conflict', async () => {
+ const op = operationsByName['file_upload'];
+ const src = join(fixtureDir, 'lane.txt');
+ writeFileSync(src, 'lane bytes v1');
+ await op.handler(mkCtx(true), { path: src, page_slug: 'notes/lane' });
+ const meta = async (storagePath: string) => {
+ const rows = await engine.executeRaw<{ metadata: unknown }>(
+ `SELECT metadata FROM files WHERE storage_path = $1`, [storagePath],
+ );
+ const m = rows[0]?.metadata;
+ return (typeof m === 'string' ? JSON.parse(m) : m) as Record<string, unknown> | null;
+ };
+ expect((await meta('notes/lane/lane.txt'))?.storage).toBe('local');
+
+ // Legacy row: pre-fix writer left `{}`. A re-upload with changed bytes
+ // takes the ON CONFLICT path and must stamp the lane (jsonb merge).
+ const legacy = join(fixtureDir, 'legacy.txt');
+ writeFileSync(legacy, 'legacy bytes v1');
+ await engine.executeRaw(
+ `INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)
+ VALUES ('notes/legacy', 'legacy.txt', 'notes/legacy/legacy.txt', 'text/plain', 1, 'stale-hash', '{"upload_method":"standard"}'::jsonb)`,
+ );
+ await op.handler(mkCtx(true), { path: legacy, page_slug: 'notes/legacy' });
+ const healed = await meta('notes/legacy/legacy.txt');
+ expect(healed?.storage).toBe('local');
+ expect(healed?.upload_method).toBe('standard');
+ });
+
+ // A #2339-era row holds metadata as the jsonb STRING scalar `"{}"` (the
+ // shape `gbrain repair-jsonb` heals via `jsonb_typeof = 'string'`). jsonb
+ // `||` merges only object||object and ARRAY-WRAPS any other left operand,
+ // so a bare `files.metadata || EXCLUDED.metadata` would turn the row into
+ // `["{}", {...}]` — invisible to repair-jsonb and unreadable by every
+ // `.storage` reader (files verify, doctor image_assets). The merge must
+ // reset non-object metadata to `{}` first.
+ test('legacy string-scalar metadata row stays an object on conflict', async () => {
+ const op = operationsByName['file_upload'];
+ const scalar = join(fixtureDir, 'scalar.txt');
+ writeFileSync(scalar, 'scalar bytes v1');
+ await engine.executeRaw(
+ `INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)
+ VALUES ('notes/scalar', 'scalar.txt', 'notes/scalar/scalar.txt', 'text/plain', 1, 'stale-hash', '"{}"'::jsonb)`,
+ );
+ await op.handler(mkCtx(true), { path: scalar, page_slug: 'notes/scalar' });
+ const rows = await engine.executeRaw<{ kind: string; storage: string | null }>(
+ `SELECT jsonb_typeof(metadata) AS kind, metadata->>'storage' AS storage
+ FROM files WHERE storage_path = 'notes/scalar/scalar.txt'`,
+ );
+ expect(rows[0]).toEqual({ kind: 'object', storage: 'local' });
+ });
+
+ // The MCP op above is one of five files upserts (the CLI upload/upload-raw/
+ // smart-upload/sync lanes are the other four). They all merge through the
+ // one hoisted fragment so the non-object guard cannot drift per site.
+ test('every files upsert merges metadata through FILES_METADATA_MERGE_SQL', () => {
+ for (const f of ['src/commands/files.ts', 'src/core/ops/files.ts']) {
+ const src = readFileSync(join(import.meta.dir, '..', f), 'utf8');
+ expect(src).not.toMatch(/files\.metadata\s*\|\|\s*EXCLUDED\.metadata/);
+ const conflicts = src.match(/ON CONFLICT \(storage_path\)/g)?.length ?? 0;
+ expect(conflicts).toBeGreaterThan(0);
+ expect(src.match(/\$\{FILES_METADATA_MERGE_SQL\}/g)?.length ?? 0).toBe(conflicts);
+ }
+ });
+
test('already_exists only when the backend really holds the object', async () => {
const op = operationsByName['file_upload'];
const src = join(fixtureDir, 'dup.txt');
diff --git a/test/files.test.ts b/test/files.test.ts
index 50001fdd08..b92ce57523 100644
--- a/test/files.test.ts
+++ b/test/files.test.ts
@@ -321,6 +321,30 @@ describe('files upload-raw git-storage branch (#2297)', () => {
expect(meta.type).toBe('report');
});
+ // Pre-landing review: the #4910 ON CONFLICT metadata merge must not null a
+ // stored `type` when the same path is re-uploaded without --type. jsonb `||`
+ // writes a null VALUE over the existing key, so the payload may only carry
+ // `type` when the flag was actually given.
+ test('re-upload without --type keeps the stored metadata type', async () => {
+ await engine.setConfig('sync.repo_path', repo);
+ const src = join(srcDir, 'retyped.txt');
+ writeFileSync(src, 'first bytes');
+ const cap = captureLogs();
+ try {
+ await runFiles(engine, ['upload-raw', src, '--page', 'notes/small-doc', '--type', 'photo']);
+ writeFileSync(src, 'changed bytes');
+ await runFiles(engine, ['upload-raw', src, '--page', 'notes/small-doc']);
+ } finally {
+ cap.restore();
+ }
+ const rows = await engine.executeRaw<{ type: string | null; storage: string | null }>(
+ `SELECT metadata->>'type' AS type, metadata->>'storage' AS storage FROM files WHERE filename = 'retyped.txt'`,
+ );
+ expect(rows.length).toBe(1);
+ expect(rows[0].storage).toBe('git');
+ expect(rows[0].type).toBe('photo');
+ });
+
test('no repo configured: exits 1 instead of lying success', async () => {
await engine.executeRaw(`DELETE FROM config WHERE key = 'sync.repo_path'`);
const src = join(srcDir, 'orphan.txt');
diff --git a/test/frontmatter-install-hook.test.ts b/test/frontmatter-install-hook.test.ts
index baf928fe84..51ea2a1046 100644
--- a/test/frontmatter-install-hook.test.ts
+++ b/test/frontmatter-install-hook.test.ts
@@ -1,9 +1,10 @@
import { describe, expect, test, beforeEach, afterEach } from 'bun:test';
-import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'fs';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, symlinkSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { execFileSync } from 'child_process';
-import { installHook, uninstallHook } from '../src/commands/frontmatter-install-hook.ts';
+import { activeGitHooks, installHook, uninstallHook } from '../src/commands/frontmatter-install-hook.ts';
+import { withEnv } from './helpers/with-env.ts';
function gitInit(dir: string) {
execFileSync('git', ['init', '-q', dir]);
@@ -11,6 +12,46 @@ function gitInit(dir: string) {
execFileSync('git', ['-C', dir, 'config', 'user.name', 'Test']);
}
+/**
+ * installHook with the developer's global/system git config masked: a global
+ * core.hooksPath (husky, secret-scanner templates, dotfiles) would otherwise
+ * turn every "installed" here into "installed_unwired". Tests that WANT a
+ * global value wrap withEnv themselves.
+ */
+const install = (path: string, force = false) =>
+ withEnv({ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null' }, () => installHook(path, force));
+
+/**
+ * Run the installed hook (via sh, as git would) with a `gbrain` stub that FAILS
+ * every validate call: any staged file that reaches the loop blocks the
+ * commit, so exit 0 proves a file was never reached and exit 1 proves it was.
+ */
+function runHookWithFailingGbrain(repo: string): number {
+ const bin = mkdtempSync(join(tmpdir(), 'fm-hook-bin-'));
+ writeFileSync(join(bin, 'gbrain'), '#!/bin/sh\nexit 1\n', { mode: 0o755 });
+ try {
+ execFileSync('sh', [join(repo, '.githooks', 'pre-commit')], {
+ cwd: repo,
+ env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ''}` },
+ stdio: 'pipe',
+ });
+ return 0;
+ } catch (e) {
+ return (e as { status: number }).status;
+ } finally {
+ rmSync(bin, { recursive: true, force: true });
+ }
+}
+
+/** The repo-local core.hooksPath ('' when unset) — global scope never leaks in. */
+function localHooksPath(dir: string): string {
+ try {
+ return execFileSync('git', ['-C', dir, 'config', '--local', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim();
+ } catch {
+ return '';
+ }
+}
+
describe('frontmatter install-hook (B13)', () => {
let tmp: string;
@@ -23,38 +64,22 @@ describe('frontmatter install-hook (B13)', () => {
rmSync(tmp, { recursive: true, force: true });
});
- test('installHook writes executable .githooks/pre-commit and sets core.hooksPath', () => {
- const result = installHook(tmp, false);
+ test('installHook writes executable .githooks/pre-commit and sets core.hooksPath', async () => {
+ const result = await install(tmp);
expect(result).toBe('installed');
const hookPath = join(tmp, '.githooks', 'pre-commit');
expect(existsSync(hookPath)).toBe(true);
const content = readFileSync(hookPath, 'utf8');
expect(content).toContain('gbrain frontmatter');
expect(content).toContain('git diff --cached');
- // installHook's contract is "set core.hooksPath unless it's already set
- // elsewhere". Test BOTH branches deterministically by reading the local
- // scope only: clean CI → local should be `.githooks`; developer with a
- // global core.hooksPath (e.g. dotfiles → ~/.config/git/hooks) → local
- // should be empty because installHook correctly skipped clobbering.
- // Reading via `--get` without `--local` falls back to global scope when
- // local is unset, which made this test environmentally fragile.
- let globalHooksPath = '';
- try {
- globalHooksPath = execFileSync('git', ['config', '--global', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim();
- } catch { /* unset is the expected clean-env case */ }
- let localHooksPath = '';
- try {
- localHooksPath = execFileSync('git', ['-C', tmp, 'config', '--local', '--get', 'core.hooksPath'], { encoding: 'utf8' }).trim();
- } catch { /* unset is fine when global was present */ }
- if (globalHooksPath) {
- expect(localHooksPath).toBe('');
- } else {
- expect(localHooksPath).toBe('.githooks');
- }
+ // install() masks the developer's global config, so the clean-machine
+ // branch is the only one here; the "already set elsewhere" branch has its
+ // own test below. Read the LOCAL scope so a global value can't satisfy it.
+ expect(localHooksPath(tmp)).toBe('.githooks');
});
- test('#1840 — generated hook matches .md/.mdx (single-backslash regex, not over-escaped)', () => {
- installHook(tmp, false);
+ test('#1840 — generated hook matches .md/.mdx (single-backslash regex, not over-escaped)', async () => {
+ await install(tmp);
const content = readFileSync(join(tmp, '.githooks', 'pre-commit'), 'utf8');
// The shell must see `grep -E '\.mdx?$'`. Pre-fix it emitted `'\\.mdx?$'`
// (literal backslash), so the hook matched nothing and silently no-opped.
@@ -72,45 +97,45 @@ describe('frontmatter install-hook (B13)', () => {
expect(re.test('notes/thing.txt')).toBe(false);
});
- test('installHook refuses to clobber existing hook without --force', () => {
+ test('installHook refuses to clobber existing hook without --force', async () => {
const hooksDir = join(tmp, '.githooks');
mkdirSync(hooksDir, { recursive: true });
const hookPath = join(hooksDir, 'pre-commit');
writeFileSync(hookPath, '#!/bin/sh\necho "user hook"');
- const result = installHook(tmp, false);
+ const result = await install(tmp);
expect(result).toBe('skipped_existing');
// Original survives.
expect(readFileSync(hookPath, 'utf8')).toContain('user hook');
expect(existsSync(hookPath + '.bak')).toBe(false);
});
- test('installHook with force overwrites and saves .bak', () => {
+ test('installHook with force overwrites and saves .bak', async () => {
const hooksDir = join(tmp, '.githooks');
mkdirSync(hooksDir, { recursive: true });
const hookPath = join(hooksDir, 'pre-commit');
writeFileSync(hookPath, '#!/bin/sh\necho "user hook"');
- const result = installHook(tmp, true);
+ const result = await install(tmp, true);
expect(result).toBe('installed');
expect(existsSync(hookPath + '.bak')).toBe(true);
expect(readFileSync(hookPath + '.bak', 'utf8')).toContain('user hook');
expect(readFileSync(hookPath, 'utf8')).toContain('gbrain frontmatter');
});
- test('installHook on existing gbrain hook refreshes silently (no .bak)', () => {
- installHook(tmp, false);
+ test('installHook on existing gbrain hook refreshes silently (no .bak)', async () => {
+ await install(tmp);
const hookPath = join(tmp, '.githooks', 'pre-commit');
expect(existsSync(hookPath + '.bak')).toBe(false);
// Re-run; should be 'unchanged' (banner already present).
- const second = installHook(tmp, false);
+ const second = await install(tmp);
expect(second).toBe('unchanged');
});
- test('uninstallHook removes the gbrain hook and restores .bak when present', () => {
+ test('uninstallHook removes the gbrain hook and restores .bak when present', async () => {
const hooksDir = join(tmp, '.githooks');
mkdirSync(hooksDir, { recursive: true });
const hookPath = join(hooksDir, 'pre-commit');
writeFileSync(hookPath, '#!/bin/sh\necho "user hook"');
- installHook(tmp, true);
+ await install(tmp, true);
expect(existsSync(hookPath + '.bak')).toBe(true);
const removed = uninstallHook(tmp);
@@ -120,7 +145,7 @@ describe('frontmatter install-hook (B13)', () => {
expect(existsSync(hookPath + '.bak')).toBe(false);
});
- test('uninstallHook on a non-gbrain hook returns false (does not remove user hook)', () => {
+ test('uninstallHook on a non-gbrain hook returns false (does not remove user hook)', async () => {
const hooksDir = join(tmp, '.githooks');
mkdirSync(hooksDir, { recursive: true });
const hookPath = join(hooksDir, 'pre-commit');
@@ -129,4 +154,240 @@ describe('frontmatter install-hook (B13)', () => {
expect(removed).toBe(false);
expect(readFileSync(hookPath, 'utf8')).toContain('user hook');
});
+
+ // ── #4600: local_path is a SUBDIRECTORY of the host repo (the `<ws>/brain`
+ // layout `gbrain bootstrap` creates) — the hook lands at the discovered git
+ // root, pathspec-scoped to the source, one hook per root.
+
+ test('#4600 nested source: hook installs at the discovered git root, scoped to the subdirectory', async () => {
+ mkdirSync(join(tmp, 'brain'));
+ expect(await install(join(tmp, 'brain'))).toBe('installed');
+ const hookPath = join(tmp, '.githooks', 'pre-commit');
+ expect(existsSync(hookPath)).toBe(true);
+ expect(existsSync(join(tmp, 'brain', '.githooks'))).toBe(false);
+ const content = readFileSync(hookPath, 'utf8');
+ expect(content).toContain('# gbrain-scope: brain/');
+ expect(content).toContain("--diff-filter=ACM -- 'brain/' | tr '\\0' '\\n' | grep -E '\\.mdx?$'");
+ });
+
+ test('#4600 several nested sources share one hook: pathspecs union, no .bak, idempotent', async () => {
+ mkdirSync(join(tmp, 'brain'));
+ mkdirSync(join(tmp, 'wiki'));
+ expect(await install(join(tmp, 'brain'))).toBe('installed');
+ expect(await install(join(tmp, 'wiki'))).toBe('installed');
+ const hookPath = join(tmp, '.githooks', 'pre-commit');
+ const content = readFileSync(hookPath, 'utf8');
+ expect(content).toContain('# gbrain-scope: brain/');
+ expect(content).toContain('# gbrain-scope: wiki/');
+ expect(content).toContain("-- 'brain/' 'wiki/' |");
+ expect(existsSync(hookPath + '.bak')).toBe(false);
+ expect(await install(join(tmp, 'wiki'))).toBe('unchanged');
+ });
+
+ test('#4600 root-registered source keeps the unscoped script; a root install widens a scoped hook to the whole repo', async () => {
+ await install(tmp);
+ const hookPath = join(tmp, '.githooks', 'pre-commit');
+ expect(readFileSync(hookPath, 'utf8')).not.toContain('gbrain-scope');
+ expect(readFileSync(hookPath, 'utf8')).toContain("--diff-filter=ACM | tr '\\0' '\\n' | grep -E '\\.mdx?$'");
+
+ mkdirSync(join(tmp, 'brain'));
+ expect(await install(join(tmp, 'brain'))).toBe('unchanged'); // whole repo already covers brain/
+ expect(readFileSync(hookPath, 'utf8')).not.toContain('gbrain-scope');
+ });
+
+ test('#4600 the other order: a root install after a nested one widens the scoped hook to the whole repo', async () => {
+ mkdirSync(join(tmp, 'brain'));
+ await install(join(tmp, 'brain'));
+ const hookPath = join(tmp, '.githooks', 'pre-commit');
+ expect(readFileSync(hookPath, 'utf8')).toContain('# gbrain-scope: brain/');
+ expect(await install(tmp)).toBe('installed');
+ const content = readFileSync(hookPath, 'utf8');
+ expect(content).not.toContain('gbrain-scope');
+ expect(content).toContain("--diff-filter=ACM | tr '\\0' '\\n' | grep -E '\\.mdx?$'");
+ expect(existsSync(hookPath + '.bak')).toBe(false);
+ });
+
+ test('#4600 the scoped hook ignores staged files outside the source (host README commits pass)', async () => {
+ mkdirSync(join(tmp, 'brain'));
+ await install(join(tmp, 'brain'));
+ writeFileSync(join(tmp, 'README.md'), 'no frontmatter here\n');
+ execFileSync('git', ['-C', tmp, 'add', 'README.md']);
+ expect(runHookWithFailingGbrain(tmp)).toBe(0);
+ writeFileSync(join(tmp, 'brain', 'bad.md'), 'no frontmatter here\n');
+ execFileSync('git', ['-C', tmp, 'add', 'brain/bad.md']);
+ expect(runHookWithFailingGbrain(tmp)).toBe(1);
+ });
+
+ test('the hook checks a staged filename containing a space or non-ASCII characters', async () => {
+ mkdirSync(join(tmp, 'brain'));
+ await install(join(tmp, 'brain'));
+ // `for f in $staged` word-split "brain/my note.md" into two non-files
+ // (skipped), and git's default core.quotePath printed "brain/caf\303\251.md"
+ // in double quotes, which `grep '\.mdx?$'` then rejected — both silently
+ // let malformed pages through.
+ writeFileSync(join(tmp, 'brain', 'my note.md'), 'no frontmatter here\n');
+ execFileSync('git', ['-C', tmp, 'add', 'brain/my note.md']);
+ expect(runHookWithFailingGbrain(tmp)).toBe(1);
+ execFileSync('git', ['-C', tmp, 'reset', '-q']);
+ writeFileSync(join(tmp, 'brain', 'café.md'), 'no frontmatter here\n');
+ execFileSync('git', ['-C', tmp, 'add', 'brain/café.md']);
+ expect(runHookWithFailingGbrain(tmp)).toBe(1);
+ });
+
+ test('#4600 a scope containing a quote is shell-quoted into the pathspec and the hook still runs', async () => {
+ mkdirSync(join(tmp, "it's"));
+ await install(join(tmp, "it's"));
+ const content = readFileSync(join(tmp, '.githooks', 'pre-commit'), 'utf8');
+ expect(content).toContain("# gbrain-scope: it's/");
+ expect(content).toContain(`-- 'it'\\''s/'`);
+ writeFileSync(join(tmp, 'README.md'), 'outside\n');
+ execFileSync('git', ['-C', tmp, 'add', 'README.md']);
+ expect(runHookWithFailingGbrain(tmp)).toBe(0);
+ writeFileSync(join(tmp, "it's", 'bad.md'), 'inside\n');
+ execFileSync('git', ['-C', tmp, 'add', "it's/bad.md"]);
+ expect(runHookWithFailingGbrain(tmp)).toBe(1);
+ });
+
+ test('#4600 uninstall for one nested source drops only its scope; the last one removes the hook', async () => {
+ mkdirSync(join(tmp, 'brain'));
+ mkdirSync(join(tmp, 'wiki'));
+ await install(join(tmp, 'brain'));
+ await install(join(tmp, 'wiki'));
+ const hookPath = join(tmp, '.githooks', 'pre-commit');
+ expect(uninstallHook(join(tmp, 'brain'))).toBe(true);
+ const content = readFileSync(hookPath, 'utf8');
+ expect(content).not.toContain('brain/');
+ expect(content).toContain("-- 'wiki/' |");
+ expect(uninstallHook(join(tmp, 'wiki'))).toBe(true);
+ expect(existsSync(hookPath)).toBe(false);
+ });
+
+ test('a host repo that already runs hooks from .git/hooks keeps core.hooksPath unset (hook written, not wired)', async () => {
+ // Setting core.hooksPath makes git ignore <gitdir>/hooks/* for EVERY hook
+ // type. `git init` ships only *.sample files there (inert); an executable
+ // non-sample entry is a live hook the user relies on, so wiring .githooks
+ // would silently disable it. Non-executable files are ignored by git too.
+ const gitHooks = join(tmp, '.git', 'hooks');
+ writeFileSync(join(gitHooks, 'pre-push'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ writeFileSync(join(gitHooks, 'pre-rebase'), '#!/bin/sh\nexit 0\n', { mode: 0o644 });
+ expect(activeGitHooks(tmp)).toEqual(['pre-push']);
+ mkdirSync(join(tmp, 'brain'));
+ expect(await install(join(tmp, 'brain'))).toBe('installed_unwired');
+ // A re-run refreshes an identical script — still inert, so still unwired
+ // (not "unchanged", which the CLI prints as "already up to date").
+ expect(await install(join(tmp, 'brain'))).toBe('installed_unwired');
+ expect(existsSync(join(tmp, '.githooks', 'pre-commit'))).toBe(true);
+ expect(localHooksPath(tmp)).toBe('');
+ });
+
+ test('a core.hooksPath already pointing elsewhere (global/corporate templates) is reported unwired, not installed', async () => {
+ // git resolves core.hooksPath from every scope; a global one (husky,
+ // secret-scanner templates, dotfiles) means git never looks at .githooks.
+ // "installed" would be a lie — the hook is on disk but inert.
+ const other = mkdtempSync(join(tmpdir(), 'fm-hook-elsewhere-'));
+ try {
+ writeFileSync(join(other, 'gitconfig'), `[core]\n\thooksPath = ${join(other, 'hooks')}\n`);
+ // installHook directly: install() would mask the very global config
+ // this test supplies.
+ await withEnv({ GIT_CONFIG_GLOBAL: join(other, 'gitconfig') }, async () => {
+ expect(installHook(tmp, false)).toBe('installed_unwired');
+ });
+ expect(existsSync(join(tmp, '.githooks', 'pre-commit'))).toBe(true);
+ expect(localHooksPath(tmp)).toBe(''); // theirs to keep — never clobbered
+ // The inverse: a hooksPath that RESOLVES to our dir (absolute, unresolved
+ // /tmp on macOS) is wired, whatever its spelling.
+ execFileSync('git', ['-C', tmp, 'config', 'core.hooksPath', join(tmp, '.githooks')]);
+ expect(await install(tmp)).toBe('unchanged');
+ } finally {
+ rmSync(other, { recursive: true, force: true });
+ }
+ });
+
+ test('a fresh clone that carries the committed gbrain hook gets wired on install (not "unchanged" while inert)', async () => {
+ // The hook FILE travels with the repo; core.hooksPath is per-clone config
+ // and does not. Install on the clone must fall through to the wiring step
+ // instead of stopping at "the script is already current".
+ await install(tmp);
+ execFileSync('git', ['-C', tmp, 'add', '.githooks']);
+ execFileSync('git', ['-C', tmp, '-c', 'commit.gpgsign=false', 'commit', '-q', '-m', 'add hook']);
+ const clone = mkdtempSync(join(tmpdir(), 'fm-hook-clone-'));
+ try {
+ execFileSync('git', ['clone', '-q', tmp, clone]);
+ expect(localHooksPath(clone)).toBe('');
+ expect(await install(clone)).toBe('installed');
+ expect(localHooksPath(clone)).toBe('.githooks');
+ } finally {
+ rmSync(clone, { recursive: true, force: true });
+ }
+ });
+
+ test('a host repo that ships other hook scripts under .githooks/ keeps core.hooksPath unset (wiring would activate them)', async () => {
+ // Third-party clones commit `.githooks/<hook>` as a convention. Pointing
+ // core.hooksPath at that dir makes git run EVERY executable script in
+ // it — not just ours — so the installer must refuse to flip the switch.
+ mkdirSync(join(tmp, '.githooks'));
+ writeFileSync(join(tmp, '.githooks', 'post-commit'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ writeFileSync(join(tmp, '.githooks', 'README.md'), 'docs, not a hook\n');
+ expect(await install(tmp)).toBe('installed_unwired');
+ expect(readFileSync(join(tmp, '.githooks', 'pre-commit'), 'utf8')).toContain('gbrain frontmatter');
+ expect(localHooksPath(tmp)).toBe('');
+ });
+
+ test('a symlinked .githooks/ or pre-commit is refused — nothing is written or removed through the link', async () => {
+ // A committed symlink in a host repo would otherwise redirect our
+ // writeFileSync/chmodSync (and uninstall's rmSync) to wherever it points.
+ const elsewhere = mkdtempSync(join(tmpdir(), 'fm-hook-linktarget-'));
+ try {
+ symlinkSync(elsewhere, join(tmp, '.githooks'));
+ await expect(install(tmp)).rejects.toThrow(/symlink/);
+ expect(existsSync(join(elsewhere, 'pre-commit'))).toBe(false);
+ rmSync(join(tmp, '.githooks'));
+ mkdirSync(join(tmp, '.githooks'));
+ symlinkSync(join(elsewhere, 'target'), join(tmp, '.githooks', 'pre-commit'));
+ await expect(install(tmp)).rejects.toThrow(/symlink/);
+ expect(existsSync(join(elsewhere, 'target'))).toBe(false);
+ expect(() => uninstallHook(tmp)).toThrow(/symlink/);
+ } finally {
+ rmSync(elsewhere, { recursive: true, force: true });
+ }
+ });
+
+ test('a source path containing a line terminator is refused before rendering — nothing written, an installed hook untouched (pre-landing review r3)', async () => {
+ // "# gbrain-scope: <path>" is a shell comment: a newline inside the path
+ // would end it early and the remainder would run as hook code.
+ const evil = join(tmp, 'brain\necho pwned');
+ mkdirSync(evil);
+ await expect(install(evil)).rejects.toThrow(/line terminator/);
+ expect(existsSync(join(tmp, '.githooks', 'pre-commit'))).toBe(false);
+ // A hook already guarding a sibling source stays byte-identical.
+ mkdirSync(join(tmp, 'brain'));
+ await install(join(tmp, 'brain'));
+ const before = readFileSync(join(tmp, '.githooks', 'pre-commit'), 'utf8');
+ for (const bad of [evil, join(tmp, 'brain\rx')]) {
+ if (!existsSync(bad)) mkdirSync(bad);
+ await expect(install(bad)).rejects.toThrow(/line terminator/);
+ expect(() => uninstallHook(bad)).toThrow(/line terminator/);
+ }
+ expect(readFileSync(join(tmp, '.githooks', 'pre-commit'), 'utf8')).toBe(before);
+ // Control: quotes + spaces still install, and the scope text appears ONLY
+ // on a marker (comment) line or inside the quoted `--` pathspec.
+ mkdirSync(join(tmp, "it's here"));
+ await install(join(tmp, "it's here"));
+ const hook = readFileSync(join(tmp, '.githooks', 'pre-commit'), 'utf8');
+ const carrying = hook.split('\n').filter((l) => l.includes('s here/')); // the pathspec spells it 'it'\''s here/'
+ expect(carrying.length).toBe(2);
+ for (const line of carrying) {
+ expect(line.startsWith('# gbrain-scope: ') || line.startsWith('staged=$(git diff --cached ')).toBe(true);
+ }
+ });
+
+ test('#4600 a path outside any git repo is refused with the shared sync message, nothing written', async () => {
+ const plain = mkdtempSync(join(tmpdir(), 'fm-hook-nogit-'));
+ try {
+ await expect(install(plain)).rejects.toThrow(/Not inside a git repository/);
+ expect(existsSync(join(plain, '.githooks'))).toBe(false);
+ } finally {
+ rmSync(plain, { recursive: true, force: true });
+ }
+ });
});
diff --git a/test/generate-flag-registry.test.ts b/test/generate-flag-registry.test.ts
index 5023c28709..7a6aef6e8f 100644
--- a/test/generate-flag-registry.test.ts
+++ b/test/generate-flag-registry.test.ts
@@ -183,6 +183,32 @@ describe('segmentDispatchBlocks — every if/case shape is a marker for its comm
expect(CLI_FLAG_REGISTRY.reindex).toContain('--multimodal');
});
+ test('committed registry: brainstorm/lsd do not carry the phantom --retry-judge (#4766)', () => {
+ // The flag had no parser branch; it registered only because the judge-failed
+ // advice strings in the brainstorm orchestrator mentioned it. The advice now
+ // points at --resume, so the token is gone from the source and the rows.
+ expect(CLI_FLAG_REGISTRY.brainstorm).not.toContain('--retry-judge');
+ expect(CLI_FLAG_REGISTRY.lsd).not.toContain('--retry-judge');
+ expect(CLI_FLAG_REGISTRY.brainstorm).toContain('--resume');
+ expect(CLI_FLAG_REGISTRY.lsd).toContain('--resume');
+ const fresh = buildFlagRegistry();
+ expect(fresh.brainstorm).not.toContain('--retry-judge');
+ expect(fresh.lsd).not.toContain('--retry-judge');
+ });
+
+ test('committed registry: reindex-search-vector does not carry the phantom --fresh (wave review)', () => {
+ // The command parses only --dry-run/--yes/--json. `--fresh` reached the row
+ // through backfill-base.ts's doc comment ("Used by --fresh + after manual
+ // reset") once #4795 imported checkpointKey from it. Comments at module and
+ // dep depth are prose, not consumption — the same rule the dispatch-block
+ // scan already applies (stripComments).
+ expect(CLI_FLAG_REGISTRY['reindex-search-vector']).not.toContain('--fresh');
+ expect(CLI_FLAG_REGISTRY['reindex-search-vector']).toContain('--yes');
+ const fresh = buildFlagRegistry();
+ expect(fresh['reindex-search-vector']).not.toContain('--fresh');
+ expect(fresh['reindex-search-vector']).toContain('--yes');
+ });
+
test('the real handleCliOnly yields one block per eval bypass sub-owner', () => {
// Pin against src/cli.ts: every sub-owned no-DB bypass must land on eval.
const fresh = buildFlagRegistry();
diff --git a/test/helpers/recording-engine.ts b/test/helpers/recording-engine.ts
new file mode 100644
index 0000000000..04f98c2e45
--- /dev/null
+++ b/test/helpers/recording-engine.ts
@@ -0,0 +1,33 @@
+/**
+ * Wrap an engine so every `executeRaw` / `runMigration` / `transaction` call
+ * (including calls on the engine handed to a `transaction` callback) is
+ * appended to `calls` as `"<method>:<sql>"`. Methods stay bound to the real
+ * engine, so private state and `this.db` keep working.
+ */
+import type { BrainEngine } from '../../src/core/engine.ts';
+
+export function recordingEngine<E extends BrainEngine>(target: E): { engine: E; calls: string[] } {
+ const calls: string[] = [];
+ const wrap = <T extends object>(t: T): T =>
+ new Proxy(t, {
+ get(obj, prop) {
+ const v = Reflect.get(obj, prop, obj);
+ if (typeof v !== 'function') return v;
+ if (prop === 'transaction') {
+ return (fn: (tx: BrainEngine) => Promise<unknown>) => {
+ calls.push('transaction:');
+ return v.call(obj, (tx: BrainEngine) => fn(wrap(tx)));
+ };
+ }
+ if (prop === 'executeRaw' || prop === 'runMigration') {
+ return (...args: unknown[]) => {
+ const sql = args.find((a) => typeof a === 'string') as string | undefined;
+ calls.push(`${String(prop)}:${(sql ?? '').replace(/\s+/g, ' ').trim()}`);
+ return v.apply(obj, args);
+ };
+ }
+ return v.bind(obj);
+ },
+ });
+ return { engine: wrap(target), calls };
+}
diff --git a/test/hook-writeback-stop.serial.test.ts b/test/hook-writeback-stop.serial.test.ts
index ea7b2e4f59..4197d6c570 100644
--- a/test/hook-writeback-stop.serial.test.ts
+++ b/test/hook-writeback-stop.serial.test.ts
@@ -81,6 +81,36 @@ function writeTranscript(userText: string, opts: { assistantOnly?: boolean; assi
return { path: p, root };
}
+function writeTranscriptWithToolResult(userText: string, resultChars: number): { path: string; root: string } {
+ const root = join(tmp, 'projects-root');
+ mkdirSync(root, { recursive: true });
+ const p = join(root, 'session.jsonl');
+ const lines = [
+ JSON.stringify({
+ parentUuid: null, isSidechain: false, type: 'user',
+ message: { role: 'user', content: userText },
+ uuid: 'u-1', sessionId: 's-wb', timestamp: '2026-09-01T10:00:00.000Z',
+ }),
+ JSON.stringify({
+ parentUuid: 'u-1', isSidechain: false, type: 'assistant',
+ message: { role: 'assistant', content: [{ type: 'tool_use', id: 'tool-1', name: 'Read', input: { file_path: '/tmp/a' } }] },
+ uuid: 'a-1', sessionId: 's-wb', timestamp: '2026-09-01T10:00:01.000Z',
+ }),
+ JSON.stringify({
+ parentUuid: 'a-1', isSidechain: false, type: 'user',
+ message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'tool-1', content: 'x'.repeat(resultChars) }] },
+ uuid: 'u-tool-1', sessionId: 's-wb', timestamp: '2026-09-01T10:00:02.000Z',
+ }),
+ JSON.stringify({
+ parentUuid: 'u-tool-1', isSidechain: false, type: 'assistant',
+ message: { role: 'assistant', content: [{ type: 'text', text: 'Done — noted.' }] },
+ uuid: 'a-2', sessionId: 's-wb', timestamp: '2026-09-01T10:00:03.000Z',
+ }),
+ ];
+ writeFileSync(p, lines.join('\n') + '\n');
+ return { path: p, root };
+}
+
const io = { write: () => {} };
async function wbHeartbeats() {
@@ -129,6 +159,32 @@ describe('hook stop — ambient writeback banking', () => {
expect((await wbHeartbeats())[0]?.reason).toBe('no_user_turn');
});
+ test('tool_result user entries do not shadow the genuine user prompt', async () => {
+ writeConfig({ writeback: 'salient' });
+ const prompt = 'I prefer dark mode in every editor, and I want weekly summaries.';
+ const t = writeTranscriptWithToolResult(prompt, 20);
+ expect(await runHook(['stop'], {
+ ...io, transcriptRoot: t.root,
+ stdin: JSON.stringify({ session_id: 's-wb', transcript_path: t.path }),
+ })).toBe(0);
+ const file = readdirSync(corpus()).find((f) => /^s-wb\.wb-[0-9a-f]{24}\.txt$/.test(f));
+ expect(file).toBeDefined();
+ expect(await Bun.file(join(corpus(), file!)).text()).toBe(prompt + '\n');
+ });
+
+ test('tool_result beyond the cheap tail triggers the wide retry for the genuine prompt', async () => {
+ writeConfig({ writeback: 'salient' });
+ const prompt = 'I prefer dark mode in every editor, and I want weekly summaries.';
+ const t = writeTranscriptWithToolResult(prompt, 140_000);
+ expect(await runHook(['stop'], {
+ ...io, transcriptRoot: t.root,
+ stdin: JSON.stringify({ session_id: 's-wb', transcript_path: t.path }),
+ })).toBe(0);
+ const file = readdirSync(corpus()).find((f) => /^s-wb\.wb-[0-9a-f]{24}\.txt$/.test(f));
+ expect(file).toBeDefined();
+ expect(await Bun.file(join(corpus(), file!)).text()).toBe(prompt + '\n');
+ });
+
test('user turn pushed past the 128KB tail by ONE huge assistant payload: wide retry finds it — banked, NOT no_user_turn', async () => {
writeConfig({ writeback: 'salient' });
// The assistant turn between the last user turn and EOF exceeds
diff --git a/test/hybrid-search-single-mode-read.serial.test.ts b/test/hybrid-search-single-mode-read.serial.test.ts
new file mode 100644
index 0000000000..a354d695dc
--- /dev/null
+++ b/test/hybrid-search-single-mode-read.serial.test.ts
@@ -0,0 +1,158 @@
+/**
+ * #4359 — hybridSearchCached() and the bare hybridSearch() it calls on a
+ * miss/disabled outcome each independently call `loadSearchModeConfig(engine)`
+ * (mode.ts). That's a second DB-plane config round trip on every
+ * `hybridSearchCached` call, AND — if `search.mode` / `search.searchLimit` /
+ * another per-key override changes between the two reads — a desync: the
+ * cache row gets keyed (`knobsHash`) from the outer (stale) config read while
+ * its actual size/contents come from the inner (newer) read.
+ *
+ * Context (checked before writing these tests, per the coordinator's note):
+ * `semanticResultCacheAvailable()` (query-cache.ts) is hardcoded `false` right
+ * now, so `hybridSearchCached` never actually reads a HIT or writes a cache
+ * row in this repo's current state — every call takes the miss/disabled
+ * branch. That does NOT make the double config read moot: both reads happen
+ * unconditionally, at the top of each function, regardless of whether the
+ * semantic result cache itself is live. These tests exercise ONLY the
+ * miss/disabled path (no cache HIT, no cache row write) and pin the read
+ * count directly — they do not depend on the cache being enabled, and they
+ * stay meaningful once it's turned back on (that's exactly when the desync
+ * this fix closes becomes observable again).
+ *
+ * Seam: `loadSearchModeConfig` itself, module-mocked so the count and the
+ * returned snapshot are fully decoupled from the OTHER config reads
+ * `hybridSearch`/`hybridSearchCached` also perform (loadConfigWithEngine for
+ * the embedding column, loadEngineIntentPatterns, loadCacheConfig, ...) —
+ * none of those are part of this bug or this fix.
+ */
+
+import { afterAll, afterEach, beforeAll, describe, expect, mock, test } from 'bun:test';
+import * as realMode from '../src/core/search/mode.ts';
+import type { ResolveSearchModeInput } from '../src/core/search/mode.ts';
+
+// Capture the REAL function reference before mock.module runs. `realMode` is
+// a live ES module namespace object — once mock.module replaces the module
+// registry entry for this specifier, `realMode.loadSearchModeConfig` (looked
+// up by property access at call time) resolves to the MOCK, not the
+// original, and calling through it from inside the mock recurses forever.
+// The captured local binding is a plain function reference, unaffected by
+// later mutation of the namespace object's properties.
+const originalLoadSearchModeConfig = realMode.loadSearchModeConfig;
+
+let loadSearchModeConfigCallCount = 0;
+/** When set, `loadSearchModeConfig` returns entries from this list by call
+ * index (clamped to the last entry) instead of delegating to the real
+ * engine read — lets a test simulate a config value that CHANGES between
+ * reads without needing a real config table mutation mid-request. */
+let overrideSequence: ResolveSearchModeInput[] | null = null;
+
+mock.module('../src/core/search/mode.ts', () => ({
+ ...realMode,
+ loadSearchModeConfig: async (engine: Parameters<typeof realMode.loadSearchModeConfig>[0]) => {
+ const callIndex = loadSearchModeConfigCallCount;
+ loadSearchModeConfigCallCount++;
+ if (overrideSequence) {
+ const idx = Math.min(callIndex, overrideSequence.length - 1);
+ return overrideSequence[idx];
+ }
+ return originalLoadSearchModeConfig(engine);
+ },
+}));
+
+// Import AFTER mocking (Bun resolves both static and dynamic `import()` of a
+// mocked specifier to the mock — hybrid.ts's `await import('./mode.ts')`
+// call sites pick this up too).
+const { hybridSearch, hybridSearchCached } = await import('../src/core/search/hybrid.ts');
+const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');
+
+let engine: InstanceType<typeof PGLiteEngine>;
+const savedKey = process.env.OPENAI_API_KEY;
+const KEYWORD = 'gbrain4359singlemoderead';
+const PAGE_COUNT = 15;
+
+beforeAll(async () => {
+ // Force keyword-only fallback (no embedding provider) — cache lookup is
+ // already unconditionally skipped by semanticResultCacheAvailable()===false
+ // (see file header), so this just keeps the fixture simple/fast; it is not
+ // load-bearing for the discrimination itself.
+ delete process.env.OPENAI_API_KEY;
+
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+
+ for (let i = 0; i < PAGE_COUNT; i++) {
+ const slug = `widgets/${i}`;
+ const truth = `${KEYWORD} entry number ${i}, a widget.`;
+ await engine.putPage(slug, { type: 'note', title: `Widget ${i}`, compiled_truth: truth });
+ await engine.upsertChunks(slug, [
+ { chunk_index: 0, chunk_text: truth, chunk_source: 'compiled_truth' },
+ ]);
+ }
+});
+
+afterAll(async () => {
+ // Restore exactly what was there — an initial empty string must come back
+ // as an empty string, not be dropped (savedKey === '' is falsy).
+ if (savedKey !== undefined) process.env.OPENAI_API_KEY = savedKey;
+ try { await engine.disconnect(); } catch { /* ignore */ }
+ // Put the real loader back so a combined (non-serial) bun test run that
+ // loads this file first does not hand the counting mock to later files.
+ // `realMode` is the live namespace whose `loadSearchModeConfig` now
+ // resolves to the mock, so re-registering the namespace alone would NOT
+ // restore it — the captured original function reference must be spliced in.
+ mock.module('../src/core/search/mode.ts', () => ({
+ ...realMode,
+ loadSearchModeConfig: originalLoadSearchModeConfig,
+ }));
+});
+
+afterEach(() => {
+ loadSearchModeConfigCallCount = 0;
+ overrideSequence = null;
+});
+
+describe('#4359 — one search-mode config read per hybridSearchCached call', () => {
+ test('cache miss/disabled through hybridSearchCached loads search-mode config exactly once', async () => {
+ const results = await hybridSearchCached(engine, KEYWORD, {
+ limit: 5,
+ autocut: false,
+ relationalRetrieval: false,
+ });
+ expect(results.length).toBeGreaterThan(0);
+ expect(loadSearchModeConfigCallCount).toBe(1);
+ });
+
+ test('bare hybridSearch (no internal field) still loads its own config exactly once — regression guard for direct callers (eval replay / eval-longmemeval / ops)', async () => {
+ const results = await hybridSearch(engine, KEYWORD, {
+ limit: 5,
+ autocut: false,
+ relationalRetrieval: false,
+ });
+ expect(results.length).toBeGreaterThan(0);
+ expect(loadSearchModeConfigCallCount).toBe(1);
+ });
+
+ test('desync guard: the cache-key resolution and the actual returned result set agree on the SAME config snapshot, even when the underlying config changes mid-request', async () => {
+ // Simulates `search.searchLimit` changing between hybridSearchCached's
+ // own read (used to build knobsHash / the HIT-path limit) and whatever
+ // read the inner hybridSearch performs: call #1 (whichever site makes
+ // it first) sees searchLimit=3, call #2 (if one happens) sees
+ // searchLimit=9. Pre-fix, hybridSearchCached reads once (call #1, limit
+ // 3 — what the cache key would reflect) and the inner hybridSearch it
+ // calls on the miss reads AGAIN independently (call #2, limit 9 — what
+ // actually gets sliced and returned/would-be-cached), producing a
+ // request whose returned result count doesn't match its own cache-key
+ // resolution. Post-fix there is only ever ONE read (limit 3, threaded
+ // into the inner call), so the returned count always agrees with it.
+ overrideSequence = [
+ { mode: 'conservative', overrides: { searchLimit: 3 } },
+ { mode: 'conservative', overrides: { searchLimit: 9 } },
+ ];
+ const results = await hybridSearchCached(engine, KEYWORD, {
+ autocut: false,
+ relationalRetrieval: false,
+ });
+ expect(results.length).toBe(3);
+ });
+});
diff --git a/test/import-source-id.test.ts b/test/import-source-id.test.ts
index 545a8875b3..3be412548d 100644
--- a/test/import-source-id.test.ts
+++ b/test/import-source-id.test.ts
@@ -81,6 +81,35 @@ describe('import --source-id (#1167)', () => {
}
});
+ // The --json payload reports counts; without a destination field a caller
+ // (gstack's memory-ingest is the one in tree — see
+ // test/import-json-stdout.serial.test.ts) cannot tell a routed import from
+ // one that fell through the resolver to `default`. Both directions are
+ // pinned so the field can't be "fixed" by hardcoding either answer.
+ async function importPayload(args: string[]): Promise<Record<string, unknown>> {
+ const lines: string[] = [];
+ const origLog = console.log;
+ console.log = (...a: unknown[]) => { lines.push(a.join(' ')); };
+ try {
+ await runImport(engine, args);
+ } finally {
+ console.log = origLog;
+ }
+ const jsonLine = lines.find((l) => l.trimStart().startsWith('{'));
+ expect(jsonLine).toBeDefined();
+ return JSON.parse(jsonLine!) as Record<string, unknown>;
+ }
+
+ test('--json payload names default as the destination when unrouted', async () => {
+ const payload = await importPayload([scratchDir, '--no-embed', '--json']);
+ expect(payload.source_id).toBe('default');
+ });
+
+ test('--json payload names the routed source', async () => {
+ const payload = await importPayload([scratchDir, '--source-id', 'dept-x', '--no-embed', '--json']);
+ expect(payload.source_id).toBe('dept-x');
+ });
+
test('--source-id value is NOT treated as a positional dir arg', async () => {
// Regression: flag-value-as-dirArg was a real bug class in early
// CLI parsers. Pre-fix the parser at line 82-83 would have
diff --git a/test/import-source-path-refresh.test.ts b/test/import-source-path-refresh.test.ts
new file mode 100644
index 0000000000..1c3c5e4eb4
--- /dev/null
+++ b/test/import-source-path-refresh.test.ts
@@ -0,0 +1,202 @@
+/**
+ * #4588 — the import SKIP path refreshes `pages.source_path`.
+ *
+ * A row whose slug moved before the sync rename repair existed keeps a
+ * source_path naming the OLD file. Write-through prefers source_path, so every
+ * later write recreates the old directory, and the full-sync reconcile reads
+ * the stale path as "file removed". The changed-content import path already
+ * heals this through putPage's COALESCE; the unchanged-content skip (the
+ * common case on every re-sync) used to discard the real path handed in by
+ * importFile. Both skip branches — the canonical hash short-circuit and the
+ * #3694 legacy-hash reconcile — must now write it.
+ *
+ * Pre-landing review (performance): the heal must NOT cost a statement per
+ * UNCHANGED file. A 20k-file tree re-synced with nothing changed used to issue
+ * 20k zero-row UPDATEs (each still firing the statement-level generation-clock
+ * trigger). getPage now projects `source_path`, so the skip path compares the
+ * stored path first and only issues the UPDATE when it actually differs.
+ */
+
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { parseMarkdown } from '../src/core/markdown.ts';
+import { contentHashLegacy } from '../src/core/utils.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+const SLUG = 'people/alpha';
+const REAL_PATH = 'people/alpha.md';
+const STALE_PATH = 'people/old.md';
+const BODY = ['---', 'type: person', 'title: Alpha', '---', '', 'Alpha is a person.'].join('\n');
+
+type ImportOpts = Parameters<typeof importFromContent>[3];
+
+async function sourcePathOf(slug: string, sourceId = 'default'): Promise<string | null> {
+ const rows = await engine.executeRaw<{ source_path: string | null }>(
+ `SELECT source_path FROM pages WHERE source_id = $2 AND slug = $1 AND deleted_at IS NULL`,
+ [slug, sourceId],
+ );
+ expect(rows).toHaveLength(1);
+ return rows[0].source_path;
+}
+
+async function driftTo(slug: string, stalePath: string, sourceId = 'default'): Promise<void> {
+ await engine.executeRaw(
+ `UPDATE pages SET source_path = $1 WHERE source_id = $3 AND slug = $2`,
+ [stalePath, slug, sourceId],
+ );
+ expect(await sourcePathOf(slug, sourceId)).toBe(stalePath);
+}
+
+/**
+ * Run one import while counting the skip path's `UPDATE pages SET source_path`
+ * statements. The spy shadows the prototype method on the instance for the
+ * duration of the call only, so the drift/readback helpers above never count.
+ */
+async function importCountingRefreshes(slug: string, body: string, opts: ImportOpts) {
+ const orig = engine.executeRaw.bind(engine);
+ const updates: string[] = [];
+ Object.defineProperty(engine, 'executeRaw', {
+ configurable: true,
+ value: (sql: string, params?: unknown[]) => {
+ if (/UPDATE pages SET source_path/.test(sql)) updates.push(sql);
+ return orig(sql, params);
+ },
+ });
+ try {
+ const result = await importFromContent(engine, slug, body, opts);
+ return { result, updates };
+ } finally {
+ Reflect.deleteProperty(engine, 'executeRaw');
+ }
+}
+
+function legacyHashOf(body: string, slug: string): string {
+ const parsed = parseMarkdown(body, `${slug}.md`);
+ return contentHashLegacy({
+ title: parsed.title,
+ type: parsed.type as never,
+ compiled_truth: parsed.compiled_truth,
+ timeline: parsed.timeline,
+ frontmatter: parsed.frontmatter,
+ });
+}
+
+describe('#4588 import skip path refreshes a drifted source_path', () => {
+ test('hash-equal skip rewrites source_path to the path the file really lives at', async () => {
+ const first = await importFromContent(engine, SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH });
+ expect(first.status).toBe('imported');
+ expect(await sourcePathOf(SLUG)).toBe(REAL_PATH);
+
+ await driftTo(SLUG, STALE_PATH);
+
+ const { result: again, updates } = await importCountingRefreshes(SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH });
+ expect(again.status).toBe('skipped');
+ // pre-fix: still 'people/old.md' — the skip returned before any write.
+ expect(await sourcePathOf(SLUG)).toBe(REAL_PATH);
+ // A real drift costs exactly one statement.
+ expect(updates).toHaveLength(1);
+ });
+
+ test('#3694 legacy-hash skip rewrites source_path too', async () => {
+ await importFromContent(engine, SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH });
+ const legacy = legacyHashOf(BODY, SLUG);
+ await engine.executeRaw(
+ `UPDATE pages SET content_hash = $1 WHERE source_id = 'default' AND slug = $2`,
+ [legacy, SLUG],
+ );
+ await driftTo(SLUG, STALE_PATH);
+
+ const { result: again, updates } = await importCountingRefreshes(SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH });
+ expect(again.status).toBe('skipped');
+ expect(await sourcePathOf(SLUG)).toBe(REAL_PATH);
+ expect(updates).toHaveLength(1);
+ // The legacy branch still reconciled the hash (fast path next time).
+ const row = await engine.getPage(SLUG, { sourceId: 'default' });
+ expect(row!.content_hash).not.toBe(legacy);
+ });
+
+ test('a skip without sourcePath (put_page / capture lane) leaves source_path alone', async () => {
+ await importFromContent(engine, SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH });
+ const { result: again, updates } = await importCountingRefreshes(SLUG, BODY, { noEmbed: true });
+ expect(again.status).toBe('skipped');
+ expect(await sourcePathOf(SLUG)).toBe(REAL_PATH);
+ expect(updates).toHaveLength(0);
+ });
+});
+
+describe('the refresh is skipped entirely when the stored source_path already matches (pre-landing review)', () => {
+ test('hash-equal skip of an unchanged file issues NO source_path UPDATE', async () => {
+ await importFromContent(engine, SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH });
+
+ const { result: again, updates } = await importCountingRefreshes(SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH });
+ expect(again.status).toBe('skipped');
+ // pre-fix: one zero-row UPDATE per unchanged file (20k statements on a
+ // 20k-file unchanged tree, each firing the generation-clock trigger).
+ expect(updates).toHaveLength(0);
+ expect(await sourcePathOf(SLUG)).toBe(REAL_PATH);
+ });
+
+ test('#3694 legacy-hash skip of an unchanged file issues NO source_path UPDATE', async () => {
+ await importFromContent(engine, SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH });
+ const legacy = legacyHashOf(BODY, SLUG);
+ await engine.executeRaw(
+ `UPDATE pages SET content_hash = $1 WHERE source_id = 'default' AND slug = $2`,
+ [legacy, SLUG],
+ );
+
+ const { result: again, updates } = await importCountingRefreshes(SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH });
+ expect(again.status).toBe('skipped');
+ expect(updates).toHaveLength(0);
+ expect(await sourcePathOf(SLUG)).toBe(REAL_PATH);
+ });
+
+ test('same slug in two sources: re-importing default never touches the other source', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('other', 'Other') ON CONFLICT (id) DO NOTHING`);
+ await importFromContent(engine, SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH });
+ await importFromContent(engine, SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH, sourceId: 'other' });
+ // Drift ONLY the other source's row.
+ await driftTo(SLUG, STALE_PATH, 'other');
+
+ const { result: again, updates } = await importCountingRefreshes(SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH });
+ expect(again.status).toBe('skipped');
+ // default already matches → no statement; other is out of scope → untouched.
+ expect(updates).toHaveLength(0);
+ expect(await sourcePathOf(SLUG, 'default')).toBe(REAL_PATH);
+ expect(await sourcePathOf(SLUG, 'other')).toBe(STALE_PATH);
+
+ // The other source heals on ITS OWN import, still without touching default.
+ const other = await importCountingRefreshes(SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH, sourceId: 'other' });
+ expect(other.result.status).toBe('skipped');
+ expect(other.updates).toHaveLength(1);
+ expect(await sourcePathOf(SLUG, 'other')).toBe(REAL_PATH);
+ expect(await sourcePathOf(SLUG, 'default')).toBe(REAL_PATH);
+ });
+
+ test('getPage projects source_path (the short-circuit input) — PGLite', async () => {
+ await importFromContent(engine, SLUG, BODY, { noEmbed: true, sourcePath: REAL_PATH });
+ const page = await engine.getPage(SLUG, { sourceId: 'default' });
+ expect(page!.source_path).toBe(REAL_PATH);
+
+ // Three-state read: a row written without a path reads back null, not undefined.
+ await importFromContent(engine, 'people/beta', BODY.replace('Alpha', 'Beta'), { noEmbed: true });
+ const beta = await engine.getPage('people/beta', { sourceId: 'default' });
+ expect(beta!.source_path).toBeNull();
+ });
+});
diff --git a/test/ingestion/put-page-write-through.test.ts b/test/ingestion/put-page-write-through.test.ts
index 98174613a0..abab21d7d9 100644
--- a/test/ingestion/put-page-write-through.test.ts
+++ b/test/ingestion/put-page-write-through.test.ts
@@ -4,7 +4,7 @@
* Verifies that put_page writes the markdown file to disk alongside the
* DB row when sync.repo_path is configured. Trust gating: subagent
* sandbox writes stay DB-only; dry-run stays DB-only; missing-repo
- * stays DB-only.
+ * stays DB-only, with a loud warning for remote callers.
*/
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
@@ -180,8 +180,22 @@ describe('put_page write-through — config edge cases', () => {
const result = (await putPage.handler(ctx, {
slug: 'inbox/no-repo',
content: '---\ntitle: N\n---\n\nbody',
- })) as { write_through?: { skipped?: string } };
+ })) as { write_through?: { skipped?: string; warning?: string } };
expect(result.write_through?.skipped).toBe('no_repo_configured');
+ expect(result.write_through?.warning).toBeUndefined();
+ });
+
+ test('remote repo not configured → warns that the write is DB-only', async () => {
+ await engine.executeRaw("DELETE FROM config WHERE key = 'sync.repo_path'");
+ const ctx = makeCtx({ remote: true });
+ const result = (await putPage.handler(ctx, {
+ slug: 'inbox/no-repo-remote',
+ content: '---\ntitle: Remote\n---\n\nbody',
+ })) as { write_through?: { skipped?: string; warning?: string } };
+ expect(result.write_through?.skipped).toBe('no_repo_configured');
+ expect(result.write_through?.warning).toContain('wrote only to the database');
+ expect(result.write_through?.warning).toContain("source 'default'");
+ expect(result.write_through?.warning).toContain('no durable markdown file');
});
test('repo path points at a missing directory → put_page rejects, no orphan row', async () => {
diff --git a/test/init-mode-picker.test.ts b/test/init-mode-picker.test.ts
index 3fe7aeb890..e18f86ebd8 100644
--- a/test/init-mode-picker.test.ts
+++ b/test/init-mode-picker.test.ts
@@ -93,6 +93,14 @@ describe('MENU_TEXT cost-matrix anchors (must match CLAUDE.md + methodology doc)
expect(MODE_PICKER_MENU).toContain('corner-to-corner');
});
+ test('does not claim the semantic result cache saves money while it is disabled', async () => {
+ const { MODE_PICKER_MENU } = await import('../src/commands/init-mode-picker.ts');
+ // CLAUDE.md ## Search Mode: "Semantic result caching is temporarily
+ // disabled; budget for fresh retrieval on every query."
+ expect(MODE_PICKER_MENU).not.toContain('semantic cache is free');
+ expect(MODE_PICKER_MENU).toContain('semantic result caching is temporarily disabled');
+ });
+
test('cost matrix lists every cell at the natural diagonal and corners', async () => {
const { MODE_PICKER_MENU } = await import('../src/commands/init-mode-picker.ts');
// Three anchor cells from the natural diagonal at 10K/mo volume. Scales
@@ -119,11 +127,15 @@ describe('MENU_TEXT cost-matrix anchors (must match CLAUDE.md + methodology doc)
expect(MODE_PICKER_MENU).toContain('$5/M');
});
- test('tokenmax Haiku-expansion surcharge is named explicitly', async () => {
+ test('query-verb Haiku-expansion surcharge is named explicitly, not attributed to tokenmax', async () => {
const { MODE_PICKER_MENU } = await import('../src/commands/init-mode-picker.ts');
// Cross-line match — the surcharge phrase can wrap.
- expect(MODE_PICKER_MENU.replace(/\s+/g, ' ')).toContain('~$1.50 per 1K queries');
+ const flat = MODE_PICKER_MENU.replace(/\s+/g, ' ');
+ expect(flat).toContain('gbrain query adds ~$1.50 per 1K queries');
expect(MODE_PICKER_MENU).toContain('Haiku expansion call');
+ // `gbrain query` expands in every mode (#4601); the surcharge is not a tokenmax line item.
+ expect(flat).not.toContain('tokenmax adds');
+ expect(flat).toContain('--no-expand');
});
test('cache-hit discount framing is named', async () => {
diff --git a/test/link-extraction-pack-3190.test.ts b/test/link-extraction-pack-3190.test.ts
index 472b67184a..50d91a81e1 100644
--- a/test/link-extraction-pack-3190.test.ts
+++ b/test/link-extraction-pack-3190.test.ts
@@ -58,9 +58,9 @@ describe('#3190 gate 1 — same-directory markdown links', () => {
expect(refs[0].sameDir).toBe(true);
});
- test('scheme/anchor/dir targets never match the sameDir pass', () => {
+ test('scheme/dir targets never match the sameDir pass; anchors are stripped (#4995)', () => {
expect(extractEntityRefs('[x](https://example.com/a.md)').filter(r => r.sameDir)).toEqual([]);
- expect(extractEntityRefs('[x](beta.md#section)').filter(r => r.sameDir)).toEqual([]);
+ expect(extractEntityRefs('[x](beta.md#section)').filter(r => r.sameDir).map(r => r.slug)).toEqual(['beta']);
// dir-shaped targets belong to pass 1, not the sameDir pass
const dirRefs = extractEntityRefs('[x](people/beta.md)');
expect(dirRefs).toHaveLength(1);
@@ -108,8 +108,8 @@ describe('#3190 gate 1 — same-directory markdown links', () => {
{ skipFrontmatter: true },
);
expect(candidates.map(c => c.targetSlug)).toEqual([slugifyPath('docs/i18n/README.vi')]);
- // Anchors and schemes stay excluded on the ./ arm too.
- expect(extractEntityRefs('[x](./beta.md#section)').filter(r => r.sameDir)).toEqual([]);
+ // Schemes stay excluded on the ./ arm too; anchors are stripped (#4995).
+ expect(extractEntityRefs('[x](./beta.md#section)').filter(r => r.sameDir).map(r => r.slug)).toEqual(['beta']);
expect(extractEntityRefs('[x](./https://example.com/a.md)').filter(r => r.sameDir)).toEqual([]);
});
});
diff --git a/test/link-extraction.test.ts b/test/link-extraction.test.ts
index 54a0975710..e4a1c21b54 100644
--- a/test/link-extraction.test.ts
+++ b/test/link-extraction.test.ts
@@ -61,13 +61,13 @@ describe('extractEntityRefs', () => {
test('extracts filesystem-relative refs ([Name](../people/slug.md))', () => {
const refs = extractEntityRefs('Met with [Alice Chen](../people/alice-chen.md) at the office.');
expect(refs.length).toBe(1);
- expect(refs[0]).toEqual({ name: 'Alice Chen', slug: 'people/alice-chen', dir: 'people', upLevels: 1 });
+ expect(refs[0]).toEqual({ name: 'Alice Chen', slug: 'people/alice-chen', dir: 'people', upLevels: 1, index: 9 });
});
test('extracts engine-style slug refs ([Name](people/slug))', () => {
const refs = extractEntityRefs('See [Alice Chen](people/alice-chen) for context.');
expect(refs.length).toBe(1);
- expect(refs[0]).toEqual({ name: 'Alice Chen', slug: 'people/alice-chen', dir: 'people' });
+ expect(refs[0]).toEqual({ name: 'Alice Chen', slug: 'people/alice-chen', dir: 'people', index: 4 });
});
test('extracts company refs', () => {
@@ -1591,7 +1591,7 @@ describe("extractEntityRefs — v0.18.0 qualified wikilinks", () => {
test("[[gstack:projects/foo|Display Name]] preserves display + sourceId", () => {
const refs = extractEntityRefs("See [[gstack:projects/foo|The Foo Project]] for details.");
expect(refs.length).toBe(1);
- expect(refs[0]).toEqual({ name: "The Foo Project", slug: "projects/foo", dir: "projects", sourceId: "gstack" });
+ expect(refs[0]).toEqual({ name: "The Foo Project", slug: "projects/foo", dir: "projects", sourceId: "gstack", index: 4 });
});
test("qualified source-id format is validated (must match [a-z0-9-]+ kebab rules)", () => {
@@ -2050,6 +2050,133 @@ describe('#4062 — bare [[name]] emits a root-exact direct candidate flag-off',
});
});
+// ─── Role-prior suppression in Timeline / See-also / machine-list sections ─
+//
+// The page-role prior (advisor/employee/partner bio language biasing bare
+// person→company links) must not type list-shaped links inside Timeline or
+// See-also sections — that is what re-minted thousands of unevidenced
+// works_at/advises edges on re-import. Per-edge verbs still win everywhere.
+describe('extractPageLinks — role prior suppressed in Timeline/See-also', () => {
+ // Real entity pages separate the bio from Timeline/See-also by far more
+ // than the 240-char per-edge window; the padding keeps the fixtures from
+ // letting per-edge verb regexes see bio text (that bleed is pre-existing
+ // behavior, not what these tests exercise).
+ const advisorBio =
+ 'Jane is an advisor to several startups and serves as advisor across fintech.\n' +
+ 'Filler context about the neighborhood, the weather, and travel plans. '.repeat(6) + '\n';
+
+ test('advisor bio no longer types a Timeline company link (advises -> mentions)', async () => {
+ const content =
+ advisorBio +
+ '\n## Timeline\n' +
+ '- 2026-05-12 — met with [Acme](companies/acme) about the roadmap\n';
+ const { candidates } = await extractPageLinks('people/jane', content, {}, 'person', allowAllResolver);
+ const acme = candidates.find(c => c.targetSlug === 'companies/acme');
+ expect(acme).toBeDefined();
+ expect(acme!.linkType).toBe('mentions');
+ });
+
+ test('advisor bio still types a prose company link outside those sections', async () => {
+ const content =
+ advisorBio +
+ '\nShe spends most weeks with [Acme](companies/acme) and the broader group.\n' +
+ '\n## Timeline\n- 2026-05-12 — quarterly review\n';
+ const { candidates } = await extractPageLinks('people/jane', content, {}, 'person', allowAllResolver);
+ const acme = candidates.find(c => c.targetSlug === 'companies/acme');
+ expect(acme).toBeDefined();
+ expect(acme!.linkType).toBe('advises');
+ });
+
+ test('per-edge verb inside Timeline still wins over suppression', async () => {
+ const content =
+ advisorBio +
+ '\n## Timeline\n' +
+ '- 2026-05-12 — Jane is an advisor to [Acme](companies/acme) as of this week\n';
+ const { candidates } = await extractPageLinks('people/jane', content, {}, 'person', allowAllResolver);
+ const acme = candidates.find(c => c.targetSlug === 'companies/acme');
+ expect(acme).toBeDefined();
+ expect(acme!.linkType).toBe('advises');
+ });
+
+ test('See-also bare wikilink stays mentions despite employee bio', async () => {
+ const content =
+ 'Jane is a senior engineer at somewhere important.\n' +
+ 'Filler context about the neighborhood, the weather, and travel plans. '.repeat(6) + '\n' +
+ '\n## See also\n- [[companies/acme]]\n';
+ const { candidates } = await extractPageLinks('people/jane', content, {}, 'person', allowAllResolver);
+ const acme = candidates.find(c => c.targetSlug === 'companies/acme');
+ expect(acme).toBeDefined();
+ expect(acme!.linkType).toBe('mentions');
+ });
+
+ test('section ends at the next same-level heading — prior applies again after', async () => {
+ const content =
+ advisorBio +
+ '\n## Timeline\n- 2026-05-12 — planning\n' +
+ '\n## Work\nCurrent focus is [Acme](companies/acme) strategy.\n';
+ const { candidates } = await extractPageLinks('people/jane', content, {}, 'person', allowAllResolver);
+ const acme = candidates.find(c => c.targetSlug === 'companies/acme');
+ expect(acme).toBeDefined();
+ expect(acme!.linkType).toBe('advises');
+ });
+
+ test('a `## Timeline` line inside a fenced code block does not open a suppression range', async () => {
+ // Headings are matched on the code-stripped content (same length-preserving
+ // mask the passes use), so a fence quoting a heading never blanks the
+ // prior for the prose that follows it.
+ const content =
+ advisorBio +
+ '\n```md\n## Timeline\n```\n' +
+ '\nShe spends most weeks with [Acme](companies/acme) and the broader group.\n';
+ const { candidates } = await extractPageLinks('people/jane', content, {}, 'person', allowAllResolver);
+ const acme = candidates.find(c => c.targetSlug === 'companies/acme');
+ expect(acme).toBeDefined();
+ expect(acme!.linkType).toBe('advises');
+ });
+
+ test('machine-list sections (Related / Email mention links) are suppressed too', async () => {
+ const content =
+ 'Jane is an advisor to several startups and serves as advisor across fintech.\n' +
+ 'Filler context about the neighborhood, the weather, and travel plans. '.repeat(6) + '\n' +
+ '\n## Related\n- [[companies/acme]]\n' +
+ '\n## Email mention links\n- mentions [[companies/beta-corp]] — forwarded thread\n';
+ const { candidates } = await extractPageLinks('people/jane', content, {}, 'person', allowAllResolver);
+ for (const t of ['companies/acme', 'companies/beta-corp']) {
+ const c = candidates.find(x => x.targetSlug === t);
+ expect(c).toBeDefined();
+ expect(c!.linkType).toBe('mentions');
+ }
+ });
+
+ // EntityRef.index half: the display text also appears in the bio, so
+ // first-occurrence anchoring (content.indexOf) lands in the bio and its
+ // 'advisor to' verb types the Timeline link even with suppression alone.
+ test('Timeline link to a bio-named entity anchors at the link, not the bio mention', async () => {
+ const content =
+ 'Jane is an advisor to Acme and serves as advisor across fintech.\n' +
+ 'Filler context about the neighborhood, the weather, and travel plans. '.repeat(6) + '\n' +
+ '\n## Timeline\n' +
+ '- 2026-05-12 — met with [Acme](companies/acme) about the roadmap\n';
+ const { candidates } = await extractPageLinks('people/jane', content, {}, 'person', allowAllResolver);
+ const acme = candidates.find(c => c.targetSlug === 'companies/acme');
+ expect(acme).toBeDefined();
+ expect(acme!.linkType).toBe('mentions');
+ });
+
+ // A column-0 tag line (`#links`) is not an ATX heading — it must not open
+ // a suppression span that runs to EOF.
+ test('a `#links` tag line at column 0 does not suppress the prior', async () => {
+ const content =
+ advisorBio +
+ '#links\n' +
+ 'She spends most weeks with [Acme](companies/acme) and the broader group.\n';
+ const { candidates } = await extractPageLinks('people/jane', content, {}, 'person', allowAllResolver);
+ const acme = candidates.find(c => c.targetSlug === 'companies/acme');
+ expect(acme).toBeDefined();
+ expect(acme!.linkType).toBe('advises');
+ });
+});
+
// #4062 lane, #4855 grammar: the flag-off root-exact candidate tried ONLY
// slugifyPath, which keeps stroke letters (`đuc-example`) while a brain that
// synced the folded name lives at `duc-example`. Try both grammars — exact
@@ -2111,3 +2238,48 @@ describe('makeResolver — dir-hint step tries both slug grammars (#4855)', () =
expect(await r.resolve('Đức Example', 'people')).toBe('people/duc-example');
});
});
+
+// #4995: markdown links carrying a `#anchor` either produced an unmatchable
+// slug (pass 1 kept `x.md#anchor` in the slug) or matched nothing (sameDir
+// pass excluded `#`), while every wikilink regex already stripped anchors. A
+// brain that links with anchors had an empty graph. Pass-1 targets are also
+// lowercased: validateSlug stores every slug lowercase on both engines, so a
+// mixed-case candidate could never resolve.
+describe('#4995 — markdown link anchors are stripped, pass-1 targets lowercased', () => {
+ test('pass-1 dir-shaped link drops the anchor and the .md', () => {
+ expect(extractEntityRefs('[D](registry/sessions/tally.md#x)')).toEqual([
+ { name: 'D', slug: 'registry/sessions/tally', dir: 'registry', index: 0 },
+ ]);
+ expect(extractEntityRefs('[D](registry/sessions/tally#x)')[0].slug).toBe('registry/sessions/tally');
+ expect(extractEntityRefs('[D](../registry/tally.md#a b)')[0]).toEqual(
+ { name: 'D', slug: 'registry/tally', dir: 'registry', upLevels: 1, index: 0 },
+ );
+ });
+
+ test('sameDir link drops the anchor (bare and ./ arms)', () => {
+ expect(extractEntityRefs('See [see](b.md#section).').filter(r => r.sameDir)).toEqual([
+ { name: 'see', slug: 'b', dir: '', sameDir: true, index: 4 },
+ ]);
+ const dot = extractEntityRefs('[x](./beta.md#section)').filter(r => r.sameDir);
+ expect(dot).toHaveLength(1);
+ expect(dot[0].slug).toBe('beta');
+ });
+
+ test('extractPageLinks emits the anchored sibling as a candidate', async () => {
+ const { candidates } = await extractPageLinks(
+ 'a', 'See [see](b.md#section).', {}, 'concept', nullResolver, { skipFrontmatter: true },
+ );
+ expect(candidates.map(c => c.targetSlug)).toEqual(['b']);
+ });
+
+ test('extractPageLinks lowercases pass-1 and wikilink targets', async () => {
+ const md = await extractPageLinks(
+ 'x', '[D](registry/DECISIONS.md)', {}, 'concept', nullResolver, { skipFrontmatter: true },
+ );
+ expect(md.candidates.map(c => c.targetSlug)).toEqual(['registry/decisions']);
+ const wiki = await extractPageLinks(
+ 'x', 'See [[people/Alice]].', {}, 'concept', nullResolver, { skipFrontmatter: true, globalBasename: false },
+ );
+ expect(wiki.candidates.map(c => c.targetSlug)).toContain('people/alice');
+ });
+});
diff --git a/test/link-source-check-repair.test.ts b/test/link-source-check-repair.test.ts
new file mode 100644
index 0000000000..3f2354eb9c
--- /dev/null
+++ b/test/link-source-check-repair.test.ts
@@ -0,0 +1,255 @@
+/**
+ * #4613 — links_link_source_check constraint-shape self-heal.
+ *
+ * Repro chain pinned here: a fully-migrated brain (ledger >= v114) whose
+ * `links_link_source_check` reverted to the pre-v114 closed allowlist rejects
+ * every kebab provenance tag ('atom-provenance', 'concept-provenance') while
+ * `runMigrations` sees nothing pending and doctor reports the schema current.
+ * The repair module probes the constraint SHAPE via pg_constraint (same drift
+ * class as #2038 / #550), restores the v114 definition on every migrate pass,
+ * and doctor names the drift.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { readFileSync } from 'fs';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { runMigrations, MIGRATIONS } from '../src/core/migrate.ts';
+import { PGLITE_SCHEMA_SQL } from '../src/core/pglite-schema.ts';
+import {
+ LINK_SOURCE_KEBAB_RE,
+ checkLinkSourceCheck,
+ repairLinkSourceCheck,
+} from '../src/core/link-source-check-repair.ts';
+import { linkSourceCheckConstraintCheck } from '../src/commands/doctor/checks/core-health.ts';
+import { recordingEngine } from './helpers/recording-engine.ts';
+
+let engine: PGLiteEngine;
+
+/** The literal v113 predicate — the drift shape reported in #4613. */
+const V113_ALLOWLIST_DDL =
+ `ALTER TABLE links ADD CONSTRAINT links_link_source_check ` +
+ `CHECK (link_source IS NULL OR link_source IN ('markdown', 'frontmatter', 'manual', 'mentions', 'wikilink-resolved'))`;
+
+/** v114's definition left NOT VALID (an interrupted two-phase Postgres migration). */
+const V114_NOT_VALID_DDL =
+ `ALTER TABLE links ADD CONSTRAINT links_link_source_check ` +
+ `CHECK (link_source IS NULL OR (link_source ~ '${LINK_SOURCE_KEBAB_RE}' AND char_length(link_source) <= 64)) NOT VALID`;
+
+const isDdl = (call: string) => /^(transaction:|runMigration:)|ALTER TABLE/.test(call);
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ // Restore the canonical constraint in case a prior test drifted it.
+ await repairLinkSourceCheck(engine);
+ for (const slug of ['notes/alpha-example', 'notes/beta-example']) {
+ await engine.putPage(slug, {
+ title: slug, type: 'concept', frontmatter: {}, compiled_truth: `body ${slug}`, timeline: '',
+ });
+ }
+});
+
+async function dropConstraint(): Promise<void> {
+ await engine.executeRaw(`ALTER TABLE links DROP CONSTRAINT IF EXISTS links_link_source_check`);
+}
+
+async function driftToV113(): Promise<void> {
+ await dropConstraint();
+ await engine.executeRaw(V113_ALLOWLIST_DDL);
+}
+
+async function addKebabLink(): Promise<void> {
+ await engine.addLinksBatch([{
+ from_slug: 'notes/alpha-example',
+ to_slug: 'notes/beta-example',
+ link_source: 'atom-provenance',
+ from_source_id: 'default',
+ to_source_id: 'default',
+ }]);
+}
+
+async function constraintRow(): Promise<{ def: string; convalidated: boolean } | undefined> {
+ const rows = await engine.executeRaw<{ def: string; convalidated: boolean }>(
+ `SELECT pg_get_constraintdef(oid) AS def, convalidated FROM pg_constraint
+ WHERE conrelid = to_regclass('links') AND conname = 'links_link_source_check'`,
+ );
+ return rows[0];
+}
+
+describe('runMigrations self-heal (#4613)', () => {
+ test('a ledger-current brain with the v113 allowlist heals on a nothing-pending pass', async () => {
+ // Stamp the ledger fully-migrated first (resetPgliteState clears config):
+ // the drift must heal on a NO-PENDING pass.
+ await runMigrations(engine);
+ await driftToV113();
+ await expect(addKebabLink()).rejects.toThrow(/check constraint/i);
+
+ const out = await runMigrations(engine);
+ expect(out.applied).toBe(0); // nothing pending — the self-heal ran anyway
+
+ await addKebabLink();
+ const n = await engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*)::text AS n FROM links WHERE link_source = 'atom-provenance'`,
+ );
+ expect(parseInt(n[0].n, 10)).toBe(1);
+ expect((await constraintRow())?.def).toContain(LINK_SOURCE_KEBAB_RE);
+ });
+
+ test('ledger below v114: the self-heal is skipped and v114 itself installs the gate (no double rewrite)', async () => {
+ // A pre-v114 brain has the v113 allowlist legitimately — the pending loop
+ // replays v114. Running the repair first would rewrite the constraint
+ // twice (and on a pre-v11 brain with no link_source column, print a
+ // spurious self-heal error).
+ await engine.setConfig('version', '113');
+ await driftToV113();
+ const rec = recordingEngine(engine);
+ const out = await runMigrations(rec.engine);
+ expect(out.applied).toBeGreaterThan(0);
+ expect(rec.calls.filter(c => c.includes(`conname = 'links_link_source_check'`))).toEqual([]);
+ const row = await constraintRow();
+ expect(row?.def).toContain(LINK_SOURCE_KEBAB_RE);
+ expect(row?.convalidated).toBe(true);
+ });
+});
+
+describe('checkLinkSourceCheck / repairLinkSourceCheck (#4613)', () => {
+ test('healthy brain: no repair needed, repair is a no-op that leaves the def untouched', async () => {
+ const before = await constraintRow();
+ expect(before?.def).toContain(LINK_SOURCE_KEBAB_RE);
+ const status = await checkLinkSourceCheck(engine);
+ expect(status.tablePresent).toBe(true);
+ expect(status.needsRepair).toBe(false);
+ expect(status.drift).toBeNull();
+
+ const r = await repairLinkSourceCheck(engine);
+ expect(r.reason).toBe('already_correct');
+ expect(r.repaired).toBe(false);
+ expect((await constraintRow())?.def).toBe(before!.def);
+ });
+
+ test('v113 allowlist → drift wrong_def → restored', async () => {
+ await driftToV113();
+ const status = await checkLinkSourceCheck(engine);
+ expect(status.needsRepair).toBe(true);
+ expect(status.drift).toBe('wrong_def');
+
+ const r = await repairLinkSourceCheck(engine);
+ expect(r.reason).toBe('restored');
+ expect(r.repaired).toBe(true);
+ expect((await checkLinkSourceCheck(engine)).needsRepair).toBe(false);
+ expect((await constraintRow())?.convalidated).toBe(true);
+ await addKebabLink();
+ });
+
+ test('absent constraint → drift absent → restored', async () => {
+ await dropConstraint();
+ const status = await checkLinkSourceCheck(engine);
+ expect(status.constraintPresent).toBe(false);
+ expect(status.drift).toBe('absent');
+ expect(status.needsRepair).toBe(true);
+
+ const r = await repairLinkSourceCheck(engine);
+ expect(r.reason).toBe('restored');
+ expect((await constraintRow())?.def).toContain(LINK_SOURCE_KEBAB_RE);
+ });
+
+ test('v114 def left NOT VALID → drift not_validated → restored + validated', async () => {
+ await dropConstraint();
+ await engine.executeRaw(V114_NOT_VALID_DDL);
+ const status = await checkLinkSourceCheck(engine);
+ expect(status.drift).toBe('not_validated');
+ expect(status.needsRepair).toBe(true);
+
+ const r = await repairLinkSourceCheck(engine);
+ expect(r.reason).toBe('restored');
+ expect(r.repaired).toBe(true);
+ const row = await constraintRow();
+ expect(row?.def).toContain(LINK_SOURCE_KEBAB_RE);
+ expect(row?.convalidated).toBe(true);
+ expect((await checkLinkSourceCheck(engine)).needsRepair).toBe(false);
+ });
+
+ test('pre-existing violating rows: repair refuses loudly WITHOUT attempting any DDL', async () => {
+ await dropConstraint();
+ await engine.executeRaw(
+ `INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source)
+ SELECT a.id, b.id, '', '', 'BAD_TAG' FROM pages a, pages b
+ WHERE a.slug = 'notes/alpha-example' AND b.slug = 'notes/beta-example'`,
+ );
+ const rec = recordingEngine(engine);
+ const r = await repairLinkSourceCheck(rec.engine);
+ expect(r.reason).toBe('violations');
+ expect(r.repaired).toBe(false);
+ expect(r.violations).toBe(1);
+ // Violators are probed FIRST: no transaction, no ALTER TABLE — on Postgres
+ // a failing ADD would otherwise take ACCESS EXCLUSIVE + a full scan on
+ // every engine open until a human edits rows.
+ expect(rec.calls.filter(isDdl)).toEqual([]);
+ expect(await constraintRow()).toBeUndefined();
+ expect((await checkLinkSourceCheck(engine)).drift).toBe('absent');
+ });
+});
+
+describe('doctor links_link_source_check (#4613)', () => {
+ test('ok on a healthy brain', async () => {
+ const check = await linkSourceCheckConstraintCheck(engine);
+ expect(check.name).toBe('links_link_source_check');
+ expect(check.status).toBe('ok');
+ });
+
+ test('fail when the def lacks the kebab regex (kebab writes are rejected)', async () => {
+ await driftToV113();
+ const check = await linkSourceCheckConstraintCheck(engine);
+ expect(check.status).toBe('fail');
+ expect(check.message).toContain('atom-provenance');
+ expect(check.message).toContain('gbrain apply-migrations --yes');
+ });
+
+ test('warn (not fail) when the constraint is absent — writes still succeed', async () => {
+ await dropConstraint();
+ const check = await linkSourceCheckConstraintCheck(engine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('absent');
+ await addKebabLink(); // no gate → the write goes through
+ });
+
+ test('warn (not fail) when the constraint is NOT VALID — the gate is live, only old rows are unchecked', async () => {
+ await dropConstraint();
+ await engine.executeRaw(V114_NOT_VALID_DDL);
+ const check = await linkSourceCheckConstraintCheck(engine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('NOT VALID');
+ await addKebabLink(); // the kebab gate accepts kebab writes even while NOT VALID
+ });
+
+ test('warn on a probe error, never a false ok', async () => {
+ const broken = { executeRaw: async () => { throw new Error('boom'); } } as unknown as PGLiteEngine;
+ const check = await linkSourceCheckConstraintCheck(broken);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('Could not check');
+ });
+});
+
+describe('regex literal drift guard (#4613)', () => {
+ test('LINK_SOURCE_KEBAB_RE matches migration v114, pglite-schema.ts and schema.sql verbatim', () => {
+ const m = MIGRATIONS.find(x => x.version === 114)!;
+ expect(m.name).toBe('links_link_source_check_kebab_regex');
+ const needle = `link_source ~ '${LINK_SOURCE_KEBAB_RE}'`;
+ expect(m.sqlFor!.pglite!).toContain(needle);
+ expect(m.sqlFor!.postgres!).toContain(needle);
+ expect(PGLITE_SCHEMA_SQL).toContain(needle);
+ const schemaSql = readFileSync(join(import.meta.dir, '..', 'src', 'schema.sql'), 'utf8');
+ expect(schemaSql).toContain(needle);
+ });
+});
diff --git a/test/loadConfig-merge.test.ts b/test/loadConfig-merge.test.ts
index ff7c8dd4e0..387d9b4ae8 100644
--- a/test/loadConfig-merge.test.ts
+++ b/test/loadConfig-merge.test.ts
@@ -7,6 +7,7 @@
import { describe, expect, test } from 'bun:test';
import { loadConfigWithEngine, DB_MERGED_PROVIDER_KEY_FIELDS, type GBrainConfig } from '../src/core/config.ts';
import { FILE_PLANE_API_KEYS } from '../src/commands/config.ts';
+import { adaptiveReturnFromConfig } from '../src/core/search/return-policy.ts';
interface FakeEngine {
getConfig(key: string): Promise<string | null | undefined>;
@@ -660,3 +661,55 @@ describe('loadConfigWithEngine (Phase 4 / F3)', () => {
});
});
});
+
+// #4605 — `search.adaptive_return*` are registered DB-plane keys (E5a) and the
+// 0.48.0.0 notes call them "now a real knob", but loadConfigWithEngine never
+// nested a search.* row, and hybrid.ts feeds adaptiveReturnFromConfig(cfg)
+// with THIS merged object — so `gbrain config set search.adaptive_return true`
+// was accepted, stored, echoed by `config get`, and never read. Same class and
+// same shape as the #1475 eval.* merge above (strict bool, file > DB, no
+// spurious container).
+describe('search.adaptive_return* DB-plane merge (#4605)', () => {
+ test('DB rows reach adaptiveReturnFromConfig', async () => {
+ const engine = makeEngine({
+ 'search.adaptive_return': 'true',
+ 'search.adaptive_return_entity_max': '1',
+ 'search.adaptive_return_other_max': '7',
+ 'search.adaptive_return_min_keep': '2',
+ });
+ const merged = await loadConfigWithEngine(engine, { engine: 'pglite' });
+ expect(adaptiveReturnFromConfig(merged as Record<string, unknown> | null)).toEqual({
+ enabled: true,
+ entityMax: 1,
+ otherMax: 7,
+ minKeep: 2,
+ });
+ });
+
+ test('false reaches the runtime too (explicit opt-out), and the caps merge independently', async () => {
+ const merged = await loadConfigWithEngine(
+ makeEngine({ 'search.adaptive_return': 'false', 'search.adaptive_return_entity_max': '3' }),
+ { engine: 'pglite' },
+ );
+ expect(merged?.search).toEqual({ adaptive_return: false, adaptive_return_entity_max: 3 });
+ });
+
+ test('file plane wins over DB', async () => {
+ const base: GBrainConfig = { engine: 'pglite', search: { adaptive_return: false, adaptive_return_entity_max: 9 } };
+ const merged = await loadConfigWithEngine(
+ makeEngine({ 'search.adaptive_return': 'true', 'search.adaptive_return_entity_max': '1' }),
+ base,
+ );
+ expect(merged?.search).toEqual({ adaptive_return: false, adaptive_return_entity_max: 9 });
+ });
+
+ test('unrecognised bool / non-numeric cap are treated as unset; no keys → no container', async () => {
+ const junk = await loadConfigWithEngine(
+ makeEngine({ 'search.adaptive_return': 'TRUE', 'search.adaptive_return_other_max': 'lots' }),
+ { engine: 'pglite' },
+ );
+ expect(junk?.search).toBeUndefined();
+ const none = await loadConfigWithEngine(makeEngine({ embedding_multimodal: 'true' }), { engine: 'pglite' });
+ expect(none?.search).toBeUndefined();
+ });
+});
diff --git a/test/maintain.test.ts b/test/maintain.test.ts
index 0db805a872..b8d387518e 100644
--- a/test/maintain.test.ts
+++ b/test/maintain.test.ts
@@ -1,9 +1,15 @@
-import { describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import {
extractCycleFreshnessSourceIds,
parseMaintainArgs,
+ runMaintain,
} from '../src/commands/maintain.ts';
import type { Check } from '../src/commands/doctor.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { withEnv } from './helpers/with-env.ts';
describe('maintain args', () => {
test('defaults to dry-run unless --safe is explicit', () => {
@@ -60,3 +66,38 @@ describe('cycle freshness source extraction', () => {
expect(extractCycleFreshnessSourceIds(checks)).toEqual([]);
});
});
+
+// `gbrain maintain --json` owns the report: every embedded helper it runs must
+// stay off stdout, or the JSON document is no longer parseable by the caller.
+describe('runMaintain --json keeps stdout a single JSON document', () => {
+ let engine: PGLiteEngine;
+ let home: string;
+
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-maintain-json-'));
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+
+ afterAll(async () => {
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ test('the stale-extraction summary does not leak onto stdout in json mode', async () => {
+ await engine.putPage('companies/acme', { type: 'company', title: 'Acme', compiled_truth: 'Acme builds widgets.' });
+ await engine.putPage('people/alice', { type: 'person', title: 'Alice', compiled_truth: 'Alice met [Acme](companies/acme) last week.' });
+ await engine.executeRaw(`UPDATE pages SET links_extracted_at = NULL`);
+
+ const out: string[] = [];
+ const spy = spyOn(console, 'log').mockImplementation((...args: unknown[]) => { out.push(args.map(String).join(' ')); });
+ try {
+ await withEnv({ GBRAIN_HOME: home }, () => runMaintain(engine, ['--safe', '--json']));
+ } finally {
+ spy.mockRestore();
+ }
+ const report = JSON.parse(out.join('\n')) as { actions: Array<{ name: string; status: string }> };
+ expect(report.actions.some((a) => a.name === 'extract_stale' && a.status === 'applied')).toBe(true);
+ });
+});
diff --git a/test/mcp-registration-blocks.test.ts b/test/mcp-registration-blocks.test.ts
index 0b9b243483..3a2cd5fb60 100644
--- a/test/mcp-registration-blocks.test.ts
+++ b/test/mcp-registration-blocks.test.ts
@@ -9,9 +9,29 @@
*/
import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'fs';
+import { dirname, join } from 'path';
import { OAUTH_SECRET_NOTE, openclawThinClientBlock } from '../src/core/mcp-registration.ts';
import { OAUTH_SECRET_NOTE as CONNECT_REEXPORTED_NOTE } from '../src/commands/connect.ts';
+const ROOT = dirname(import.meta.dir);
+
+describe('OpenClaw stdio registration docs (#4842)', () => {
+ // OpenClaw 2026.8.x reads ~/.openclaw/openclaw.json `mcp.servers`, never
+ // ~/.openclaw/config.json `mcpServers`; the supported wiring is the CLI.
+ const openclawDoc = readFileSync(join(ROOT, 'docs/mcp/OPENCLAW.md'), 'utf8');
+ const readme = readFileSync(join(ROOT, 'README.md'), 'utf8');
+
+ test('no doc prescribes the retired ~/.openclaw/config.json path', () => {
+ expect(openclawDoc).not.toMatch(/~\/\.openclaw\/config\.json/);
+ expect(readme).not.toMatch(/~\/\.openclaw\/config\.json/);
+ });
+
+ test('OPENCLAW.md registers via the openclaw mcp CLI', () => {
+ expect(openclawDoc).toContain('openclaw mcp add');
+ });
+});
+
const OPTS = {
issuerUrl: 'https://brain.example.com',
mcpUrl: 'https://brain.example.com/mcp',
diff --git a/test/mcp-tool-defs.test.ts b/test/mcp-tool-defs.test.ts
index a657ffd160..9d46ac8db8 100644
--- a/test/mcp-tool-defs.test.ts
+++ b/test/mcp-tool-defs.test.ts
@@ -139,6 +139,27 @@ describe('buildToolDefs', () => {
expect(GBRAIN_MCP_INSTRUCTIONS).toContain(phrase);
}
});
+
+ test('delete_page / restore_page descriptions disclose the on-disk file side effect (#4829)', async () => {
+ // delete_page unlinks the page's markdown file from the source working tree
+ // (#4022, so a sync can't resurrect it) and restore_page re-renders it.
+ // op.description is the single home for the MCP tool def, `gbrain delete
+ // --help`, and the TOOL_CATALOG cell (first sentence only) — so the side
+ // effect must be in the description AND lead it.
+ const { firstSentence } = await import('../src/mcp/tool-catalog.ts');
+ const defs = buildToolDefs(operations);
+ const del = defs.find(def => def.name === 'delete_page');
+ const restore = defs.find(def => def.name === 'restore_page');
+ expect(del).toBeDefined();
+ expect(restore).toBeDefined();
+
+ expect(del!.description).toMatch(/markdown file/);
+ expect(del!.description).toContain('local_path');
+ expect(del!.description).toContain('restore_page');
+ expect(firstSentence(del!.description)).toMatch(/\bfile\b/);
+
+ expect(restore!.description).toMatch(/\bfile\b/);
+ });
});
// ---------------------------------------------------------------------------
diff --git a/test/ollama-recipe.test.ts b/test/ollama-recipe.test.ts
index 7dfb12fa7c..b8f4a67861 100644
--- a/test/ollama-recipe.test.ts
+++ b/test/ollama-recipe.test.ts
@@ -29,12 +29,15 @@ describe('Ollama recipe — chat touchpoint', () => {
}
});
- test('local chat models advertise no hosted-only capabilities', () => {
- // Local Ollama chat serves plain completions; the gateway must not route
- // tool-use / subagent / structured-output work here.
+ test('local chat models advertise no tool-loop capabilities but do declare structured outputs', () => {
+ // Local Ollama chat serves plain completions; tool support varies by the
+ // loaded model, so the gateway must not route tool-use / subagent work
+ // here. Structured output is different: Ollama enforces json_schema
+ // server-side (grammar-constrained decoding since 0.5, model-independent),
+ // so the recipe declares it and chat()/expand() may send a schema (#4863).
const tp = getRecipe('ollama')!.touchpoints.chat!;
expect(tp.supports_tools).toBe(false);
expect(tp.supports_subagent_loop).toBe(false);
- expect(tp.supports_structured_outputs).toBe(false);
+ expect(tp.supports_structured_outputs).toBe(true);
});
});
diff --git a/test/operations-schema-pack.test.ts b/test/operations-schema-pack.test.ts
index 7524019747..9e5574ea42 100644
--- a/test/operations-schema-pack.test.ts
+++ b/test/operations-schema-pack.test.ts
@@ -417,3 +417,77 @@ describe('reload_schema_pack', () => {
expect(result.invalidated).toContain('foo');
});
});
+
+// ── #4653: DB-plane schema_pack (tier 4) honored by every inspection op ─
+
+describe('#4653 inspection ops honor the DB-plane schema_pack tier', () => {
+ // `tweet` is declared ONLY in gbrain-base-v2 — the discriminator between
+ // "resolved through the DB tier" and "fell through to the default".
+ it('schema_explain_type resolves a type declared only in the DB-configured pack', async () => {
+ await withEnv({ GBRAIN_HOME: tmpDir, GBRAIN_SCHEMA_PACK: undefined }, async () => {
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ const result = await operationsByName.schema_explain_type!.handler(ctxOf(), { type: 'tweet' }) as Record<string, unknown>;
+ expect(result.error).toBeUndefined();
+ expect(result.pack).toBe('gbrain-base-v2');
+ });
+ });
+
+ it('schema_graph reports the DB-configured pack', async () => {
+ await withEnv({ GBRAIN_HOME: tmpDir, GBRAIN_SCHEMA_PACK: undefined }, async () => {
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ const result = await operationsByName.schema_graph!.handler(ctxOf(), {}) as Record<string, unknown>;
+ expect(result.pack).toBe('gbrain-base-v2');
+ });
+ });
+
+ it('get_active_schema_pack and schema_graph agree on the same ctx (no split resolution)', async () => {
+ await withEnv({ GBRAIN_HOME: tmpDir, GBRAIN_SCHEMA_PACK: undefined }, async () => {
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ const ctx = ctxOf();
+ const active = await operationsByName.get_active_schema_pack!.handler(ctx, {}) as Record<string, unknown>;
+ const graph = await operationsByName.schema_graph!.handler(ctx, {}) as Record<string, unknown>;
+ expect(active.source_tier).toBe('db-config');
+ expect(graph.pack).toBe(active.pack_name);
+ });
+ });
+
+ it('schema_lint (no pack arg) lints the DB-configured pack', async () => {
+ await withEnv({ GBRAIN_HOME: tmpDir, GBRAIN_SCHEMA_PACK: undefined }, async () => {
+ // A user pack with a deliberate alias_shadows_type error; each LintIssue
+ // names its pack, so the report itself says which pack was linted.
+ // Pre-fix: the bundled gbrain-base is linted instead → clean report.
+ const dir = join(tmpDir, '.gbrain', 'schema-packs', 'lintme');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'pack.yaml'), `api_version: gbrain-schema-pack-v1
+name: lintme
+version: 1.0.0
+description: ""
+gbrain_min_version: 0.38.0
+extends: null
+borrow_from: []
+page_types:
+ - name: person
+ primitive: entity
+ path_prefixes: [people/]
+ aliases: [company]
+ extractable: false
+ expert_routing: false
+ - name: company
+ primitive: entity
+ path_prefixes: [companies/]
+ aliases: []
+ extractable: false
+ expert_routing: false
+link_types: []
+frontmatter_links: []
+takes_kinds: [fact]
+enrichable_types: []
+filing_rules: []
+`, 'utf-8');
+ await engine.setConfig('schema_pack', 'lintme');
+ const result = await operationsByName.schema_lint!.handler(ctxOf(), {}) as { ok: boolean; errors: Array<{ rule: string; pack: string }> };
+ expect(result.ok).toBe(false);
+ expect(result.errors).toContainEqual(expect.objectContaining({ rule: 'alias_shadows_type', pack: 'lintme' }));
+ });
+ });
+});
diff --git a/test/phantom-redirect-engine-parity.test.ts b/test/phantom-redirect-engine-parity.test.ts
index 33b6299a48..040f21ee7c 100644
--- a/test/phantom-redirect-engine-parity.test.ts
+++ b/test/phantom-redirect-engine-parity.test.ts
@@ -209,4 +209,73 @@ describe('migrateFactsToCanonical (parity)', () => {
expect(facts['Expired']).toBe('alice'); // audit trail intact
}
});
+
+ test('#4558 — offsets migrated row_num past canonical MAX so idx_facts_fence_key never collides; NULL stays NULL', async () => {
+ for (const engine of [pglite, pg].filter(Boolean) as BrainEngine[]) {
+ await seed(engine, 'alice', '# alice\n');
+ await seed(engine, 'people/alice-example', '# alice-example\n');
+ // Canonical already owns fence row 1 (the common case: a full-name person
+ // page with a fence vs a bare first-name phantom that also starts at 1).
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, valid_from, source, source_markdown_slug, row_num)
+ VALUES ('default', 'people/alice-example', 'Canonical', 'fact', '2020-01-01'::date, 'm', 'people/alice-example', 1)`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, valid_from, source, source_markdown_slug, row_num)
+ VALUES ('default', 'alice', 'Phantom fenced', 'fact', '2020-01-01'::date, 'm', 'alice', 1)`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, valid_from, source, source_markdown_slug, row_num)
+ VALUES ('default', 'alice', 'Phantom unfenced', 'fact', '2020-01-01'::date, 'm', 'alice', NULL)`,
+ );
+
+ const r = await engine.migrateFactsToCanonical('alice', 'people/alice-example', 'default');
+ expect(r.migrated).toBe(2);
+
+ const rows = await engine.executeRaw<{ fact: string; row_num: number | null }>(
+ `SELECT fact, row_num FROM facts
+ WHERE source_id='default' AND source_markdown_slug='people/alice-example'
+ ORDER BY row_num NULLS LAST`,
+ );
+ expect(rows.map((x) => [x.fact, x.row_num])).toEqual([
+ ['Canonical', 1], // untouched
+ ['Phantom fenced', 2], // 1 + MAX(canonical)=1
+ ['Phantom unfenced', null], // NULL + offset stays NULL (legacy-guard semantics intact)
+ ]);
+ const left = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM facts WHERE source_id='default' AND source_markdown_slug='alice' AND expired_at IS NULL`,
+ );
+ expect(Number(left[0].n)).toBe(0);
+ }
+ });
+
+ test('#4558 — offset is canonical MAX incl. expired rows (the partial index only excludes NULL)', async () => {
+ for (const engine of [pglite, pg].filter(Boolean) as BrainEngine[]) {
+ await seed(engine, 'alice', '# alice\n');
+ await seed(engine, 'people/alice-example', '# alice-example\n');
+ // Canonical rows 1..2 active, row 3 expired: still occupies (source, slug, 3).
+ for (const [n, expired] of [[1, false], [2, false], [3, true]] as const) {
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, valid_from, source, source_markdown_slug, row_num, expired_at)
+ VALUES ('default', 'people/alice-example', 'C${n}', 'fact', '2020-01-01'::date, 'm', 'people/alice-example', ${n}, ${expired ? 'now()' : 'NULL'})`,
+ );
+ }
+ for (const n of [1, 2]) {
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, valid_from, source, source_markdown_slug, row_num)
+ VALUES ('default', 'alice', 'P${n}', 'fact', '2020-01-01'::date, 'm', 'alice', ${n})`,
+ );
+ }
+
+ const r = await engine.migrateFactsToCanonical('alice', 'people/alice-example', 'default');
+ expect(r.migrated).toBe(2);
+
+ const rows = await engine.executeRaw<{ fact: string; row_num: number }>(
+ `SELECT fact, row_num FROM facts
+ WHERE source_id='default' AND source_markdown_slug='people/alice-example' AND fact LIKE 'P%'
+ ORDER BY row_num`,
+ );
+ expect(rows.map((x) => [x.fact, Number(x.row_num)])).toEqual([['P1', 4], ['P2', 5]]);
+ }
+ });
});
diff --git a/test/propose-takes.test.ts b/test/propose-takes.test.ts
index 30475b0bc7..d83573c22f 100644
--- a/test/propose-takes.test.ts
+++ b/test/propose-takes.test.ts
@@ -1097,3 +1097,38 @@ describe('cycle.propose_takes.enabled gate (#4102)', () => {
expect(calls()).toBe(1);
});
});
+
+// ─── #4823: `gbrain dream --dry-run` promises "no writes" ────────────
+// BaseCyclePhase.run() must skip every subclass (propose_takes / grade_takes /
+// calibration_profile) under dry-run — they bill LLM calls and INSERT rows and
+// have no dry-run path of their own — the same shape extract uses.
+
+describe('runPhaseProposeTakes — dry-run (#4823)', () => {
+ function armedEngine(): { engine: BrainEngine; calls: () => number } {
+ let calls = 0;
+ const engine = {
+ kind: 'pglite',
+ async executeRaw() { calls++; throw new Error('executeRaw must not run under dry-run'); },
+ async listPages() { calls++; throw new Error('listPages must not run under dry-run'); },
+ } as unknown as BrainEngine;
+ return { engine, calls: () => calls };
+ }
+ const meter = () => new BudgetMeter({ budgetUsd: 1, phase: 'propose_takes' });
+
+ test('opts.dryRun: skipped with no_dry_run_support; engine never touched', async () => {
+ const { engine, calls } = armedEngine();
+ const r = await runPhaseProposeTakes(buildCtx(engine), { dryRun: true, meter: meter() });
+ expect(r.status).toBe('skipped');
+ expect(r.details.reason).toBe('no_dry_run_support');
+ expect(r.details.dryRun).toBe(true);
+ expect(calls()).toBe(0);
+ });
+
+ test('ctx.dryRun alone (caller forgot to thread opts): still skipped; engine never touched', async () => {
+ const { engine, calls } = armedEngine();
+ const r = await runPhaseProposeTakes({ ...buildCtx(engine), dryRun: true }, { meter: meter() });
+ expect(r.status).toBe('skipped');
+ expect(r.details.reason).toBe('no_dry_run_support');
+ expect(calls()).toBe(0);
+ });
+});
diff --git a/test/put-page-remote-autolink-hint.test.ts b/test/put-page-remote-autolink-hint.test.ts
index d34830854c..0fe523f1a0 100644
--- a/test/put-page-remote-autolink-hint.test.ts
+++ b/test/put-page-remote-autolink-hint.test.ts
@@ -12,6 +12,8 @@
*/
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { operations } from '../src/core/operations.ts';
@@ -56,6 +58,13 @@ describe('put_page remote auto-link disclosure (#4525)', () => {
test('tool description names the remote auto-link skip', () => {
expect(putPage.description).toMatch(/[Rr]emote .*callers/);
expect(putPage.description).toContain('skipped');
+ // #4679: name the async path too (serve maintenance sweep / `gbrain sweep`).
+ expect(putPage.description).toContain('sweep');
+ // Wave review: only a stdio serve self-sweeps (startup + idle);
+ // `gbrain serve --http` never arms one. The disclosure must be per-lane.
+ expect(putPage.description).toMatch(/stdio `gbrain serve` sweeps/);
+ expect(putPage.description).toMatch(/`gbrain serve --http` does not self-sweep/);
+ expect(putPage.description).not.toMatch(/sweep \(startup \+ idle\)/);
});
test('remote write reports skipped: remote WITH an actionable hint', async () => {
@@ -66,10 +75,42 @@ describe('put_page remote auto-link disclosure (#4525)', () => {
expect(result.auto_links?.skipped).toBe('remote');
expect(result.auto_links?.hint).toBeDefined();
expect(result.auto_links?.hint).toContain('NOT reconciled');
+ expect(result.auto_links?.hint).toContain('sweep');
+ // Wave review: lane-accurate — HTTP serve callers are told it does NOT self-sweep.
+ expect(result.auto_links?.hint).toMatch(/stdio `gbrain serve` sweeps/);
+ expect(result.auto_links?.hint).toMatch(/`gbrain serve --http` does not self-sweep/);
+ expect(result.auto_links?.hint).not.toMatch(/sweep \(startup \+ idle\)/);
expect(result.auto_timeline?.skipped).toBe('remote');
expect(result.auto_timeline?.hint).toBeDefined();
}, 120000);
+ // #4679: the brain-ops skill (shipped to the exact agents that write over
+ // stdio) promised inline auto_links {created, removed, errors} on EVERY
+ // put_page — false for every MCP transport since the gate shipped. It must
+ // state the remote skip and the sweep that reconciles those edges later.
+ test('brain-ops skill Phase 2.5 states the MCP skip + sweep instead of promising inline auto-link', () => {
+ const skill = readFileSync(join(import.meta.dir, '..', 'skills', 'brain-ops', 'SKILL.md'), 'utf8');
+ expect(skill).not.toContain('No manual `add_link` calls needed for ordinary page writes');
+ expect(skill).toContain('skipped');
+ expect(skill).toContain('sweep');
+ // Wave review: the skill must not promise a startup/idle sweep to HTTP
+ // callers — only the stdio serve arms one.
+ expect(skill).toMatch(/`gbrain serve --http` does not self-sweep/);
+ expect(skill).not.toMatch(/\(at startup and on 10-minute idle ticks\)/);
+ });
+
+ // The paste-in template downstream forks copy (UPGRADING_DOWNSTREAM_AGENTS.md)
+ // and the enrich skill carried the same inline promise one file over.
+ test('downstream-upgrade doc and enrich skill state the MCP skip, not an inline auto_links promise', () => {
+ for (const rel of ['docs/UPGRADING_DOWNSTREAM_AGENTS.md', 'skills/enrich/SKILL.md']) {
+ const flat = readFileSync(join(import.meta.dir, '..', rel), 'utf8').replace(/\s+/g, ' ');
+ expect(flat).not.toContain('MCP response includes `auto_links: { created');
+ expect(flat).not.toContain('Verify via the `auto_links` field in the put_page response (`{ created');
+ expect(flat).toContain('skipped: "remote"');
+ expect(flat).toContain('sweep');
+ }
+ });
+
test('local write does not carry the remote skip marker', async () => {
const result = (await putPage.handler(
makeCtx({ remote: false }),
diff --git a/test/r1-namedthing-rerank-ab.test.ts b/test/r1-namedthing-rerank-ab.test.ts
index f9eb84ad7f..d966268da8 100644
--- a/test/r1-namedthing-rerank-ab.test.ts
+++ b/test/r1-namedthing-rerank-ab.test.ts
@@ -295,9 +295,9 @@ describe('CLI', () => {
expect(parseArgs([]).relationalPin).toBeUndefined();
expect(parseArgs([]).searchPins).toBeUndefined();
expect(parseArgs(['--search-pin', 'search.autocut=true'])).toMatchObject({ searchPins: { 'search.autocut': 'true' } });
- expect(parseArgs(['--search-pin', ' search.relational_rerank_pin = 5 ', '--search-pin', 'search.token_budget=off', '--search-pin', 'search.token_budget=4000']).searchPins).toEqual({
+ expect(parseArgs(['--search-pin', ' search.relational_rerank_pin = 5 ', '--search-pin', 'search.tokenBudget=off', '--search-pin', 'search.tokenBudget=4000']).searchPins).toEqual({
'search.relational_rerank_pin': '5',
- 'search.token_budget': '4000',
+ 'search.tokenBudget': '4000',
});
// A value may itself contain '=' — only the first one splits.
expect(parseArgs(['--search-pin', 'search.x=a=b']).searchPins).toEqual({ 'search.x': 'a=b' });
@@ -310,8 +310,8 @@ describe('CLI', () => {
expect(buildOverlay(parseArgs(['--search-pin', 'search.autocut=false', '--autocut', 'on']))).toEqual({ 'search.autocut': 'true' });
expect(buildOverlay(parseArgs(['--relational-pin', '3', '--search-pin', 'search.relational_rerank_pin=9']))).toEqual({ 'search.relational_rerank_pin': '3' });
// Non-colliding search pins ride along untouched; no explicit flag → the pin stands.
- expect(buildOverlay(parseArgs(['--autocut', 'off', '--search-pin', 'search.token_budget=4000', '--search-pin', 'search.autocut=true']))).toEqual({
- 'search.token_budget': '4000',
+ expect(buildOverlay(parseArgs(['--autocut', 'off', '--search-pin', 'search.tokenBudget=4000', '--search-pin', 'search.autocut=true']))).toEqual({
+ 'search.tokenBudget': '4000',
'search.autocut': 'false',
});
expect(buildOverlay(parseArgs(['--search-pin', 'search.autocut=true']))).toEqual({ 'search.autocut': 'true' });
diff --git a/test/recompute-emotional-weight.test.ts b/test/recompute-emotional-weight.test.ts
index f2ada95658..9c1c5a7ebe 100644
--- a/test/recompute-emotional-weight.test.ts
+++ b/test/recompute-emotional-weight.test.ts
@@ -119,6 +119,49 @@ describe('runPhaseRecomputeEmotionalWeight', () => {
expect(engine.written[0].weight).toBeCloseTo(0.5, 5);
});
+ // #4797: one synchronous full-brain UPDATE on PGLite wedges the main thread
+ // (no lock refresh, no progress, no abort) for as long as the statement
+ // runs. The phase must write in bounded slices and yield between them.
+ test('full mode writes in slices of 1000 with a yield + progress tick between statements (#4797)', async () => {
+ const rows: EmotionalWeightInputRow[] = Array.from({ length: 2500 }, (_, i) => ({
+ slug: `p/${i}`, source_id: 'default', tags: [], takes: [],
+ }));
+ const calls: number[] = [];
+ let yields = 0;
+ let ticks = 0;
+ const engine: FakeEngine = {
+ batchLoadEmotionalInputs: async () => rows,
+ setEmotionalWeightBatch: async (rs) => { calls.push(rs.length); return 0; }, // 0 = nothing changed
+ getConfig: async () => null,
+ };
+ const r = await runPhaseRecomputeEmotionalWeight(engine as any, {
+ yieldDuringPhase: async () => { yields++; },
+ onProgress: () => { ticks++; },
+ });
+ expect(r.status).toBe('ok');
+ expect(calls).toEqual([1000, 1000, 500]);
+ expect(yields).toBeGreaterThanOrEqual(2);
+ expect(ticks).toBeGreaterThanOrEqual(3);
+ // pages_recomputed = pages EVALUATED (cycle totals + dry-run stay consistent);
+ // pages_updated = rows the engine actually changed.
+ expect(r.pages_recomputed).toBe(2500);
+ expect(r.details.pages_recomputed).toBe(2500);
+ expect(r.details.pages_updated).toBe(0);
+ });
+
+ test('an already-aborted signal stops the phase before the first write (#4797)', async () => {
+ const rows: EmotionalWeightInputRow[] = Array.from({ length: 2500 }, (_, i) => ({
+ slug: `p/${i}`, source_id: 'default', tags: [], takes: [],
+ }));
+ const engine = makeEngine(rows);
+ const ac = new AbortController();
+ ac.abort(new Error('SIGTERM'));
+ const r = await runPhaseRecomputeEmotionalWeight(engine as any, { signal: ac.signal });
+ expect(r.status).toBe('fail');
+ expect(r.error?.message.toLowerCase()).toContain('abort');
+ expect(engine.written.length).toBe(0);
+ });
+
test('engine throw bubbles into a fail PhaseResult, not an unhandled exception', async () => {
const engine: FakeEngine = {
batchLoadEmotionalInputs: async () => { throw new Error('db down'); },
diff --git a/test/reindex-search-vector.serial.test.ts b/test/reindex-search-vector.serial.test.ts
index e8dd3a1a93..683a6447cc 100644
--- a/test/reindex-search-vector.serial.test.ts
+++ b/test/reindex-search-vector.serial.test.ts
@@ -2,6 +2,7 @@ import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import type { BrainEngine } from '../src/core/engine.ts';
import { runReindexSearchVector } from '../src/commands/reindex-search-vector.ts';
import { resetFtsLanguageCache } from '../src/core/fts-language.ts';
+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';
const ENV_KEY = 'GBRAIN_FTS_LANGUAGE';
const originalLang = process.env[ENV_KEY];
@@ -9,21 +10,44 @@ const originalLang = process.env[ENV_KEY];
interface MockState {
calls: string[];
rowsToReturn: { pages: number; chunks: number };
+ /** In-memory config table (marker + checkpoints). Separate from `calls`
+ * so the executeRaw call-count assertions stay intact. */
+ config?: Map<string, string>;
+ /** Interleaved timeline of executeRaw SQL + `set:<key>` / `unset:<key>`. */
+ order?: string[];
+ /** Throw from executeRaw on the first SQL matching this pattern. */
+ failOn?: RegExp;
}
function makeMockEngine(state: MockState): BrainEngine {
+ const config = state.config ?? (state.config = new Map());
+ const order = state.order ?? (state.order = []);
return {
executeRaw: async (sql: string) => {
state.calls.push(sql);
+ order.push(sql);
+ if (state.failOn && state.failOn.test(sql)) throw new Error(`injected failure: ${state.failOn}`);
// Inventory query — return the configured counts
if (sql.includes('SELECT') && sql.includes('FROM pages WHERE search_vector')) {
return [{ pages: state.rowsToReturn.pages, chunks: state.rowsToReturn.chunks }];
}
return [];
},
+ getConfig: async (key: string) => config.get(key) ?? null,
+ setConfig: async (key: string, value: string) => {
+ order.push(`set:${key}`);
+ config.set(key, value);
+ },
+ unsetConfig: async (key: string) => {
+ order.push(`unset:${key}`);
+ return config.delete(key) ? 1 : 0;
+ },
} as unknown as BrainEngine;
}
+const MARKER = 'fts.reindex_in_progress';
+const CHUNKS_CKPT = 'backfill.fts_content_chunks.last_id';
+
beforeEach(() => {
delete process.env[ENV_KEY];
resetFtsLanguageCache();
@@ -149,4 +173,119 @@ describe('runReindexSearchVector', () => {
expect(typeof result.durationMs).toBe('number');
expect(result.durationMs).toBeGreaterThanOrEqual(0);
});
+
+ // #4795 — an interrupted run commits the trigger-language flip but leaves
+ // rows un-backfilled. The in-progress marker + persisted checkpoint make
+ // that state visible (doctor) and resumable (re-run).
+ describe('interrupted-run marker + checkpoint (#4795)', () => {
+ test('backfill failure leaves the in-progress marker set', async () => {
+ const state: MockState = {
+ calls: [], rowsToReturn: { pages: 10, chunks: 30 }, failOn: /UPDATE content_chunks/,
+ };
+ const engine = makeMockEngine(state);
+ process.env[ENV_KEY] = 'pt_br';
+ resetFtsLanguageCache();
+
+ await expect(runReindexSearchVector(engine, { yes: true, json: true })).rejects.toThrow();
+ expect(state.config!.get(MARKER)).toBe('pt_br');
+ });
+
+ test('a failure on the first DDL clears the marker — nothing landed, so doctor must not flag an incomplete reindex', async () => {
+ // A missing CREATE FUNCTION privilege fails here, before either trigger
+ // flipped. Leaving the marker set would be a permanent false
+ // fts_reindex_incomplete whose suggested fix (re-run) fails the same way.
+ const state: MockState = {
+ calls: [], rowsToReturn: { pages: 10, chunks: 30 }, failOn: /update_page_search_vector/,
+ };
+ const engine = makeMockEngine(state);
+ process.env[ENV_KEY] = 'pt_br';
+ resetFtsLanguageCache();
+
+ await expect(runReindexSearchVector(engine, { yes: true, json: true })).rejects.toThrow();
+ expect(state.config!.has(MARKER)).toBe(false);
+ });
+
+ test('a failure on the first DDL restores a PRE-EXISTING marker — a previously split index must stay visible to doctor', async () => {
+ // A prior run already flipped triggers and was interrupted (marker set).
+ // This resume fails before any DDL lands, so the index is still split
+ // exactly as before: the marker must survive with its prior value.
+ for (const prior of ['pt_br', 'english']) {
+ const state: MockState = {
+ calls: [], rowsToReturn: { pages: 10, chunks: 30 }, failOn: /update_page_search_vector/,
+ config: new Map([[MARKER, prior]]),
+ };
+ const engine = makeMockEngine(state);
+ process.env[ENV_KEY] = 'pt_br';
+ resetFtsLanguageCache();
+
+ await expect(runReindexSearchVector(engine, { yes: true, json: true })).rejects.toThrow();
+ expect(state.config!.get(MARKER)).toBe(prior);
+ }
+ });
+
+ test('a failure on the second DDL keeps the marker — the pages trigger already flipped', async () => {
+ const state: MockState = {
+ calls: [], rowsToReturn: { pages: 10, chunks: 30 }, failOn: /update_chunk_search_vector/,
+ };
+ const engine = makeMockEngine(state);
+ process.env[ENV_KEY] = 'pt_br';
+ resetFtsLanguageCache();
+
+ await expect(runReindexSearchVector(engine, { yes: true, json: true })).rejects.toThrow();
+ expect(state.config!.get(MARKER)).toBe('pt_br');
+ });
+
+ test('the marker key is registered so `gbrain config` treats the escape hatch as a known key', () => {
+ expect(KNOWN_CONFIG_KEYS).toContain(MARKER);
+ });
+
+ test('successful run sets the marker before the first CREATE OR REPLACE and clears all state at the end', async () => {
+ const state: MockState = { calls: [], rowsToReturn: { pages: 10, chunks: 30 } };
+ const engine = makeMockEngine(state);
+ process.env[ENV_KEY] = 'pt_br';
+ resetFtsLanguageCache();
+
+ await runReindexSearchVector(engine, { yes: true, json: true });
+
+ const order = state.order!;
+ const markerAt = order.indexOf(`set:${MARKER}`);
+ const firstDdlAt = order.findIndex(s => s.includes('CREATE OR REPLACE FUNCTION'));
+ expect(markerAt).toBeGreaterThanOrEqual(0);
+ expect(firstDdlAt).toBeGreaterThan(markerAt);
+ // Marker + both checkpoints gone once both backfills return.
+ 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);
+ });
+
+ test('resumes the chunks backfill from the persisted checkpoint when the marker matches the language', async () => {
+ const state: MockState = { calls: [], rowsToReturn: { pages: 10, chunks: 30 } };
+ state.config = new Map([[MARKER, 'pt_br'], [CHUNKS_CKPT, '10000']]);
+ const engine = makeMockEngine(state);
+ process.env[ENV_KEY] = 'pt_br';
+ resetFtsLanguageCache();
+
+ await runReindexSearchVector(engine, { yes: true, json: true });
+
+ const chunksUpdate = state.calls.find(s => /UPDATE content_chunks/.test(s));
+ expect(chunksUpdate).toContain('id > 10000');
+ });
+
+ // Regression guard for the reset branch (passes on the unpatched tree,
+ // which always emits `id > 0`; not part of the fails-on-master proof).
+ test('a different target language discards the stale checkpoint', async () => {
+ const state: MockState = { calls: [], rowsToReturn: { pages: 10, chunks: 30 } };
+ state.config = new Map([[MARKER, 'english'], [CHUNKS_CKPT, '10000']]);
+ const engine = makeMockEngine(state);
+ process.env[ENV_KEY] = 'pt_br';
+ resetFtsLanguageCache();
+
+ await runReindexSearchVector(engine, { yes: true, json: true });
+
+ const chunksUpdate = state.calls.find(s => /UPDATE content_chunks/.test(s));
+ expect(chunksUpdate).toContain('id > 0');
+ expect(state.config!.has(CHUNKS_CKPT)).toBe(false);
+ });
+ });
});
diff --git a/test/schema-cli-db-config.serial.test.ts b/test/schema-cli-db-config.serial.test.ts
new file mode 100644
index 0000000000..2f80578a54
--- /dev/null
+++ b/test/schema-cli-db-config.serial.test.ts
@@ -0,0 +1,81 @@
+/**
+ * #4653 — the schema inspection verbs (show / explain / graph / lint) must
+ * resolve the active pack through the same tier chain `schema active` uses,
+ * including tier 4 (brain-wide DB config `schema_pack`).
+ *
+ * Serial because it opens a persistent PGLite database and then hands that
+ * database to CLI subprocesses.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+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';
+
+const REPO_ROOT = join(import.meta.dir, '..');
+
+let home: string;
+
+function runSchema(...args: string[]) {
+ return spawnSync('bun', ['run', 'src/cli.ts', 'schema', ...args], {
+ cwd: REPO_ROOT,
+ encoding: 'utf-8',
+ env: {
+ ...process.env,
+ GBRAIN_DATABASE_URL: '',
+ DATABASE_URL: '',
+ GBRAIN_SCHEMA_PACK: '',
+ GBRAIN_HOME: home,
+ },
+ timeout: 60_000,
+ });
+}
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-schema-db-config-'));
+ const gbrainDir = join(home, '.gbrain');
+ const dbPath = join(gbrainDir, 'brain.pglite');
+ mkdirSync(gbrainDir, { recursive: true });
+ const engine = new PGLiteEngine();
+ try {
+ await engine.connect({ engine: 'pglite', database_path: dbPath });
+ await engine.initSchema();
+ // Tier 4 only: no env var, no config.json schema_pack.
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ } finally {
+ await engine.disconnect();
+ }
+ writeFileSync(
+ join(gbrainDir, 'config.json'),
+ JSON.stringify({ engine: 'pglite', database_path: dbPath }),
+ 'utf-8',
+ );
+});
+
+afterAll(() => {
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('#4653 schema inspection verbs honor DB-config schema_pack (tier 4)', () => {
+ test('schema show prints the DB-configured pack header', () => {
+ const r = runSchema('show');
+ expect(r.status).toBe(0);
+ expect((r.stdout ?? '').split('\n')[0]).toBe('# gbrain-base-v2 v1.2.0');
+ }, 90_000);
+
+ test('schema explain <v2-only type> exits 0', () => {
+ // `tweet` exists only in gbrain-base-v2 — pre-fix: exit 1, "not in active pack `gbrain-base`".
+ const r = runSchema('explain', 'tweet', '--json');
+ expect(r.status).toBe(0);
+ expect(JSON.parse(r.stdout ?? '').pack).toBe('gbrain-base-v2');
+ }, 90_000);
+
+ test('schema graph --json and schema lint --json report the DB-configured pack', () => {
+ const graph = runSchema('graph', '--json');
+ expect(graph.status).toBe(0);
+ expect(JSON.parse(graph.stdout ?? '').pack).toBe('gbrain-base-v2');
+ const lint = runSchema('lint', '--json');
+ expect(JSON.parse(lint.stdout ?? '').pack).toBe('gbrain-base-v2');
+ }, 120_000);
+});
diff --git a/test/schema-pack-best-effort.test.ts b/test/schema-pack-best-effort.test.ts
index 121ef1f4f0..138663a89f 100644
--- a/test/schema-pack-best-effort.test.ts
+++ b/test/schema-pack-best-effort.test.ts
@@ -5,7 +5,7 @@
// facts/eligibility, enrichment-service) depend on this contract.
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { loadActivePackBestEffort } from '../src/core/schema-pack/best-effort.ts';
@@ -81,3 +81,40 @@ describe('loadActivePackBestEffort', () => {
});
});
});
+
+describe('loadActivePackBestEffort — #4653 DB-plane schema_pack (tier 4)', () => {
+ function engineWithDbPack(pack: string | null) {
+ return { getConfig: async (key: string) => (key === 'schema_pack' ? pack : null) } as never;
+ }
+
+ it('honors the engine-side schema_pack when the ctx carries a live engine', async () => {
+ await withEnv({ GBRAIN_HOME: tmpDir, GBRAIN_SCHEMA_PACK: undefined }, async () => {
+ const ctx = { ...fakeCtx(), engine: engineWithDbPack('gbrain-base-v2') } as OperationContext;
+ const result = await loadActivePackBestEffort(ctx);
+ expect(result?.manifest.name).toBe('gbrain-base-v2');
+ });
+ });
+
+ it('a path-shaped DB schema_pack never escapes ~/.gbrain/schema-packs (unknown pack → null)', async () => {
+ // Unguarded, `gbrainPath('schema-packs', '../evil')` lands on
+ // <home>/.gbrain/evil — plant a valid pack there and prove the tier-4
+ // string cannot reach it (isValidPackName gate in defaultPackLocator).
+ const evilDir = join(tmpDir, '.gbrain', 'evil');
+ mkdirSync(evilDir, { recursive: true });
+ const base = readFileSync(join(import.meta.dir, '..', 'src', 'core', 'schema-pack', 'base', 'gbrain-base.yaml'), 'utf-8');
+ writeFileSync(join(evilDir, 'pack.yaml'), base.replace('name: gbrain-base', 'name: evil-pack'), 'utf-8');
+ await withEnv({ GBRAIN_HOME: tmpDir, GBRAIN_SCHEMA_PACK: undefined }, async () => {
+ const ctx = { ...fakeCtx(), engine: engineWithDbPack('../evil') } as OperationContext;
+ expect(await loadActivePackBestEffort(ctx)).toBeNull();
+ });
+ });
+
+ it('a throwing getConfig degrades to file/env resolution, never throws', async () => {
+ await withEnv({ GBRAIN_HOME: tmpDir, GBRAIN_SCHEMA_PACK: undefined }, async () => {
+ const boom = { getConfig: async () => { throw new Error('no config table'); } } as never;
+ const ctx = { ...fakeCtx(), engine: boom } as OperationContext;
+ const result = await loadActivePackBestEffort(ctx);
+ expect(result?.manifest.name).toBe('gbrain-base');
+ });
+ });
+});
diff --git a/test/schema-pack-stats.test.ts b/test/schema-pack-stats.test.ts
index a27694c6c8..0af644a464 100644
--- a/test/schema-pack-stats.test.ts
+++ b/test/schema-pack-stats.test.ts
@@ -331,3 +331,14 @@ describe('runStatsCore — type/untyped split', () => {
});
});
});
+
+describe('runStatsCore — #4653 DB-plane schema_pack tier', () => {
+ it('pack_identity follows the brain-wide DB config schema_pack (tier 4)', async () => {
+ await withEnv({ GBRAIN_HOME: tmpDir, GBRAIN_SCHEMA_PACK: undefined }, async () => {
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ const result = await runStatsCore(ctxOf());
+ // Pre-fix: loadActivePackBestEffort never read the engine → '[email protected]+…'.
+ expect(result.pack_identity).toStartWith('[email protected]');
+ });
+ });
+});
diff --git a/test/scripts/check-key-files-current-state.test.ts b/test/scripts/check-key-files-current-state.test.ts
index 026ef34096..34fc4abae8 100644
--- a/test/scripts/check-key-files-current-state.test.ts
+++ b/test/scripts/check-key-files-current-state.test.ts
@@ -105,6 +105,18 @@ describe("check-key-files-current-state.sh", () => {
expect(r.stderr).toContain("WARN");
});
+ it("FAILS when KEY_FILES.md carries two bullets for the same src file", () => {
+ seedClean();
+ writeDoc(
+ "docs/architecture/KEY_FILES.md",
+ "# Key files\n\n- `src/core/db.ts` — connection management.\n- `src/core/db.ts` — connection management + pool reconnect.\n",
+ );
+ const r = run();
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain("more than one bullet");
+ expect(r.stderr).toContain("src/core/db.ts");
+ });
+
it("catches the marker in any of the three reference docs (thin-client)", () => {
seedClean();
writeDoc("docs/architecture/thin-client.md", "# Thin-client\n\n**v0.36.3:** added cross-modal.\n");
diff --git a/test/search-mode-config-snapshot.test.ts b/test/search-mode-config-snapshot.test.ts
index 3a1988c541..fd505c8bf5 100644
--- a/test/search-mode-config-snapshot.test.ts
+++ b/test/search-mode-config-snapshot.test.ts
@@ -4,12 +4,15 @@ import { loadSearchModeConfig, SEARCH_MODE_CONFIG_KEYS } from '../src/core/searc
/**
* loadSearchModeConfig resolves the mode key plus every per-knob override key.
* Read one key per round trip and that is 33 `SELECT value FROM config WHERE
- * key = $1` queries on every uncached search (66 on the cached path, which
- * resolves the mode twice). On a hosted Postgres with the default pool of 10
- * that is ~4 sequential RTT rounds and 33 pooler-slot grabs before any
- * retrieval work runs. config-snapshot.ts exists to collapse exactly this
- * shape into one whole-table read; these tests pin that the loader uses it
- * and falls back to per-key reads when it cannot.
+ * key = $1` queries on every search — on a hosted Postgres with the default
+ * pool of 10 that is ~4 sequential RTT rounds and 33 pooler-slot grabs before
+ * any retrieval work runs. (#4359, fixed) `hybridSearchCached` used to call
+ * this twice per request (once for its own cache-key resolution, once again
+ * inside the bare `hybridSearch` it calls on a miss) before threading the
+ * loaded snapshot through; now it's once either way. config-snapshot.ts
+ * exists to collapse the 33-reads-per-call shape into one whole-table read;
+ * these tests pin that the loader uses it and falls back to per-key reads
+ * when it cannot.
*/
function countingEngine(rows: Record<string, string>) {
const calls = { getConfig: 0, getAllConfig: 0 };
diff --git a/test/search-mode.test.ts b/test/search-mode.test.ts
index 5e987e9894..dbec0d14ee 100644
--- a/test/search-mode.test.ts
+++ b/test/search-mode.test.ts
@@ -357,12 +357,20 @@ describe('attributeKnob source attribution', () => {
expect(a.value).toBe(999);
});
- test('override source labels the config key path', () => {
- const input = { mode: 'conservative', overrides: { cache_enabled: false } };
+ test('override source labels the REAL config key path, not the knob name (#4605)', () => {
+ // `gbrain search modes` prints source_detail verbatim as a copy-pasteable
+ // `gbrain config set` target, so it must be the key mode.ts reads.
+ const input = {
+ mode: 'conservative',
+ overrides: { cache_enabled: false, reranker_top_n_in: 5, relationalRetrieval: false },
+ };
const resolved = resolveSearchMode(input);
const a = attributeKnob('cache_enabled', input, resolved);
expect(a.source).toBe('override');
- expect(a.source_detail).toContain('search.cache_enabled');
+ expect(a.source_detail).toContain('search.cache.enabled');
+ expect(a.source_detail).not.toContain('search.cache_enabled');
+ expect(attributeKnob('reranker_top_n_in', input, resolved).source_detail).toBe('config: search.reranker.top_n_in');
+ expect(attributeKnob('relationalRetrieval', input, resolved).source_detail).toBe('config: search.relational_retrieval');
});
test('mode source labels the mode name', () => {
diff --git a/test/search-safe-index-probe.test.ts b/test/search-safe-index-probe.test.ts
new file mode 100644
index 0000000000..74fd6f4443
--- /dev/null
+++ b/test/search-safe-index-probe.test.ts
@@ -0,0 +1,82 @@
+/**
+ * #5004 (pre-landing review) — the `safe_index_pending` probe in
+ * `src/core/ops/search.ts` (`hasUnsealedPagesInScope`) runs on EVERY empty
+ * remote search/query. On a fully sealed brain it must be an index probe, not
+ * a walk of every markdown page: `NOT (COALESCE(chunker_version, 0) >= N)` is
+ * not sargable, so the partial btree `pages_chunker_version_idx` can only be
+ * scanned whole with the predicate as a post-scan Filter. `pages.chunker_version`
+ * is `SMALLINT NOT NULL DEFAULT 1` (cjk_wave migration), so the plain range
+ * `chunker_version < N` is the same set and lets the planner use an Index Cond.
+ *
+ * Pins both layers: the SQL text the probe issues, and the PGLite plan for it
+ * (seq scans disabled so a non-sargable predicate cannot hide behind a small
+ * table).
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { SAFE_FENCE_CHUNKER_VERSION } from '../src/core/search/safe-chunks.ts';
+
+let engine: PGLiteEngine;
+const captured: Array<{ sql: string; params: unknown[] | undefined }> = [];
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ // Keyword-only keeps the op keyless (no embedding call); the probe fires on
+ // this path too — it is the one producer of the `retrieval` meta channel.
+ await engine.setConfig('search.mcp_keyword_only', 'true');
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+/** The real engine, with the op-level `executeRaw` calls recorded. */
+function recordingCtx(): OperationContext {
+ const recording = new Proxy(engine, {
+ get(target, prop) {
+ if (prop === 'executeRaw') {
+ return (sql: string, params?: unknown[]) => {
+ captured.push({ sql, params });
+ return target.executeRaw(sql, params);
+ };
+ }
+ const value = Reflect.get(target, prop);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ return {
+ engine: recording,
+ config: {},
+ logger: { info: () => {}, warn: () => {}, error: () => {} },
+ dryRun: false,
+ remote: true,
+ sourceId: 'default',
+ emitResponseMeta: () => {},
+ } as unknown as OperationContext;
+}
+
+describe('safe_index_pending probe stays sargable (#5004)', () => {
+ test('an empty remote search issues a plain chunker_version range the partial index serves as an Index Cond', async () => {
+ captured.length = 0;
+ const rows = await operationsByName.search.handler(recordingCtx(), { query: 'nosuchtokenanywhere', limit: 5 });
+ expect(rows).toEqual([]);
+
+ const probe = captured.find(c => c.sql.includes("page_kind = 'markdown'") && /LIMIT 1/.test(c.sql));
+ expect(probe).toBeDefined();
+ expect(probe!.sql).not.toContain('COALESCE');
+ expect(probe!.sql).toContain(`p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION}`);
+
+ await engine.executeRaw('SET enable_seqscan = off');
+ try {
+ const plan = (await engine.executeRaw<Record<string, string>>(`EXPLAIN ${probe!.sql}`, probe!.params))
+ .map(r => Object.values(r)[0]).join('\n');
+ expect(plan).toContain('Index Scan using pages_chunker_version_idx');
+ expect(plan).toContain(`Index Cond: (chunker_version < ${SAFE_FENCE_CHUNKER_VERSION})`);
+ } finally {
+ await engine.executeRaw('RESET enable_seqscan');
+ }
+ });
+});
diff --git a/test/search/modes-report-coverage.test.ts b/test/search/modes-report-coverage.test.ts
index b41ce31857..ab2aa363d8 100644
--- a/test/search/modes-report-coverage.test.ts
+++ b/test/search/modes-report-coverage.test.ts
@@ -120,6 +120,10 @@ describe('#4604 buildModesReport — full-bundle knob coverage', () => {
const report = await buildModesReport(stubEngine());
expect(report.per_call_note).toBe(MODES_REPORT_PER_CALL_NOTE);
expect(report.per_call_note).toContain('Per-call');
+ // #4601: the `query` op always passes `expand` (default on), so the
+ // bundle's `expansion` row never governs it — the note must say so or the
+ // dashboard gives a confident wrong answer for the primary agent verb.
+ expect(report.per_call_note).toContain('`query` op');
});
});
diff --git a/test/serve-http-lifecycle.test.ts b/test/serve-http-lifecycle.test.ts
index cb9c54b772..04062f8ab6 100644
--- a/test/serve-http-lifecycle.test.ts
+++ b/test/serve-http-lifecycle.test.ts
@@ -130,6 +130,67 @@ describe('HTTP server lifecycle', () => {
expect(server.listenerCount('error')).toBe(0);
expect(signals.listenerCount('SIGINT')).toBe(0);
});
+
+ // Sockets are held weakly (Bun never emits 'close' on them), so destroyAll()
+ // can only sever wrappers still reachable. An idle keep-alive wrapper the
+ // runtime already collected leaves its native handle keeping close() waiting
+ // forever — the same hang the severing fixed, from the other side. The
+ // lifecycle bounds that wait instead of trusting close() to return.
+ test('bounds a close() that never finishes, says so, and still completes the lifecycle', async () => {
+ const server = new FakeHttpServer();
+ server.close = function (this: FakeHttpServer) {
+ this.closeCalls++;
+ this.listening = false;
+ return this; // never calls back, never emits 'close'
+ };
+ const signals = new EventEmitter();
+ const logs: string[] = [];
+ let deregistered = false;
+
+ const lifecycle = waitForHttpServerLifecycle(server, {
+ signals,
+ register() { return () => { deregistered = true; }; },
+ closeTimeoutMs: 20,
+ log: (msg) => { logs.push(msg); },
+ });
+
+ signals.emit('SIGINT');
+ const outcome = await Promise.race([
+ lifecycle.then(() => 'settled'),
+ new Promise<string>((r) => setTimeout(() => r('hung'), 500)),
+ ]);
+
+ expect(outcome).toBe('settled');
+ expect(server.closeCalls).toBe(1);
+ expect(deregistered).toBe(true);
+ expect(logs.join('\n')).toMatch(/20ms/);
+ expect(signals.listenerCount('SIGINT')).toBe(0);
+ });
+
+ test('a close() error that lands after the deadline is logged, not dropped', async () => {
+ const server = new FakeHttpServer();
+ server.close = function (this: FakeHttpServer, callback?: (error?: Error) => void) {
+ this.closeCalls++;
+ this.listening = false;
+ setTimeout(() => callback?.(new Error('late close failure')), 40); // after the 20ms deadline
+ return this;
+ };
+ const signals = new EventEmitter();
+ const logs: string[] = [];
+
+ const lifecycle = waitForHttpServerLifecycle(server, {
+ signals,
+ register() { return () => {}; },
+ closeTimeoutMs: 20,
+ log: (msg) => { logs.push(msg); },
+ });
+ signals.emit('SIGINT');
+ await lifecycle; // resolved by the deadline
+ await new Promise((r) => setTimeout(r, 60)); // let the late callback fire
+
+ expect(logs.join('\n')).toMatch(/20ms/);
+ expect(logs.join('\n')).toContain('late close failure');
+ });
});
// Severing sockets lets close() finish; this is what actually stops the
diff --git a/test/serve-http-socket-tracking.test.ts b/test/serve-http-socket-tracking.test.ts
new file mode 100644
index 0000000000..bc034a6cab
--- /dev/null
+++ b/test/serve-http-socket-tracking.test.ts
@@ -0,0 +1,81 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import http from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { trackServerSockets } from '../src/commands/serve-http.ts';
+
+// The shipped leak: `serve --http` tracked every accepted socket in a Set for
+// shutdown teardown and dropped it only on the socket's 'close' event. Bun's
+// node:http never emits 'close' (nor 'end'/'error') on server-side sockets, and
+// the socket keeps reporting open/writable after the peer is gone, so every
+// connection stayed tracked forever. Each kubelet health probe is a fresh TCP
+// connection, so a probe-only pod grew ~9 MB/h until OOMKilled. The lifecycle
+// tests use a FakeHttpServer whose 'close' fires synchronously, which is why
+// they never saw it — this file exercises a REAL server on the current runtime.
+
+const servers: http.Server[] = [];
+afterEach(async () => {
+ for (const s of servers.splice(0)) await new Promise<void>((r) => s.close(() => r()));
+});
+
+async function listen(): Promise<{ server: http.Server; url: string }> {
+ const server = http.createServer((_req, res) => res.end('ok'));
+ servers.push(server);
+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
+ const { port } = server.address() as AddressInfo;
+ return { server, url: `http://127.0.0.1:${port}/health` };
+}
+
+/**
+ * Let the runtime release dropped sockets; tracking must not out-live them.
+ * Socket teardown and GC are asynchronous, so poll until `done` holds (or a
+ * generous deadline passes and the assertion reports the real count).
+ */
+async function settle(done: () => boolean = () => false, ms = 3000): Promise<void> {
+ const deadline = Date.now() + ms;
+ do {
+ (globalThis as { Bun?: { gc(force: boolean): void } }).Bun?.gc(true);
+ await new Promise((r) => setTimeout(r, 25));
+ if (done()) return;
+ } while (Date.now() < deadline);
+}
+
+describe('trackServerSockets on a real http.Server', () => {
+ test('releases connections the peer has closed', async () => {
+ const { server, url } = await listen();
+ const tracker = trackServerSockets(server);
+
+ // node:http client, not `fetch`: Bun's in-process fetch pool can keep one
+ // server-side socket reachable for a while, which would mask what the
+ // tracker does. Real probes come from another process (kubelet).
+ for (let i = 0; i < 20; i++) {
+ await new Promise<void>((resolve, reject) => {
+ http.get(url, { headers: { Connection: 'close' } }, (res) => { res.resume(); res.on('end', resolve); }).on('error', reject);
+ });
+ }
+ await settle(() => tracker.size() === 0);
+
+ expect(tracker.size()).toBe(0);
+ });
+
+ test('keeps a live keep-alive connection so shutdown can sever it', async () => {
+ const { server, url } = await listen();
+ const tracker = trackServerSockets(server);
+
+ const agent = new http.Agent({ keepAlive: true, maxSockets: 1 });
+ await new Promise<void>((resolve, reject) => {
+ http.get(url, { agent }, (res) => { res.resume(); res.on('end', resolve); }).on('error', reject);
+ });
+ // Nothing to wait for here — a few GC passes are enough to prove the live
+ // socket stays reachable; do not burn the full 3s deadline.
+ await settle(() => false, 500);
+
+ // The pooled socket is still open on both ends: it must still be tracked,
+ // otherwise `server.close()` would hang on it at shutdown.
+ expect(tracker.size()).toBe(1);
+
+ tracker.destroyAll();
+ await settle(() => tracker.size() === 0);
+ expect(tracker.size()).toBe(0);
+ agent.destroy();
+ });
+});
diff --git a/test/serve-idle-sweep-source.serial.test.ts b/test/serve-idle-sweep-source.serial.test.ts
new file mode 100644
index 0000000000..226280e4eb
--- /dev/null
+++ b/test/serve-idle-sweep-source.serial.test.ts
@@ -0,0 +1,111 @@
+/**
+ * #4679 — the serve idle maintenance sweep must target the SAME source the
+ * stdio dispatch and the startup sweep resolve (GBRAIN_SOURCE > .gbrain-source
+ * dotfile > local_path > sources.default > …), not `GBRAIN_SOURCE || 'default'`.
+ *
+ * Pre-fix, a dotfile/local_path-scoped stdio serve wrote MCP pages into that
+ * source with auto_links {skipped:'remote'} while every idle sweep reconciled
+ * links against 'default' — in-session writes got zero edges until a restart.
+ *
+ * Serial: top-level mock.module (captures runMaintenanceSweep's opts without
+ * running the real sweep) + process.chdir (serve.ts resolves from process.cwd()).
+ */
+import { afterAll, describe, expect, mock, test } from 'bun:test';
+import { EventEmitter } from 'node:events';
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import type { BrainEngine } from '../src/core/engine.ts';
+import * as realSweep from '../src/core/sweep.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const sweepCalls: Array<{ sourceId?: string }> = [];
+mock.module('../src/core/sweep.ts', () => ({
+ ...realSweep,
+ runMaintenanceSweep: async (_e: BrainEngine, opts: { sourceId?: string }) => {
+ sweepCalls.push(opts);
+ return {};
+ },
+}));
+
+// Imported AFTER the mock so serve.ts's lazy `import('../core/sweep.ts')`
+// resolves to the capture above.
+const { runServe } = await import('../src/commands/serve.ts');
+type ServeOptions = import('../src/commands/serve.ts').ServeOptions;
+
+// Same fake-engine shape as test/mcp-stdio-source-resolution.test.ts: answers
+// the resolver's sources/config probes; nothing else on the engine is touched.
+function makeEngine(registeredSources: string[]): BrainEngine {
+ return {
+ kind: 'pglite',
+ disconnect: async () => {},
+ executeRaw: async <T>(sql: string, params?: unknown[]): Promise<T[]> => {
+ if (sql.includes('SELECT id FROM sources WHERE id = $1')) {
+ const id = params?.[0];
+ return (typeof id === 'string' && registeredSources.includes(id) ? [{ id } as T] : []);
+ }
+ if (sql.includes('SELECT id, local_path FROM sources')) return [];
+ if (sql.includes('SELECT id, config, archived FROM sources')) {
+ return registeredSources.map(id => ({ id, config: null, archived: false }) as T);
+ }
+ return [];
+ },
+ getConfig: async () => null,
+ } as unknown as BrainEngine;
+}
+
+const scratchDirs: string[] = [];
+const originalCwd = process.cwd();
+afterAll(() => {
+ process.chdir(originalCwd);
+ for (const d of scratchDirs.splice(0)) rmSync(d, { recursive: true, force: true });
+});
+
+async function waitFor(pred: () => boolean, ms = 5_000): Promise<void> {
+ const deadline = Date.now() + ms;
+ while (!pred() && Date.now() < deadline) await new Promise(r => setTimeout(r, 10));
+}
+
+describe('serve idle sweep source resolution (#4679)', () => {
+ test('idle sweep resolves through the stdio source ladder (dotfile), not GBRAIN_SOURCE || default', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-idle-sweep-'));
+ scratchDirs.push(dir);
+ const dotfile = join(dir, '.gbrain-source');
+ writeFileSync(dotfile, 'wiki\n');
+ chmodSync(dotfile, 0o600);
+
+ const stdin = new EventEmitter();
+ const timers: Array<{ fn: () => void; ms: number }> = [];
+ const engine = makeEngine(['default', 'wiki']);
+ const serveOpts: ServeOptions = {
+ stdin: stdin as never,
+ signals: new EventEmitter() as never,
+ exit: () => {},
+ log: () => {},
+ startMcpServer: async () => {},
+ getParentPid: () => 1, // parent watchdog skipped → the only interval is the idle sweep's
+ probeWatchdog: () => true,
+ setInterval: (fn: () => void, ms: number) => { timers.push({ fn, ms }); return { unref() {} }; },
+ clearInterval: () => {},
+ mcpStdio: false,
+ bootTimeoutMs: 0,
+ sweepEnabled: true,
+ };
+
+ process.chdir(dir);
+ try {
+ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {
+ await runServe(engine, [], serveOpts);
+ expect(timers.length).toBe(1);
+ timers[0].fn(); // tick 1 attaches the stdin activity listener
+ timers[0].fn(); // tick 2: quiet window → sweep fires
+ await waitFor(() => sweepCalls.length >= 1);
+ });
+ } finally {
+ process.chdir(originalCwd);
+ }
+
+ expect(sweepCalls.length).toBe(1);
+ expect(sweepCalls[0].sourceId).toBe('wiki');
+ }, 20_000);
+});
diff --git a/test/skillopt/deadline-and-hermetic.test.ts b/test/skillopt/deadline-and-hermetic.test.ts
index 6584018956..3d819ab974 100644
--- a/test/skillopt/deadline-and-hermetic.test.ts
+++ b/test/skillopt/deadline-and-hermetic.test.ts
@@ -10,11 +10,16 @@
*
* 2. Opt-in hermetic config for claude-cli children: resolveHermeticConfigDir
* maps GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG to the child's CLAUDE_CONFIG_DIR
- * (off by default — the config dir carries OAuth credentials on non-macOS
- * installs, so hermetic mode is a deliberate choice, never a default).
+ * (off by default — the config dir carries the CLI's session credentials,
+ * so the empty-dir form logs the child out wherever the CLI reads its
+ * session from the config dir; hermetic mode is a deliberate choice,
+ * never a default). #4741: the docs/code comment may not claim any
+ * platform "survives" the empty-dir form — nothing in the code seeds or
+ * looks up credential material, and macOS was observed logged out.
*/
import { describe, test, expect } from 'bun:test';
-import { existsSync } from 'fs';
+import { existsSync, readFileSync } from 'fs';
+import { join } from 'path';
import {
runValidationGate,
scoreSkillOnTasks,
@@ -122,3 +127,17 @@ describe('#4119 — resolveHermeticConfigDir (opt-in)', () => {
);
});
});
+
+describe('#4741 — hermetic-config docs make no platform-survives-logout claim', () => {
+ const root = join(import.meta.dir, '..', '..');
+ test('docs/guides/skillopt.md does not promise the empty-dir form keeps macOS logged in', () => {
+ const doc = readFileSync(join(root, 'docs/guides/skillopt.md'), 'utf8');
+ expect(doc).not.toMatch(/keychain and survives/);
+ expect(doc).toMatch(/logs the child out/);
+ });
+ test('the provider doc comment does not promise it either', () => {
+ // test-reads-source-ok: pins a doc-comment contract (#4741) — comment text has no runtime surface to assert.
+ const src = readFileSync(join(root, 'src/core/ai/providers/claude-cli-language-model.ts'), 'utf8');
+ expect(src).not.toMatch(/keychain and survives/);
+ });
+});
diff --git a/test/skillopt/validate-gate-abort.test.ts b/test/skillopt/validate-gate-abort.test.ts
index 88da5e2147..d019a4852e 100644
--- a/test/skillopt/validate-gate-abort.test.ts
+++ b/test/skillopt/validate-gate-abort.test.ts
@@ -1,6 +1,6 @@
/**
- * Regression: `runValidationGate` must SURFACE must-abort errors (budget
- * exhaustion / no-pricing), not swallow them as score=0.
+ * Regression: `runValidationGate` must SURFACE errors that make the whole
+ * gate meaningless, not swallow them as score=0.
*
* The bug the SkillOpt real-LLM eval surfaced: a Haiku run with `--max-cost`
* hit `BudgetTracker` no_pricing on the FIRST chat() of every rollout, the
@@ -9,10 +9,24 @@
* whole gate reported a vacuous `selScore:0` in milliseconds with zero LLM
* calls — a pricing crash masquerading as a real "0/N" measurement. The fix
* re-throws any MUST_ABORT-class error so the caller aborts loudly.
+ *
+ * #4741 widened the same rule structurally: when EVERY task in a gate fails
+ * (a dead provider — e.g. a logged-out claude-cli child — is a plain
+ * non-tagged error), or EVERY rollout carries a judge_error (dead judge
+ * provider), the gate throws instead of scoring the run 0.000 and letting the
+ * orchestrator end with a plausible-looking `no_improvement`. Partial failure
+ * keeps the pessimistic per-task 0 (fail-open for scoring noise).
*/
import { describe, test, expect } from 'bun:test';
-import { runValidationGate, scoreSkillOnTasks } from '../../src/core/skillopt/validate-gate.ts';
-import type { BenchmarkTask } from '../../src/core/skillopt/types.ts';
+import {
+ runValidationGate,
+ scoreSkillOnTasks,
+ SKILLOPT_ALL_ROLLOUTS_FAILED,
+ SKILLOPT_ALL_JUDGE_ERRORS,
+} from '../../src/core/skillopt/validate-gate.ts';
+import { ClaudeCliProcessError } from '../../src/core/ai/providers/claude-cli-language-model.ts';
+import type { BenchmarkTask, ScoredRollout, Trajectory } from '../../src/core/skillopt/types.ts';
+import type { RolloutOpts } from '../../src/core/skillopt/rollout.ts';
const TASKS: BenchmarkTask[] = [
{ task_id: 't1', task: 'do a thing', judge: { kind: 'rule', checks: [{ op: 'contains', arg: 'x' }] } } as never,
@@ -25,6 +39,11 @@ function budgetExhausted(): Error {
return e;
}
+const LOGGED_OUT = 'claude-cli reported error: Not logged in · Please run /login';
+
+const okTrajectory = (final_text: string): Trajectory =>
+ ({ final_text, tool_calls: [], turns: 1 }) as never;
+
describe('runValidationGate — must-abort errors surface', () => {
test('a BUDGET_EXHAUSTED rollout error is re-thrown, not scored 0', async () => {
const throwingRollout = (async () => {
@@ -59,9 +78,12 @@ describe('runValidationGate — must-abort errors surface', () => {
).rejects.toThrow(/no pricing entry/);
});
- test('an ordinary (non-abort) rollout error still scores 0 — fail-open preserved', async () => {
- const flakyRollout = (async () => {
- throw new Error('transient judge hiccup'); // no .tag → not must-abort
+ test('a PARTIAL (non-abort) rollout failure still scores that task 0 — fail-open preserved', async () => {
+ // t1 throws a plain error (no .tag → not must-abort); t2 completes and
+ // passes its contains-'y' check. Pessimistic mean = (0 + 1) / 2.
+ const flakyRollout = (async (o: RolloutOpts) => {
+ if (o.task.task_id === 't1') throw new Error('transient judge hiccup');
+ return okTrajectory('y');
}) as never;
const gate = await runValidationGate({
engine: {} as never,
@@ -72,7 +94,84 @@ describe('runValidationGate — must-abort errors surface', () => {
runsPerTask: 1,
rolloutFn: flakyRollout,
});
- expect(gate.selScore).toBe(0);
- expect(gate.scoredRollouts).toHaveLength(0);
+ expect(gate.selScore).toBe(0.5);
+ expect(gate.scoredRollouts).toHaveLength(1);
+ expect(gate.perTaskMedians.find((r) => r.task_id === 't1')?.median).toBe(0);
+ });
+});
+
+describe('#4741 — a 100%-failed gate is an error, not a 0.000 measurement', () => {
+ const loggedOutRollout = (async () => {
+ throw new ClaudeCliProcessError(LOGGED_OUT);
+ }) as never;
+
+ test('every task failing with a non-abort error throws skillopt_all_rollouts_failed carrying the first error', async () => {
+ await expect(
+ runValidationGate({
+ engine: {} as never,
+ candidateSkillText: 'skill',
+ selSet: TASKS,
+ bestScore: -1,
+ targetModel: 'claude-cli:claude-sonnet-4-6',
+ runsPerTask: 1,
+ rolloutFn: loggedOutRollout,
+ }),
+ ).rejects.toThrow(new RegExp(`${SKILLOPT_ALL_ROLLOUTS_FAILED}.*Not logged in`));
+ });
+
+ test('scoreSkillOnTasks propagates the all-failed error too', async () => {
+ await expect(
+ scoreSkillOnTasks({
+ engine: {} as never,
+ skillText: 'skill',
+ tasks: TASKS,
+ targetModel: 'claude-cli:claude-sonnet-4-6',
+ runsPerTask: 1,
+ rolloutFn: loggedOutRollout,
+ }),
+ ).rejects.toThrow(new RegExp(`${SKILLOPT_ALL_ROLLOUTS_FAILED}.*Not logged in`));
+ });
+
+ test('every rollout carrying a judge_error throws skillopt_all_judge_errors', async () => {
+ const deadJudge = (async (trajectory: Trajectory): Promise<ScoredRollout> => ({
+ trajectory,
+ score: 0,
+ judge_error: 'llm_call_failed: 401 Unauthorized',
+ })) as never;
+ await expect(
+ runValidationGate({
+ engine: {} as never,
+ candidateSkillText: 'skill',
+ selSet: TASKS,
+ bestScore: -1,
+ targetModel: 'anthropic:claude-haiku-4-5',
+ judgeModel: 'anthropic:claude-sonnet-4-6',
+ runsPerTask: 1,
+ rolloutFn: (async () => okTrajectory('x y')) as never,
+ scoreFn: deadJudge,
+ }),
+ ).rejects.toThrow(new RegExp(`${SKILLOPT_ALL_JUDGE_ERRORS}.*401 Unauthorized`));
+ });
+
+ test('one judge_error out of two rollouts resolves (partial judge failure stays fail-open)', async () => {
+ const flakyJudge = (async (trajectory: Trajectory, judge: BenchmarkTask['judge']): Promise<ScoredRollout> => {
+ const arg = (judge as { checks: Array<{ arg: string }> }).checks[0]!.arg;
+ return arg === 'x'
+ ? { trajectory, score: 0, judge_error: 'llm_call_failed: timeout' }
+ : { trajectory, score: 1 };
+ }) as never;
+ const gate = await runValidationGate({
+ engine: {} as never,
+ candidateSkillText: 'skill',
+ selSet: TASKS,
+ bestScore: -1,
+ targetModel: 'anthropic:claude-haiku-4-5',
+ judgeModel: 'anthropic:claude-sonnet-4-6',
+ runsPerTask: 1,
+ rolloutFn: (async () => okTrajectory('x y')) as never,
+ scoreFn: flakyJudge,
+ });
+ expect(gate.selScore).toBe(0.5);
+ expect(gate.scoredRollouts).toHaveLength(2);
});
});
diff --git a/test/slug-unicode-scripts.test.ts b/test/slug-unicode-scripts.test.ts
index cee0d1d10e..7aec47f24c 100644
--- a/test/slug-unicode-scripts.test.ts
+++ b/test/slug-unicode-scripts.test.ts
@@ -1,6 +1,7 @@
import { describe, test, expect } from 'bun:test';
import { slugifySegment, slugifyPath } from '../src/core/sync.ts';
import { validatePageSlug } from '../src/core/operations.ts';
+import { normalizeBasename, buildBasenameIndex, queryBasenameIndex } from '../src/core/link-extraction.ts';
import { isValidHolder } from '../src/core/takes-fence.ts';
/**
@@ -145,3 +146,58 @@ describe('#3700: Hebrew niqqud + cantillation strip', () => {
expect(slugifySegment('ภาษาไทย')).toBe('ภาษาไทย');
});
});
+
+// Variation selectors — emoji VS1–VS16 (U+FE00–FE0F) and ideographic IVS
+// (U+E0100–E01EF) are Mn-category invisibles. #3417 kept \p{M} in
+// SLUG_WORD_CHARS to protect Devanagari matras / Thai vowels, so variation
+// selectors survive slugification too: a folder named `🗂️ entities`
+// (U+1F5C2 U+FE0F) emitted a slug with a leading invisible U+FE0F and forked
+// duplicate pages from clean-slug canon. Selectors never alter letter
+// identity, so stripping them is lossless for every script above.
+describe('variation selectors strip (emoji VS16 / ideographic IVS)', () => {
+ test('emoji + VS16 folder name lands on the clean slug', () => {
+ expect(slugifySegment('🗂️ entities')).toBe('entities');
+ // With and without VS16 converge on the same page.
+ expect(slugifySegment('🗂 entities')).toBe(slugifySegment('🗂️ entities'));
+ });
+
+ test('ideographic IVS strips too', () => {
+ // 巻 with an ideographic variation selector (U+E0101) vs bare.
+ expect(slugifySegment('巻\u{E0101}')).toBe('巻');
+ expect(slugifySegment('巻\u{E0101}')).toBe(slugifySegment('巻'));
+ });
+
+ test('emoji-only input still collapses to empty (VS16 no longer rescues it)', () => {
+ expect(slugifySegment('🗂️')).toBe('');
+ expect(slugifySegment('🎉\uFE0F')).toBe('');
+ });
+
+ test('diacritic-bearing scripts unaffected by the strip', () => {
+ expect(slugifySegment('café')).toBe('cafe');
+ expect(slugifySegment('בְּרֵאשִׁית')).toBe('בראשית'); // niqqud still strips
+ expect(slugifySegment('हिन्दी')).toBe('हिन्दी'); // Devanagari matras preserved
+ expect(slugifySegment('한글'.normalize('NFD'))).toBe('한글'); // Hangul recomposition preserved
+ expect(slugifySegment('ภาษาไทย')).toBe('ภาษาไทย'); // Thai vowels preserved
+ });
+
+ test('NFC and NFD emoji filenames converge', () => {
+ expect(slugifySegment('🗂️ entities'.normalize('NFC'))).toBe('entities');
+ expect(slugifySegment('🗂️ entities'.normalize('NFD'))).toBe('entities');
+ });
+
+ test('emitted slugs are ACCEPTED by validatePageSlug', () => {
+ expect(() => validatePageSlug(slugifyPath('🗂️ entities/README.md'))).not.toThrow();
+ });
+});
+
+// The global-basename index (`[[wikilink]]` → page) keys and looks up through
+// normalizeBasename, the '#4855 twin' of slugifySegment built from the same
+// SLUG_WORD_CHARS. It must strip the selectors too, or Obsidian's own
+// `[[✏️ Drafts]]` misses the now-clean `drafts` page (fails on unpatched
+// master AND with a sync.ts-only strip).
+describe('variation selectors strip in the basename twin grammar', () => {
+ test('normalizeBasename and the basename index converge with slugifySegment', () => {
+ expect(normalizeBasename('✏️ Drafts')).toBe('drafts');
+ expect(queryBasenameIndex(buildBasenameIndex(['notes/drafts']), '✏️ Drafts')).toEqual(['notes/drafts']);
+ });
+});
diff --git a/test/sync-all-parallel.test.ts b/test/sync-all-parallel.test.ts
index 148c44cb5d..72dc6c4a46 100644
--- a/test/sync-all-parallel.test.ts
+++ b/test/sync-all-parallel.test.ts
@@ -192,6 +192,24 @@ describe('buildSyncStatusReport', () => {
expect(byId.get('never')!.staleness_hours).toBeNull();
});
+ // #4399 predicate parity: status.ts and the skills-catalog snapshot hand this
+ // function RAW `SELECT config` rows, and PGLite returns jsonb as a JSON
+ // string. A raw `.syncEnabled` cast reads undefined on that shape and reports
+ // a disabled source as enabled while `sync --all` (isSyncDisabledConfig)
+ // skips it — two surfaces contradicting each other on the same row.
+ test('sync_enabled reads a PGLite JSON-string config through the shared predicate', async () => {
+ const sources = [
+ { id: 'off', name: 'off', local_path: '/tmp/off', config: JSON.stringify({ syncEnabled: false }) },
+ { id: 'on', name: 'on', local_path: '/tmp/on', config: JSON.stringify({ syncEnabled: true }) },
+ { id: 'obj_off', name: 'obj_off', local_path: '/tmp/obj_off', config: { syncEnabled: false } },
+ ];
+ const report = await buildSyncStatusReport(makeEngine({}), sources);
+ const byId = new Map(report.sources.map((s) => [s.source_id, s]));
+ expect(byId.get('off')!.sync_enabled).toBe(false);
+ expect(byId.get('on')!.sync_enabled).toBe(true);
+ expect(byId.get('obj_off')!.sync_enabled).toBe(false);
+ });
+
// v0.41.32.0 (supersedes #1623): buildSyncStatusReport backs the REMOTE
// get_status_snapshot MCP op, so staleness reads the stored newest_content_at
// column (NO git subprocess on a DB-supplied local_path). The makeEngine stub
diff --git a/test/sync-cost-gate.serial.test.ts b/test/sync-cost-gate.serial.test.ts
index 68c16d4fda..a35c67d3f0 100644
--- a/test/sync-cost-gate.serial.test.ts
+++ b/test/sync-cost-gate.serial.test.ts
@@ -256,8 +256,11 @@ describe('v0.41.31 — sync --all cost gate wiring', () => {
expect(exitCode).not.toBe(2);
expect(stdout).toContain('"gate":"below_floor"');
+ // #4684: the gate object is nested in the ONE envelope, never a second document.
+ expect(jsonLines(stdout)).toHaveLength(1);
const final = jsonLines(stdout).find((line) => line.schema_version === 1 && Array.isArray(line.sources));
expect(final).toBeDefined();
+ expect(final!.cost_gate).toMatchObject({ gate: 'below_floor', mode: 'inline' });
expect(final!.sources).toEqual([
expect.objectContaining({
source_id: 'vault',
@@ -374,8 +377,10 @@ describe('v0.41.31 — sync --all cost gate wiring', () => {
console.log = origLog;
}
- const notice = jsonLines(out.join('\n')).find((line) => line.gate === 'manual_drain_required');
- expect(notice).toMatchObject({
+ // #4684: under --json the gate returns its notice for the envelope instead
+ // of printing a second top-level document.
+ expect(out).toHaveLength(0);
+ expect(plan!.costGate).toMatchObject({
status: 'manual_drain_required',
workerSurface: 'worker_backed',
reason: 'auto_submit_disabled',
@@ -579,11 +584,14 @@ describe('v0.41.31 — sync --all cost gate wiring', () => {
expect(exitCode).not.toBe(2);
expect(stdout).toContain('"gate":"below_floor"');
+ // #4684: one top-level JSON document; the gate rides inside it as cost_gate.
+ expect(jsonLines(stdout)).toHaveLength(1);
const final = jsonLines(stdout).find((line) => line.schema_version === 1 && line.source_id === 'vault');
expect(final).toMatchObject({
sync_status: 'synced',
added: 101,
embedded: 0,
+ cost_gate: { gate: 'below_floor', mode: 'inline' },
embed_backfill: {
status: 'manual_drain_required',
command: 'gbrain embed --stale --source vault',
diff --git a/test/sync-include-hidden-config.test.ts b/test/sync-include-hidden-config.test.ts
new file mode 100644
index 0000000000..21f548877b
--- /dev/null
+++ b/test/sync-include-hidden-config.test.ts
@@ -0,0 +1,255 @@
+/**
+ * The hidden-path WAIVER must reach callers that never touch the CLI (#4901).
+ *
+ * `--include-hidden` is a per-invocation flag. `sync.exclude` already has a
+ * persisted twin so autopilot, minion sync jobs and the dream cycle inherit an
+ * operator's narrowing; the waiver has none, so an operator who wants a
+ * committed `.github/` indexed can say so on one code path and nowhere else.
+ *
+ * The gap is sharper than "less convenient". `sync --all` REFUSES the flag
+ * outright — "--src-subpath/--exclude/--include-hidden scope a single sync
+ * invocation; they cannot be combined with --all" — and `--all` is the form a
+ * scheduled sync uses. So today the waiver cannot be expressed at all on the
+ * only path that runs unattended.
+ *
+ * THE DEFAULT DOES NOT MOVE. An unset key admits nothing, exactly as today.
+ * This is the plumbing for an opt-in that already exists, not the product
+ * decision about whether dot-directories should be indexed by default, which
+ * #4901 leaves to the maintainer.
+ *
+ * Under test:
+ * 1. Baseline — with no config and no flag, a committed dot-directory is not
+ * indexed. Without this, case 2 could pass because the file never landed.
+ * 2. `sync.include_hidden` is honored with NO flag passed.
+ * 3. A trailing slash is normalized to a subtree glob, as `sync.exclude` is:
+ * `.github/` without the `**` matches the directory entry and none of the
+ * files inside it — silent, and indistinguishable from the feature not
+ * working.
+ * 4. A per-call flag UNIONS with the persisted waiver rather than replacing
+ * it, so an ad-hoc admission never silently closes one the operator
+ * persisted.
+ * 5. The waiver is scoped: a dot-directory the operator did NOT name stays
+ * pruned. A test that only proves admission would pass on a change that
+ * admits everything.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from 'fs';
+import { execSync } from 'child_process';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { performSync } from '../src/commands/sync.ts';
+import { runSources } from '../src/commands/sources.ts';
+
+let engine: PGLiteEngine;
+let repoPath: string;
+const SOURCE_ID = 'testsrc-inchid-cfg';
+
+function commitAll(msg: string): void {
+ execSync('git add -A', { cwd: repoPath, stdio: 'pipe' });
+ execSync(`git commit -m "${msg}"`, { cwd: repoPath, stdio: 'pipe' });
+}
+
+async function pageExists(slug: string): Promise<boolean> {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM pages WHERE slug = $1 AND source_id = $2 AND deleted_at IS NULL`,
+ [slug, SOURCE_ID],
+ );
+ return Number(rows[0]?.n ?? 0) > 0;
+}
+
+/** No `includeHidden` key: this is exactly what an internal caller passes. */
+const baseOpts = () => ({
+ repoPath,
+ sourceId: SOURCE_ID,
+ noPull: true,
+ noEmbed: true,
+ noExtract: true,
+});
+
+describe('sync.include_hidden config reaches non-CLI callers', () => {
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await runSources(engine, ['add', SOURCE_ID, '--no-federated']);
+
+ repoPath = mkdtempSync(join(tmpdir(), 'gbrain-inchid-cfg-'));
+ execSync('git init', { cwd: repoPath, stdio: 'pipe' });
+ execSync('git config user.email "[email protected]"', { cwd: repoPath, stdio: 'pipe' });
+ execSync('git config user.name "T"', { cwd: repoPath, stdio: 'pipe' });
+ mkdirSync(join(repoPath, 'notes'), { recursive: true });
+ writeFileSync(join(repoPath, 'notes/base.md'), '# Base\n\ncommitted\n');
+ commitAll('base');
+
+ const first = await performSync(engine, baseOpts());
+ expect(first.status).toBe('first_sync');
+ expect(await pageExists('notes/base')).toBe(true);
+ }, 120_000);
+
+ afterAll(async () => {
+ if (engine) await engine.disconnect();
+ if (repoPath) rmSync(repoPath, { recursive: true, force: true });
+ }, 60_000);
+
+ test('baseline: with no config and no flag, a dot-directory is not indexed', async () => {
+ mkdirSync(join(repoPath, '.github/workflows'), { recursive: true });
+ writeFileSync(join(repoPath, '.github/workflows/ci.md'), '# CI\n\nbaseline\n');
+ writeFileSync(join(repoPath, 'notes/sibling.md'), '# Sibling\n\nindexed\n');
+ commitAll('dot-dir baseline');
+
+ await performSync(engine, baseOpts());
+
+ expect(await pageExists('.github/workflows/ci')).toBe(false);
+ // The control: the same commit's non-hidden file DID land, so a false in
+ // the line above is the prune and not a sync that did nothing.
+ expect(await pageExists('notes/sibling')).toBe(true);
+ }, 60_000);
+
+ test('persisted sync.include_hidden is honored with no flag passed', async () => {
+ await engine.setConfig('sync.include_hidden', '.github/');
+
+ writeFileSync(join(repoPath, '.github/workflows/release.md'), '# Release\n\nmust be indexed\n');
+ commitAll('release workflow');
+
+ await performSync(engine, baseOpts());
+
+ // The whole point: no caller passed --include-hidden, and the waiver held.
+ expect(await pageExists('.github/workflows/release')).toBe(true);
+ }, 60_000);
+
+ test('a trailing slash covers the files inside, not just the directory entry', async () => {
+ mkdirSync(join(repoPath, '.github/ISSUE_TEMPLATE'), { recursive: true });
+ writeFileSync(join(repoPath, '.github/ISSUE_TEMPLATE/bug.md'), '# Bug\n\nnested\n');
+ commitAll('nested template');
+
+ await performSync(engine, baseOpts());
+
+ // LOWERCASED, underscores kept: the slug for `.github/ISSUE_TEMPLATE/bug.md`
+ // is `.github/issue_template/bug`. The directory keeps GitHub's real casing
+ // on disk on purpose — asserting the on-disk spelling here is how this case
+ // first failed, and it read exactly like the waiver not reaching nested paths.
+ expect(await pageExists('.github/issue_template/bug')).toBe(true);
+ }, 60_000);
+
+ test('an unnamed dot-directory stays pruned', async () => {
+ // Scope, not blanket admission. Without this a change that waived every
+ // dot-prefixed directory would pass every case above.
+ mkdirSync(join(repoPath, '.vscode'), { recursive: true });
+ writeFileSync(join(repoPath, '.vscode/notes.md'), '# Editor\n\nmust stay out\n');
+ commitAll('vscode');
+
+ await performSync(engine, baseOpts());
+
+ expect(await pageExists('.vscode/notes')).toBe(false);
+ }, 60_000);
+
+ test('a per-call flag unions with the persisted waiver', async () => {
+ mkdirSync(join(repoPath, '.claude'), { recursive: true });
+ writeFileSync(join(repoPath, '.claude/adhoc.md'), '# Ad hoc\n\nadmitted by the flag\n');
+ writeFileSync(join(repoPath, '.github/workflows/union.md'), '# Union\n\nadmitted by the config\n');
+ commitAll('union case');
+
+ await performSync(engine, { ...baseOpts(), includeHidden: ['.claude/**'] });
+
+ // The flag admits its own path AND does not close the persisted one.
+ expect(await pageExists('.claude/adhoc')).toBe(true);
+ expect(await pageExists('.github/workflows/union')).toBe(true);
+ }, 60_000);
+});
+
+/**
+ * FIRST-SYNC pin (mirrors sync-exclude-config): the waiver union must resolve
+ * ABOVE performSyncInner's performFullSync early returns, or the very first
+ * sync's full walk prunes the persisted dot-directory and no later incremental
+ * sync revisits it. Fresh engine + repo so the key is persisted BEFORE any sync
+ * has run. The second case pins the catch branch: a throwing getConfig degrades
+ * to "no waiver", never to a failed sync.
+ */
+describe('sync.include_hidden — first-sync full walk + getConfig throw', () => {
+ let fsEngine: PGLiteEngine;
+ let fsRepoPath: string;
+ const FS_SOURCE_ID = 'testsrc-inchid-first';
+
+ function fsCommitAll(msg: string): void {
+ execSync('git add -A', { cwd: fsRepoPath, stdio: 'pipe' });
+ execSync(`git commit -m "${msg}"`, { cwd: fsRepoPath, stdio: 'pipe' });
+ }
+
+ async function fsPageExists(slug: string): Promise<boolean> {
+ const rows = await fsEngine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM pages WHERE slug = $1 AND source_id = $2 AND deleted_at IS NULL`,
+ [slug, FS_SOURCE_ID],
+ );
+ return Number(rows[0]?.n ?? 0) > 0;
+ }
+
+ const fsOpts = () => ({
+ repoPath: fsRepoPath,
+ sourceId: FS_SOURCE_ID,
+ noPull: true,
+ noEmbed: true,
+ noExtract: true,
+ });
+
+ beforeAll(async () => {
+ fsEngine = new PGLiteEngine();
+ await fsEngine.connect({});
+ await fsEngine.initSchema();
+ await runSources(fsEngine, ['add', FS_SOURCE_ID, '--no-federated']);
+
+ fsRepoPath = mkdtempSync(join(tmpdir(), 'gbrain-inchid-first-'));
+ execSync('git init', { cwd: fsRepoPath, stdio: 'pipe' });
+ execSync('git config user.email "[email protected]"', { cwd: fsRepoPath, stdio: 'pipe' });
+ execSync('git config user.name "T"', { cwd: fsRepoPath, stdio: 'pipe' });
+ mkdirSync(join(fsRepoPath, 'notes'), { recursive: true });
+ mkdirSync(join(fsRepoPath, '.github/workflows'), { recursive: true });
+ mkdirSync(join(fsRepoPath, '.vscode'), { recursive: true });
+ writeFileSync(join(fsRepoPath, 'notes/kept.md'), '# Kept\n\nindexed on first sync\n');
+ writeFileSync(join(fsRepoPath, '.github/workflows/ci.md'), '# CI\n\nwaived on first sync\n');
+ writeFileSync(join(fsRepoPath, '.vscode/notes.md'), '# Editor\n\nstill pruned\n');
+ fsCommitAll('first');
+ }, 120_000);
+
+ afterAll(async () => {
+ if (fsEngine) await fsEngine.disconnect();
+ if (fsRepoPath) rmSync(fsRepoPath, { recursive: true, force: true });
+ }, 60_000);
+
+ test('persisted waiver admits on the first full walk with no flag passed; an unnamed dot-directory stays pruned', async () => {
+ // Persist the waiver BEFORE any sync has run — the trailing '/' also pins
+ // the subtree-glob normalization on this path.
+ await fsEngine.setConfig('sync.include_hidden', '.github/');
+
+ const first = await performSync(fsEngine, fsOpts());
+ expect(first.status).toBe('first_sync');
+
+ expect(await fsPageExists('notes/kept')).toBe(true);
+ expect(await fsPageExists('.github/workflows/ci')).toBe(true);
+ expect(await fsPageExists('.vscode/notes')).toBe(false);
+ }, 60_000);
+
+ test('getConfig THROWING degrades to no waiver: the sync completes and the dot-directory is NOT admitted', async () => {
+ const originalGetConfig = fsEngine.getConfig.bind(fsEngine);
+ fsEngine.getConfig = (async (key: string): Promise<string | null> => {
+ if (key === 'sync.include_hidden') throw new Error('config table unavailable (injected)');
+ return originalGetConfig(key);
+ }) as typeof fsEngine.getConfig;
+
+ try {
+ writeFileSync(join(fsRepoPath, '.github/workflows/late.md'), '# Late\n\nnot admitted: the waiver read failed\n');
+ writeFileSync(join(fsRepoPath, 'notes/after.md'), '# After\n\nindexed\n');
+ fsCommitAll('late hidden file');
+
+ const result = await performSync(fsEngine, fsOpts());
+ // 1. The sync COMPLETED (never break a sync over the scope read).
+ expect(result.status).toBe('synced');
+ expect(await fsPageExists('notes/after')).toBe(true);
+ // 2. No waiver was applied: the dot-directory file stayed pruned.
+ expect(await fsPageExists('.github/workflows/late')).toBe(false);
+ } finally {
+ fsEngine.getConfig = originalGetConfig;
+ }
+ }, 60_000);
+});
diff --git a/test/sync-index-matches-tree.serial.test.ts b/test/sync-index-matches-tree.serial.test.ts
index 2188e9d557..6f2a9c80d3 100644
--- a/test/sync-index-matches-tree.serial.test.ts
+++ b/test/sync-index-matches-tree.serial.test.ts
@@ -214,3 +214,108 @@ describe('strategy precedence', () => {
expect(await slugsFor('prec-bogus')).toEqual(['docs/x']);
}, 120_000);
});
+
+describe('un-syncable sweep is reported (#4786)', () => {
+ test('a run whose only effect is soft-deleting code pages reports deleted=N and status synced, never up_to_date', async () => {
+ await ensureSetup();
+ const { performSync } = await import('../src/commands/sync.ts');
+ const r = mkMixedRepo();
+ await addSource('sweep-count', 'auto', r);
+ await performSync(engine!, { repoPath: r, ...OPTS, sourceId: 'sweep-count' });
+ expect(await slugsFor('sweep-count')).toEqual(['docs/x', 'lib-x-ts']);
+
+ // Edit ONLY the code file, then sync under a narrower strategy: the page
+ // is un-syncable now, so the cleanup loop soft-deletes it. That sweep is
+ // the run's only effect and must be what the result reports.
+ writeFileSync(join(r, 'lib/x.ts'), 'export const x = 2;\n');
+ execSync('git add -A && git commit -qm edit', { cwd: r, stdio: 'pipe' });
+ const res = await performSync(engine!, {
+ repoPath: r, ...OPTS, sourceId: 'sweep-count', strategy: 'markdown',
+ });
+ expect(await slugsFor('sweep-count')).toEqual(['docs/x']);
+ expect(res.deleted).toBe(1);
+ expect(res.status).toBe('synced');
+ }, 120_000);
+
+ test('a failed pull on a sweep-only run reports partial/pull_failed AND carries deleted=N (not zeroed)', async () => {
+ await ensureSetup();
+ const { performSync } = await import('../src/commands/sync.ts');
+ // Local-path origin: pullRepo always passes `protocol.file.allow=never`,
+ // so its internal pull fails deterministically (the #3068 topology) while
+ // the working tree still imports. Pull is ENABLED here (no noPull).
+ const upstream = mkMixedRepo();
+ const mirror = mkdtempSync(join(tmpdir(), 'gb-tw-mirror-'));
+ extraRepos.push(mirror);
+ rmSync(mirror, { recursive: true, force: true });
+ execSync(`git clone -q ${JSON.stringify(upstream)} ${JSON.stringify(mirror)}`, { stdio: 'pipe' });
+ execSync('git config user.email t@t && git config user.name T', { cwd: mirror, stdio: 'pipe' });
+ const PULL_OPTS = { noEmbed: true, noExtract: true, sourceId: 'sweep-pull' } as const;
+ await addSource('sweep-pull', 'auto', mirror);
+ const first = await performSync(engine!, { repoPath: mirror, ...PULL_OPTS });
+ expect(first.status).toBe('first_sync');
+ expect(await slugsFor('sweep-pull')).toEqual(['docs/x', 'lib-x-ts']);
+
+ writeFileSync(join(mirror, 'lib/x.ts'), 'export const x = 2;\n');
+ execSync('git add -A && git commit -qm edit', { cwd: mirror, stdio: 'pipe' });
+ const res = await performSync(engine!, { repoPath: mirror, ...PULL_OPTS, strategy: 'markdown' });
+ expect(await slugsFor('sweep-pull')).toEqual(['docs/x']);
+ expect(res.status).toBe('partial');
+ expect(res.reason).toBe('pull_failed');
+ // #4786's invariant holds on this early return too: the sweep is the
+ // run's only effect and must be what the result reports.
+ expect(res.deleted).toBe(1);
+ }, 120_000);
+});
+
+describe('sweep-only sync must not mint an embed-backfill (#4786 x #2139)', () => {
+ test('syncProducedEmbeddableContent is false for sweep/delete-only results, true for imports', async () => {
+ const { syncProducedEmbeddableContent } = await import('../src/core/sync-embed-backfill.ts');
+ const zero = { chunksCreated: 0, added: 0, modified: 0, renamed: 0 };
+ expect(syncProducedEmbeddableContent(zero)).toBe(false);
+ expect(syncProducedEmbeddableContent({ ...zero, added: 1 })).toBe(true);
+ expect(syncProducedEmbeddableContent({ ...zero, modified: 1 })).toBe(true);
+ expect(syncProducedEmbeddableContent({ ...zero, renamed: 1 })).toBe(true);
+ expect(syncProducedEmbeddableContent({ ...zero, chunksCreated: 3 })).toBe(true);
+ });
+
+ test('jobs sync handler: a sweep-only run skips the submitter (no_new_content); an importing run still reaches it', async () => {
+ await ensureSetup();
+ const { registerBuiltinHandlers } = await import('../src/commands/jobs.ts');
+ type Handler = (job: unknown) => Promise<unknown>;
+ const handlers = new Map<string, Handler>();
+ const worker = { register: (name: string, fn: Handler) => { handlers.set(name, fn); } };
+ await registerBuiltinHandlers(worker as never, engine!, { quiet: true });
+ const runSync = (data: Record<string, unknown>) => handlers.get('sync')!({
+ id: 1, name: 'sync', data, attempts_made: 0, deadlineAtMs: null,
+ signal: new AbortController().signal, shutdownSignal: new AbortController().signal,
+ updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {},
+ isActive: async () => true, readInbox: async () => [],
+ }) as Promise<{ status: string; deleted: number; embed_job_id: number | null; embed_skip_reason: string | null }>;
+
+ const r = mkMixedRepo();
+ await addSource('sweep-backfill', 'auto', r);
+ const first = await runSync({ repoPath: r, sourceId: 'sweep-backfill', noPull: true });
+ expect(first.status).toBe('first_sync');
+ // PGLite has no worker surface, so the SUBMITTER refuses — which proves
+ // the handler reached it: an import passes the content gate.
+ expect(first.embed_skip_reason).toBe('no_worker_surface');
+
+ // The handler takes no strategy from job data; narrow the PERSISTED
+ // strategy (honored per #4903) so the edited code page is un-syncable
+ // and the run's only effect is the #4786 sweep.
+ await engine!.executeRaw(
+ `UPDATE sources SET config = config || '{"strategy":"markdown"}'::jsonb WHERE id = $1`,
+ ['sweep-backfill'],
+ );
+ writeFileSync(join(r, 'lib/x.ts'), 'export const x = 2;\n');
+ execSync('git add -A && git commit -qm edit', { cwd: r, stdio: 'pipe' });
+ const swept = await runSync({ repoPath: r, sourceId: 'sweep-backfill', noPull: true });
+ expect(await slugsFor('sweep-backfill')).toEqual(['docs/x']);
+ expect(swept.status).toBe('synced');
+ expect(swept.deleted).toBe(1);
+ // Nothing was created to embed: minting a backfill here would start the
+ // per-source cooldown and make the NEXT real import's job skip.
+ expect(swept.embed_job_id).toBeNull();
+ expect(swept.embed_skip_reason).toBe('no_new_content');
+ }, 120_000);
+});
diff --git a/test/sync-inline-extract-stamps.serial.test.ts b/test/sync-inline-extract-stamps.serial.test.ts
index 9a9db50826..5798178d22 100644
--- a/test/sync-inline-extract-stamps.serial.test.ts
+++ b/test/sync-inline-extract-stamps.serial.test.ts
@@ -18,6 +18,12 @@
* pages it processed, and (b) the existing link extraction is unchanged. Plus
* --no-extract: the changed page stays unstamped AND no links are created.
*
+ * The last two tests pin the slug-is-not-a-path contract of the sync hooks: a
+ * page whose filename does not round-trip through slugification (`Widget
+ * Co.md` → `companies/widget-co`) must still be read from its REAL path, and a
+ * slug with no file behind it must be reported as unprocessed so the caller
+ * leaves it stale instead of stamping it fresh.
+ *
* Marked .serial.test.ts — spawns git subprocesses + shares one PGLite engine.
*/
@@ -114,4 +120,109 @@ describe('#1696 — inline sync extract stamps links_extracted_at', () => {
expect(await engine.getLinks('companies/acme')).toHaveLength(0);
expect(await stampOf('companies/acme')).toBeNull();
}, 60_000);
+
+ test('a filename that does not round-trip through slugification still extracts', async () => {
+ const { performSync } = await import('../src/commands/sync.ts');
+ // `Widget Co.md` slugs to `widget-co`: the space becomes a hyphen and the
+ // capitals drop. Rebuilding the disk path from the slug looks for
+ // `companies/widget-co.md`, which does not exist on ANY filesystem — so
+ // the page used to be skipped without a word and stamped anyway.
+ writeFileSync(join(repoPath, 'companies/Widget Co.md'), [
+ '---', 'type: company', 'title: Widget Co', '---', '',
+ '[Alice](../people/alice.md) is the CEO of Widget Co.',
+ ].join('\n'));
+ git('git add -A && git commit -m "add widget co"');
+ const result = await performSync(engine, { repoPath, noPull: true, noEmbed: true });
+ expect(['synced', 'first_sync']).toContain(result.status);
+
+ // The page imported under its slugified slug either way.
+ const pages = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE slug = 'companies/widget-co' AND source_id = 'default'`,
+ );
+ expect(pages).toHaveLength(1);
+
+ // The edge is what the reconstructed path lost.
+ const links = await engine.getLinks('companies/widget-co');
+ expect(links.some(l => l.to_slug === 'people/alice')).toBe(true);
+ expect(await stampOf('companies/widget-co')).not.toBeNull();
+ }, 60_000);
+
+ test('a slug with no file behind it is reported unprocessed, so it is never stamped', async () => {
+ const { extractLinksForSlugs, extractTimelineForSlugs, slugsSafeToStamp } =
+ await import('../src/commands/extract.ts');
+
+ const links = await extractLinksForSlugs(
+ engine, repoPath, ['companies/acme', 'companies/ghost'],
+ );
+ const timeline = await extractTimelineForSlugs(
+ engine, repoPath, ['companies/acme', 'companies/ghost'],
+ );
+
+ // companies/acme.md is on disk from the fixture; companies/ghost.md is not.
+ expect(links.processed).toEqual(['companies/acme']);
+ expect(timeline.processed).toEqual(['companies/acme']);
+ expect(slugsSafeToStamp(links, timeline)).toEqual(['companies/acme']);
+ }, 60_000);
+
+ // Pre-landing review of #4967: the slug index is built from
+ // walkMarkdownFiles, which drops `_`-prefixed filenames and hidden dirs —
+ // but sync ADMITS both (`_note.md` always; `.github/**` via includeHidden).
+ // An index miss must fall back to the legacy `slug + '.md'` path before the
+ // page is declared missing, or the page imports without its edges.
+ test('an admitted `_`-prefixed page still extracts and is stamped', async () => {
+ const { performSync } = await import('../src/commands/sync.ts');
+ writeFileSync(join(repoPath, '_note.md'), [
+ '---', 'type: note', 'title: Note', '---', '',
+ '[Alice](people/alice.md) is mentioned in this note.',
+ ].join('\n'));
+ git('git add -A && git commit -m "add underscore note"');
+ const result = await performSync(engine, { repoPath, noPull: true, noEmbed: true });
+ expect(['synced', 'first_sync']).toContain(result.status);
+
+ const pages = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE slug = '_note' AND source_id = 'default'`,
+ );
+ expect(pages).toHaveLength(1);
+ const links = await engine.getLinks('_note');
+ expect(links.some(l => l.to_slug === 'people/alice')).toBe(true);
+ expect(await stampOf('_note')).not.toBeNull();
+ }, 60_000);
+
+ test('an includeHidden-admitted page under a dot-dir still extracts and is stamped', async () => {
+ const { performSync } = await import('../src/commands/sync.ts');
+ mkdirSync(join(repoPath, '.github'), { recursive: true });
+ writeFileSync(join(repoPath, '.github/note.md'), [
+ '---', 'type: note', 'title: Hidden Note', '---', '',
+ '[Alice](../people/alice.md) is mentioned in this hidden note.',
+ ].join('\n'));
+ git('git add -A && git commit -m "add hidden note"');
+ const result = await performSync(engine, {
+ repoPath, noPull: true, noEmbed: true, includeHidden: ['.github/**'],
+ });
+ expect(['synced', 'first_sync']).toContain(result.status);
+
+ const pages = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE slug = '.github/note' AND source_id = 'default'`,
+ );
+ expect(pages).toHaveLength(1);
+ const links = await engine.getLinks('.github/note');
+ expect(links.some(l => l.to_slug === 'people/alice')).toBe(true);
+ expect(await stampOf('.github/note')).not.toBeNull();
+ }, 60_000);
+
+ test('the legacy-path fallback reports only slugs with a file behind them as processed', async () => {
+ const { extractLinksForSlugs, extractTimelineForSlugs, slugsSafeToStamp } =
+ await import('../src/commands/extract.ts');
+ writeFileSync(join(repoPath, '_note.md'), '[Alice](people/alice.md) again.');
+ mkdirSync(join(repoPath, '.github'), { recursive: true });
+ writeFileSync(join(repoPath, '.github/note.md'), '[Alice](../people/alice.md) again.');
+
+ const slugs = ['_note', '.github/note', 'companies/ghost', 'companies/acme'];
+ const links = await extractLinksForSlugs(engine, repoPath, slugs);
+ const timeline = await extractTimelineForSlugs(engine, repoPath, slugs);
+
+ expect(links.processed).toEqual(['_note', '.github/note', 'companies/acme']);
+ expect(timeline.processed).toEqual(['_note', '.github/note', 'companies/acme']);
+ expect(slugsSafeToStamp(links, timeline)).toEqual(['_note', '.github/note', 'companies/acme']);
+ }, 60_000);
});
diff --git a/test/sync-json-stdout-clean.test.ts b/test/sync-json-stdout-clean.test.ts
index f2cf0deeae..8651da9ab5 100644
--- a/test/sync-json-stdout-clean.test.ts
+++ b/test/sync-json-stdout-clean.test.ts
@@ -2,8 +2,9 @@
* #4888 — `gbrain sync --json` must keep stdout pure JSON. Every human line
* performSync emits through slog() used to land on stdout AHEAD of the
* envelope, so the documented `--json | jq` contract failed on the success
- * path. Under --json those lines route to stderr; JSON lines (a cost-gate
- * status line, the final envelope) stay on stdout.
+ * path. Under --json those lines route to stderr; the final envelope is the
+ * ONLY stdout document (#4684: the cost-gate status object rides inside it as
+ * `cost_gate`, never as a second top-level JSON value).
*
* Real PGLite + a real git repo through the CLI entry (`runSync`): the leak
* is a property of the whole command path, not of one helper.
@@ -14,6 +15,7 @@ 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 { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
import { withEnv } from './helpers/with-env.ts';
let engine: PGLiteEngine;
@@ -150,6 +152,31 @@ describe('#4888: sync --json keeps stdout pure JSON', () => {
expect(stderr.join('')).toContain('Acknowledged 1 pre-existing failure(s).');
}, 60_000);
+ test('#4684: a --json run that reaches the cost gate emits exactly ONE document, gate nested as cost_gate', async () => {
+ // The issue's repro: Git-backed source, nothing new to embed -> the gate
+ // takes below_floor, then the envelope. Pre-fix stdout was two documents.
+ // A dummy key satisfies the pre-gate credential preflight; the up_to_date
+ // path never reaches an embed call, so nothing networks.
+ await run(['--no-pull', '--no-embed']);
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { OPENAI_API_KEY: 'sk-test-4684' },
+ });
+ let stdout: string[];
+ try {
+ ({ stdout } = await run(['--no-pull', '--json']));
+ } finally {
+ resetGateway();
+ }
+ const out = lines(stdout);
+ expect(out).toHaveLength(1);
+ const env = JSON.parse(out[0]) as Record<string, unknown>;
+ expect(env.schema_version).toBe(1);
+ expect(env.sync_status).toBe('up_to_date');
+ expect(env.cost_gate).toMatchObject({ gate: 'below_floor', mode: 'inline' });
+ }, 60_000);
+
test('sync trigger --source <id> --json prints one JSON line with job_id on stdout', async () => {
const { stdout } = await run(['trigger', '--source', 'default', '--json']);
const out = lines(stdout);
diff --git a/test/sync-policy.test.ts b/test/sync-policy.test.ts
new file mode 100644
index 0000000000..3e4fb5b546
--- /dev/null
+++ b/test/sync-policy.test.ts
@@ -0,0 +1,37 @@
+/**
+ * #4399: isSyncDisabledConfig — the shared predicate for
+ * config.syncEnabled === false, read by autopilot's freshness dispatcher
+ * and the `sync --all` fan-out filter (sync-cost-gate.ts's separate inline
+ * check is deliberately untouched — see sync-policy.ts's module doc).
+ */
+import { describe, expect, test } from 'bun:test';
+import { isSyncDisabledConfig } from '../src/core/sync-policy.ts';
+
+describe('isSyncDisabledConfig', () => {
+ test('true when config.syncEnabled is explicitly false', () => {
+ expect(isSyncDisabledConfig({ syncEnabled: false })).toBe(true);
+ });
+
+ test('false when syncEnabled is absent (the common case)', () => {
+ expect(isSyncDisabledConfig({})).toBe(false);
+ expect(isSyncDisabledConfig(undefined)).toBe(false);
+ expect(isSyncDisabledConfig(null)).toBe(false);
+ });
+
+ test('false when syncEnabled is explicitly true', () => {
+ expect(isSyncDisabledConfig({ syncEnabled: true })).toBe(false);
+ });
+
+ test('false when other unrelated config keys are set', () => {
+ expect(isSyncDisabledConfig({ remote_url: 'https://example.com/repo.git', strategy: 'code' })).toBe(false);
+ });
+
+ test('handles a PGLite-shaped JSON-string config (parseSourceConfig unwraps it)', () => {
+ // PGLite's driver can hand back config as a JSON string scalar rather
+ // than an already-parsed object (see sourceConfigHasRemoteUrl's doc
+ // comment in sources-load.ts for the same pattern) — the predicate must
+ // unwrap it the same way, not just check `typeof config === 'object'`.
+ expect(isSyncDisabledConfig(JSON.stringify({ syncEnabled: false }))).toBe(true);
+ expect(isSyncDisabledConfig(JSON.stringify({ syncEnabled: true }))).toBe(false);
+ });
+});
diff --git a/test/sync-rename-reconcile.serial.test.ts b/test/sync-rename-reconcile.serial.test.ts
index 8077666bb6..e803850213 100644
--- a/test/sync-rename-reconcile.serial.test.ts
+++ b/test/sync-rename-reconcile.serial.test.ts
@@ -2739,3 +2739,38 @@ describe('#4597: a fallback rename\'s own stale duplicate converges under increm
expect(await engine.getPage('party-notes')).toBeNull();
});
});
+
+describe('#4588: a legacy row whose source_path names a pre-rename path self-heals on the next full sync', () => {
+ test('sync --full refreshes source_path on the unchanged-content skip instead of reconcile-deleting the live page', async () => {
+ const { performSync } = await import('../src/commands/sync.ts');
+ const repo = mkRepo({ 'people/alpha.md': personMd('Alpha', 'Alpha original body.') });
+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
+
+ // Cheap rename alpha -> beta, then recreate the LEGACY bookkeeping a
+ // pre-GATE13 brain still carries: the live beta row naming the OLD path
+ // (which git history once committed, so the reconcile may delete it).
+ execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });
+ execSync('git commit -m "cheap rename alpha to beta"', { cwd: repo, stdio: 'pipe' });
+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
+ await engine.executeRaw(
+ `UPDATE pages SET source_path = 'people/alpha.md'
+ WHERE source_id = 'default' AND slug = 'people/beta'`,
+ );
+
+ // Full sync: runImport sees people/beta.md unchanged (hash-equal skip),
+ // THEN the reconcile re-reads source_path. Pre-fix the skip wrote
+ // nothing, the reconcile read 'people/alpha.md' as "file removed" and
+ // soft-deleted the live page (the mass valve needs >20 pages to trip).
+ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS, full: true });
+ expect(result.status).toBe('first_sync');
+ const beta = await engine.getPage('people/beta');
+ expect(beta).not.toBeNull();
+ expect(beta!.compiled_truth).toContain('Alpha original body.');
+ const rows = await engine.executeRaw<{ source_path: string | null }>(
+ `SELECT source_path FROM pages
+ WHERE source_id = 'default' AND slug = 'people/beta' AND deleted_at IS NULL`,
+ );
+ expect(rows).toHaveLength(1);
+ expect(rows[0].source_path).toBe('people/beta.md');
+ });
+});
diff --git a/test/think-max-output-tokens.test.ts b/test/think-max-output-tokens.test.ts
index 789b87bd20..75a6f896ce 100644
--- a/test/think-max-output-tokens.test.ts
+++ b/test/think-max-output-tokens.test.ts
@@ -107,6 +107,15 @@ describe('maxOutputTokensFor — thinking-default headroom', () => {
expect(maxOutputTokensFor('zhipu:glm-4-plus')).toBe(4000);
expect(maxOutputTokensFor('zhipu:glm-3-turbo')).toBe(4000);
});
+
+ test('gbrain#4727 — GLM-4.5+/5.x behind the ollama and openrouter recipes get the same headroom', () => {
+ // The issue body names other prefixes exposing GLM; a reporter hit the
+ // 4000 cap on GLM-5.3-flash via Ollama cloud. Same predicate, same cap.
+ expect(maxOutputTokensFor('ollama:glm-5.3-flash:cloud')).toBe(16000);
+ expect(maxOutputTokensFor('ollama:glm-4.6')).toBe(16000);
+ expect(maxOutputTokensFor('openrouter:z-ai/glm-5')).toBe(16000);
+ expect(maxOutputTokensFor('ollama:glm-4:9b')).toBe(4000);
+ });
});
describe('runThink — max_tokens truncation labeling (gbrain#4375)', () => {
diff --git a/test/transcript-adapters.test.ts b/test/transcript-adapters.test.ts
index 62db0a3029..ac1c59aa14 100644
--- a/test/transcript-adapters.test.ts
+++ b/test/transcript-adapters.test.ts
@@ -358,6 +358,55 @@ describe('codexAdapter', () => {
expect(diag.skippedLines).toBeGreaterThanOrEqual(2);
});
+ // #4981: codex child rollouts (subagents / forks) carry their OWN payload.id
+ // but the ROOT session's payload.session_id, and inherit the parent's
+ // session_meta header later in the file. Identity must be payload.id with
+ // first-header-wins, or every child collapses onto the parent's page and
+ // ping-pongs it on each ingest pass.
+ test('forked rollouts keep their own identity: payload.id wins, first session_meta wins (#4981)', async () => {
+ const dir = tdir();
+ const T0 = '2026-08-02T09:00:00.000Z';
+ const T1 = '2026-08-02T10:00:00.000Z';
+ const header = (id: string, ts: string, cwd: string, extra: Record<string, unknown> = {}) =>
+ JSON.stringify({
+ timestamp: ts,
+ type: 'session_meta',
+ payload: { id, session_id: 'parent', timestamp: ts, cwd, cli_version: '0.150.0', ...extra },
+ });
+ const user = (ts: string, text: string) =>
+ JSON.stringify({ timestamp: ts, type: 'event_msg', payload: { type: 'user_message', message: text } });
+ const assistant = (ts: string, text: string) =>
+ JSON.stringify({
+ timestamp: ts,
+ type: 'response_item',
+ payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text }] },
+ });
+ const parentPath = join(dir, 'rollout-parent.jsonl');
+ const childPath = join(dir, 'rollout-child.jsonl');
+ writeFileSync(parentPath, [header('parent', T0, '/repo'), user(T0, 'parent question'), assistant(T0, 'parent answer')].join('\n') + '\n');
+ writeFileSync(
+ childPath,
+ [
+ header('child', T1, '/repo/child', { forked_from_id: 'parent', parent_thread_id: 'parent' }),
+ header('parent', T0, '/repo'), // inherited parent header copied into the child
+ user(T1, 'child question'),
+ assistant(T1, 'child answer'),
+ ].join('\n') + '\n',
+ );
+ const parent = (await drain(codexAdapter.parse(parentPath))).sessions[0]!;
+ const child = (await drain(codexAdapter.parse(childPath))).sessions[0]!;
+ expect(parent.meta.sessionId).toBe('parent');
+ expect(child.meta.sessionId).toBe('child');
+ // First header wins: the inherited parent header must not rewrite identity, cwd, or start.
+ expect(child.meta.startedAt).toBe(T1);
+ expect(child.meta.cwd).toBe('/repo/child');
+ expect(child.messages.map((m) => m.text)).toEqual(['child question', 'child answer']);
+ // Same day, distinct ids → distinct pages (slug is derived from sessionId).
+ expect(buildTranscriptSlug('codex', T1, { sessionId: child.meta.sessionId })).not.toBe(
+ buildTranscriptSlug('codex', T0, { sessionId: parent.meta.sessionId }),
+ );
+ });
+
test('a rollout within budget is read whole and not marked truncated', async () => {
const { diag } = await drain(codexAdapter.parse(CODEX_FIXTURE));
expect(diag.truncated).toBe(false);
@@ -368,7 +417,7 @@ describe('codexAdapter', () => {
const { sessions, diag } = await drain(codexAdapter.parse(CODEX_FIXTURE));
expect(sessions).toHaveLength(1);
const s = sessions[0];
- expect(s.meta.sessionId).toBe('codex-fixture-session-1');
+ expect(s.meta.sessionId).toBe('rollout-1'); // payload.id (per-thread), not the root session_id (#4981)
expect(s.meta.cwd).toBe('/home/alice-example/agent-workspace');
expect(s.meta.startedAt).toBe('2026-08-02T09:00:00.000Z');
expect(s.messages.map((m) => m.role)).toEqual(['user', 'assistant', 'user', 'assistant']);
diff --git a/test/transcripts-claude-code-workflow-drift.test.ts b/test/transcripts-claude-code-workflow-drift.test.ts
new file mode 100644
index 0000000000..12349d4573
--- /dev/null
+++ b/test/transcripts-claude-code-workflow-drift.test.ts
@@ -0,0 +1,164 @@
+/**
+ * Claude Code workflow-run artifacts must not read as host-format drift.
+ *
+ * `gbrain transcripts ingest` reported "DRIFT WARNING: 27 file(s) parsed to
+ * zero sessions" on a real brain, and every one was a false positive:
+ *
+ * 1. 22 subagent logs at `<session>/subagents/workflows/<wf>/agent-<id>.jsonl`.
+ * isClaudeCodeSubagentFile checked the IMMEDIATE parent for `subagents`,
+ * so the workflow nesting slipped past the filter it was written for.
+ * 2. 5 title/metadata-only session stubs (`last-prompt` + `custom-title`,
+ * no turn records at all). The claude-code adapter never set
+ * `expectedEmpty`, which the drift predicate
+ * (`bytesRead > 0 && sessions === 0 && !expectedEmpty`) reads.
+ *
+ * Both cleared `cleanScan`, which by design holds the `--since last`
+ * watermark back — so the archive re-scanned them forever and the warning
+ * could never clear.
+ *
+ * The negative cases matter as much as the positives: turn records that stop
+ * yielding text, and files with unparseable lines, MUST still drift.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ claudeCodeAdapter,
+ isClaudeCodeSubagentFile,
+} from '../src/core/transcripts/claude-code.ts';
+import type { FileDiagnostics } from '../src/core/transcripts/types.ts';
+
+let dir: string;
+
+/** Drain the adapter generator and hand back its FileDiagnostics return. */
+async function diagnose(path: string): Promise<FileDiagnostics> {
+ const gen = claudeCodeAdapter.parse(path);
+ let step = await gen.next();
+ while (!step.done) step = await gen.next();
+ return step.value;
+}
+
+function write(name: string, lines: unknown[]): string {
+ const p = join(dir, name);
+ writeFileSync(p, lines.map((l) => JSON.stringify(l)).join('\n') + '\n');
+ return p;
+}
+
+beforeAll(() => {
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-wf-drift-'));
+ mkdirSync(join(dir, 'nested'), { recursive: true });
+});
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+const SESS = '/Users/me/.claude/projects/-Users-me-proj/9e1f3d87-95f6-46bc-bb48-97404d8d1890';
+
+describe('workflow-nested subagent logs are recognized', () => {
+ test('agent log inside a workflow run dir is a subagent file', () => {
+ expect(
+ isClaudeCodeSubagentFile(`${SESS}/subagents/workflows/wf_e37e5872-c19/agent-af0c665.jsonl`),
+ ).toBe(true);
+ });
+
+ test('the immediate-parent cases keep their existing behaviour', () => {
+ expect(isClaudeCodeSubagentFile(`${SESS}/subagents/agent-a5364e5.jsonl`)).toBe(true);
+ // A real session directly under subagents/ stays discoverable.
+ expect(isClaudeCodeSubagentFile(`${SESS}/subagents/61c79e08-716f-44df.jsonl`)).toBe(false);
+ // A project SLUG containing "subagents" is not a subagents segment.
+ expect(
+ isClaudeCodeSubagentFile('/Users/me/.claude/projects/-Users-me-subagents/agent-abc.jsonl'),
+ ).toBe(false);
+ });
+
+ test('workflow journal is an artifact; a session under subagents/ is not', async () => {
+ // Imported dynamically, not statically: this export does not exist before
+ // the fix, and a static named import would crash the whole FILE with a
+ // SyntaxError — the vacuous-failure class CONTRIBUTING.md rejects. Loading
+ // the module by value lets the other tests in this file run (and fail on
+ // their own assertions) against pre-fix source.
+ const mod = await import('../src/core/transcripts/claude-code.ts');
+ const isArtifact = mod.isClaudeCodeWorkflowArtifactFile;
+ expect(typeof isArtifact).toBe('function');
+ expect(isArtifact(`${SESS}/subagents/workflows/wf_e37e5872-c19/journal.jsonl`)).toBe(true);
+ expect(isArtifact(`${SESS}/subagents/61c79e08-716f-44df.jsonl`)).toBe(false);
+ expect(isArtifact(`${SESS}/subagents/workflows`)).toBe(false);
+ });
+});
+
+describe('expectedEmpty separates understood-empty from drift', () => {
+ test('a title/metadata-only stub is understood, not drift', async () => {
+ const p = write('meta-only.jsonl', [
+ { sessionId: 's1', type: 'last-prompt', prompt: 'hi' },
+ { sessionId: 's1', type: 'custom-title', title: 'Some title' },
+ { sessionId: 's1', type: 'ai-title', title: 'Another' },
+ ]);
+ const d = await diagnose(p);
+ expect(d.sessions).toBe(0);
+ expect(d.bytesRead).toBeGreaterThan(0);
+ expect(d.expectedEmpty).toBe(true);
+ });
+
+ test('an all-sidechain subagent log is understood, not drift', async () => {
+ const p = write('sidechain.jsonl', [
+ {
+ sessionId: 's2',
+ type: 'user',
+ isSidechain: true,
+ message: { role: 'user', content: 'sub work' },
+ },
+ {
+ sessionId: 's2',
+ type: 'assistant',
+ isSidechain: true,
+ message: { role: 'assistant', content: 'sub reply' },
+ },
+ ]);
+ const d = await diagnose(p);
+ expect(d.sessions).toBe(0);
+ expect(d.expectedEmpty).toBe(true);
+ });
+
+ test('turn records that yield no text STILL drift', async () => {
+ // The real regression signal: the host kept `type: user` but changed the
+ // message shape. Marking this expectedEmpty would silence exactly the
+ // breakage the drift counter exists to catch.
+ const p = write('shape-drift.jsonl', [
+ { sessionId: 's3', type: 'last-prompt', prompt: 'hi' },
+ { sessionId: 's3', type: 'user', message: null },
+ { sessionId: 's3', type: 'assistant', message: null },
+ ]);
+ const d = await diagnose(p);
+ expect(d.sessions).toBe(0);
+ expect(d.expectedEmpty).toBeFalsy();
+ });
+
+ test('unparseable lines STILL drift', async () => {
+ const p = join(dir, 'malformed.jsonl');
+ writeFileSync(p, '{"sessionId":"s4","type":"last-prompt"}\nnot json at all\n');
+ const d = await diagnose(p);
+ expect(d.sessions).toBe(0);
+ expect(d.skippedLines).toBeGreaterThan(0);
+ expect(d.expectedEmpty).toBeFalsy();
+ });
+
+ test('a real session still imports and is not marked empty', async () => {
+ const p = write('real.jsonl', [
+ { sessionId: 's5', type: 'last-prompt', prompt: 'hi' },
+ {
+ sessionId: 's5',
+ type: 'user',
+ timestamp: '2026-09-08T10:00:00.000Z',
+ message: { role: 'user', content: 'hello there' },
+ },
+ {
+ sessionId: 's5',
+ type: 'assistant',
+ timestamp: '2026-09-08T10:00:01.000Z',
+ message: { role: 'assistant', content: 'hi back' },
+ },
+ ]);
+ const d = await diagnose(p);
+ expect(d.sessions).toBe(1);
+ expect(d.expectedEmpty).toBeFalsy();
+ });
+});
diff --git a/test/transcripts-nul.test.ts b/test/transcripts-nul.test.ts
index 9b8345c88b..e3ac244c35 100644
--- a/test/transcripts-nul.test.ts
+++ b/test/transcripts-nul.test.ts
@@ -46,7 +46,11 @@ afterEach(() => {
const NO_PATTERNS = { userPatternsPath: '/nonexistent-patterns.txt' };
-/** Minimal codex-rollout JSONL: session_meta + one user turn + one reply. */
+/**
+ * Minimal codex-rollout JSONL: session_meta + one user turn + one reply.
+ * A ROOT rollout: payload.id === payload.session_id (#4981 keys identity on
+ * payload.id; a differing id would model a forked child thread with its own page).
+ */
function writeCodexSession(
name: string,
sessionId: string,
@@ -58,7 +62,7 @@ function writeCodexSession(
JSON.stringify({
timestamp: startIso,
type: 'session_meta',
- payload: { id: name, session_id: sessionId, timestamp: startIso, cwd },
+ payload: { id: sessionId, session_id: sessionId, timestamp: startIso, cwd },
}),
JSON.stringify({
timestamp: startIso,